Chromium Code Reviews| OLD | NEW |
|---|---|
| 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | 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 | 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
| 4 | 4 |
| 5 #include "chrome/browser/chrome_to_mobile_service.h" | 5 #include "chrome/browser/chrome_to_mobile_service.h" |
| 6 | 6 |
| 7 #include "base/bind.h" | 7 #include "base/bind.h" |
| 8 #include "base/command_line.h" | 8 #include "base/command_line.h" |
| 9 #include "base/file_util.h" | 9 #include "base/file_util.h" |
| 10 #include "base/guid.h" | 10 #include "base/guid.h" |
| 11 #include "base/json/json_reader.h" | 11 #include "base/json/json_reader.h" |
| 12 #include "base/json/json_writer.h" | 12 #include "base/json/json_writer.h" |
| 13 #include "base/metrics/histogram.h" | 13 #include "base/metrics/histogram.h" |
| 14 #include "base/stringprintf.h" | |
| 15 #include "base/utf_string_conversions.h" | 14 #include "base/utf_string_conversions.h" |
| 16 #include "chrome/app/chrome_command_ids.h" | 15 #include "chrome/app/chrome_command_ids.h" |
| 17 #include "chrome/browser/content_settings/cookie_settings.h" | |
| 18 #include "chrome/browser/prefs/pref_service.h" | 16 #include "chrome/browser/prefs/pref_service.h" |
| 19 #include "chrome/browser/printing/cloud_print/cloud_print_url.h" | 17 #include "chrome/browser/printing/cloud_print/cloud_print_url.h" |
| 20 #include "chrome/browser/profiles/profile.h" | 18 #include "chrome/browser/profiles/profile.h" |
| 21 #include "chrome/browser/signin/token_service.h" | 19 #include "chrome/browser/signin/token_service.h" |
| 22 #include "chrome/browser/signin/token_service_factory.h" | 20 #include "chrome/browser/signin/token_service_factory.h" |
| 21 #include "chrome/browser/sync/profile_sync_service.h" | |
| 22 #include "chrome/browser/sync/profile_sync_service_factory.h" | |
| 23 #include "chrome/browser/ui/browser.h" | 23 #include "chrome/browser/ui/browser.h" |
| 24 #include "chrome/browser/ui/browser_command_controller.h" | 24 #include "chrome/browser/ui/browser_command_controller.h" |
| 25 #include "chrome/browser/ui/browser_finder.h" | 25 #include "chrome/browser/ui/browser_finder.h" |
| 26 #include "chrome/browser/ui/browser_list.h" | 26 #include "chrome/browser/ui/browser_list.h" |
| 27 #include "chrome/browser/ui/browser_navigator.h" | 27 #include "chrome/browser/ui/browser_navigator.h" |
| 28 #include "chrome/browser/ui/browser_tabstrip.h" | 28 #include "chrome/browser/ui/browser_tabstrip.h" |
| 29 #include "chrome/common/chrome_notification_types.h" | 29 #include "chrome/common/chrome_notification_types.h" |
| 30 #include "chrome/common/chrome_switches.h" | 30 #include "chrome/common/chrome_switches.h" |
| 31 #include "chrome/common/cloud_print/cloud_print_helpers.h" | 31 #include "chrome/common/cloud_print/cloud_print_helpers.h" |
| 32 #include "chrome/common/net/gaia/gaia_constants.h" | 32 #include "chrome/common/net/gaia/gaia_constants.h" |
| 33 #include "chrome/common/net/gaia/gaia_urls.h" | 33 #include "chrome/common/net/gaia/gaia_urls.h" |
| 34 #include "chrome/common/net/gaia/oauth2_access_token_fetcher.h" | 34 #include "chrome/common/net/gaia/oauth2_access_token_fetcher.h" |
| 35 #include "chrome/common/pref_names.h" | 35 #include "chrome/common/pref_names.h" |
| 36 #include "chrome/common/url_constants.h" | 36 #include "chrome/common/url_constants.h" |
| 37 #include "content/public/browser/browser_thread.h" | 37 #include "content/public/browser/browser_thread.h" |
| 38 #include "content/public/browser/notification_details.h" | 38 #include "content/public/browser/notification_details.h" |
| 39 #include "content/public/browser/notification_source.h" | 39 #include "content/public/browser/notification_source.h" |
| 40 #include "content/public/browser/web_contents.h" | 40 #include "content/public/browser/web_contents.h" |
| 41 #include "google/cacheinvalidation/include/types.h" | |
| 42 #include "google/cacheinvalidation/types.pb.h" | |
| 41 #include "net/base/escape.h" | 43 #include "net/base/escape.h" |
| 42 #include "net/base/load_flags.h" | 44 #include "net/base/load_flags.h" |
| 43 #include "net/url_request/url_fetcher.h" | 45 #include "net/url_request/url_fetcher.h" |
| 44 #include "net/url_request/url_request_context_getter.h" | 46 #include "net/url_request/url_request_context_getter.h" |
| 47 #include "sync/notifier/invalidation_util.h" | |
| 45 | 48 |
| 46 namespace { | 49 namespace { |
| 47 | 50 |
| 48 // The default enabled/disabled state of the Chrome To Mobile feature. | 51 // The default enabled/disabled state of the Chrome To Mobile feature. |
| 49 const bool kChromeToMobileEnabled = true; | 52 const bool kChromeToMobileEnabled = true; |
| 50 | 53 |
| 51 // The maximum number of retries for the URLFetcher requests. | 54 // The maximum number of retries for the URLFetcher requests. |
| 52 const size_t kMaxRetries = 1; | 55 const size_t kMaxRetries = 1; |
| 53 | 56 |
| 54 // The number of hours to delay before retrying authentication on failure. | 57 // The number of hours to delay before retrying authentication on failure. |
| 55 const size_t kAuthRetryDelayHours = 6; | 58 const size_t kAuthRetryDelayHours = 6; |
| 56 | 59 |
| 57 // The number of hours before subsequent search requests are allowed. | 60 // The number of hours before subsequent search requests are allowed. |
| 58 // This value is used to throttle expensive cloud print search requests. | 61 // This value is used to throttle expensive cloud print search requests. |
| 59 // Note that this limitation does not hold across application restarts. | 62 // Note that this limitation does not hold across application restarts. |
| 60 const int kSearchRequestDelayHours = 24; | 63 const int kSearchRequestDelayHours = 24; |
| 61 | 64 |
| 65 // The sync invalidation object ID for Chrome to Mobile's mobile device list. | |
| 66 // This corresponds with cloud print's server-side invalidation object ID. | |
| 67 // Meaning: "U" == "User", "CM" == "Chrome to Mobile", "MLST" == "Mobile LiST". | |
| 68 const char kSyncInvalidationObjectIdChromeToMobileDeviceList[] = "UCMMLST"; | |
| 69 | |
| 62 // The cloud print OAuth2 scope and 'printer' type of compatible mobile devices. | 70 // The cloud print OAuth2 scope and 'printer' type of compatible mobile devices. |
| 63 const char kCloudPrintAuth[] = "https://www.googleapis.com/auth/cloudprint"; | 71 const char kCloudPrintAuth[] = "https://www.googleapis.com/auth/cloudprint"; |
| 64 const char kTypeAndroid[] = "ANDROID_CHROME_SNAPSHOT"; | 72 const char kTypeAndroid[] = "ANDROID_CHROME_SNAPSHOT"; |
| 65 const char kTypeIOS[] = "IOS_CHROME_SNAPSHOT"; | 73 const char kTypeIOS[] = "IOS_CHROME_SNAPSHOT"; |
| 66 | 74 |
| 67 // The account info URL pattern and strings to check for cloud print access. | |
| 68 // The 'key=' query parameter is used for caching; supply a random number. | |
| 69 // The 'rv=2' query parameter requests a JSON response; use 'rv=1' for XML. | |
| 70 const char kAccountInfoURL[] = | |
| 71 "https://clients1.google.com/tbproxy/getaccountinfo?key=%s&rv=2&%s"; | |
| 72 const char kAccountServicesKey[] = "services"; | |
| 73 const char kCloudPrintSerivceValue[] = "cprt"; | |
| 74 | |
| 75 // The Chrome To Mobile requestor type; used by services for filtering. | 75 // The Chrome To Mobile requestor type; used by services for filtering. |
| 76 const char kChromeToMobileRequestor[] = "requestor=chrome-to-mobile"; | 76 const char kChromeToMobileRequestor[] = "requestor=chrome-to-mobile"; |
| 77 | 77 |
| 78 // Get the job type string for a cloud print job submission. | 78 // Get the job type string for a cloud print job submission. |
| 79 std::string GetType(const ChromeToMobileService::JobData& data) { | 79 std::string GetType(const ChromeToMobileService::JobData& data) { |
| 80 if (data.type == ChromeToMobileService::URL) | 80 if (data.type == ChromeToMobileService::URL) |
| 81 return "url"; | 81 return "url"; |
| 82 if (data.type == ChromeToMobileService::DELAYED_SNAPSHOT) | 82 if (data.type == ChromeToMobileService::DELAYED_SNAPSHOT) |
| 83 return "url_with_delayed_snapshot"; | 83 return "url_with_delayed_snapshot"; |
| 84 DCHECK_EQ(data.type, ChromeToMobileService::SNAPSHOT); | 84 DCHECK_EQ(data.type, ChromeToMobileService::SNAPSHOT); |
| (...skipping 88 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 173 if (command_line->HasSwitch(switches::kEnableChromeToMobile)) | 173 if (command_line->HasSwitch(switches::kEnableChromeToMobile)) |
| 174 return true; | 174 return true; |
| 175 | 175 |
| 176 return kChromeToMobileEnabled; | 176 return kChromeToMobileEnabled; |
| 177 } | 177 } |
| 178 | 178 |
| 179 // static | 179 // static |
| 180 void ChromeToMobileService::RegisterUserPrefs(PrefService* prefs) { | 180 void ChromeToMobileService::RegisterUserPrefs(PrefService* prefs) { |
| 181 prefs->RegisterListPref(prefs::kChromeToMobileDeviceList, | 181 prefs->RegisterListPref(prefs::kChromeToMobileDeviceList, |
| 182 PrefService::UNSYNCABLE_PREF); | 182 PrefService::UNSYNCABLE_PREF); |
| 183 prefs->RegisterInt64Pref(prefs::kChromeToMobileTimestamp, 0, | |
| 184 PrefService::UNSYNCABLE_PREF); | |
| 185 } | 183 } |
| 186 | 184 |
| 187 ChromeToMobileService::ChromeToMobileService(Profile* profile) | 185 ChromeToMobileService::ChromeToMobileService(Profile* profile) |
| 188 : ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)), | 186 : ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)), |
| 189 profile_(profile), | 187 profile_(profile), |
| 190 cloud_print_url_(new CloudPrintURL(profile)), | 188 sync_invalidation_enabled_(false), |
| 191 cloud_print_accessible_(false) { | 189 cloud_print_url_(new CloudPrintURL(profile)) { |
| 192 // TODO(msw): Fix GMock tests, which lack profiles (http://crbug.com/122183). | 190 RegisterForDeviceListInvalidations(); |
| 193 if (profile_) { | |
| 194 // Get an access token as soon as the Gaia login refresh token is available. | |
| 195 TokenService* service = TokenServiceFactory::GetForProfile(profile_); | |
| 196 registrar_.Add(this, chrome::NOTIFICATION_TOKEN_AVAILABLE, | |
| 197 content::Source<TokenService>(service)); | |
| 198 if (service->HasOAuthLoginToken()) | |
| 199 RequestAccessToken(); | |
| 200 } | |
| 201 } | 191 } |
| 202 | 192 |
| 203 ChromeToMobileService::~ChromeToMobileService() { | 193 ChromeToMobileService::~ChromeToMobileService() { |
| 204 while (!snapshots_.empty()) | 194 while (!snapshots_.empty()) |
| 205 DeleteSnapshot(*snapshots_.begin()); | 195 DeleteSnapshot(*snapshots_.begin()); |
| 196 if (profile_) { | |
| 197 ProfileSyncServiceFactory::GetForProfile(profile_)-> | |
| 198 UnregisterInvalidationHandler(this); | |
| 199 } | |
| 206 } | 200 } |
| 207 | 201 |
| 208 bool ChromeToMobileService::HasMobiles() const { | 202 bool ChromeToMobileService::HasMobiles() const { |
| 209 return !GetMobiles()->empty(); | 203 return sync_invalidation_enabled_ && !GetMobiles()->empty(); |
| 210 } | 204 } |
| 211 | 205 |
| 212 const base::ListValue* ChromeToMobileService::GetMobiles() const { | 206 const base::ListValue* ChromeToMobileService::GetMobiles() const { |
| 213 return profile_->GetPrefs()->GetList(prefs::kChromeToMobileDeviceList); | 207 return sync_invalidation_enabled_ ? |
| 214 } | 208 profile_->GetPrefs()->GetList(prefs::kChromeToMobileDeviceList) : NULL; |
| 215 | |
| 216 void ChromeToMobileService::RequestMobileListUpdate() { | |
| 217 if (access_token_.empty()) | |
| 218 RequestAccessToken(); | |
| 219 else if (cloud_print_accessible_) | |
| 220 RequestDeviceSearch(); | |
| 221 } | 209 } |
| 222 | 210 |
| 223 void ChromeToMobileService::GenerateSnapshot(Browser* browser, | 211 void ChromeToMobileService::GenerateSnapshot(Browser* browser, |
| 224 base::WeakPtr<Observer> observer) { | 212 base::WeakPtr<Observer> observer) { |
| 225 // Callback SnapshotFileCreated from CreateSnapshotFile to continue. | 213 // Callback SnapshotFileCreated from CreateSnapshotFile to continue. |
| 226 CreateSnapshotFileCallback callback = | 214 CreateSnapshotFileCallback callback = |
| 227 base::Bind(&ChromeToMobileService::SnapshotFileCreated, | 215 base::Bind(&ChromeToMobileService::SnapshotFileCreated, |
| 228 weak_ptr_factory_.GetWeakPtr(), observer, | 216 weak_ptr_factory_.GetWeakPtr(), observer, |
| 229 browser->session_id().id()); | 217 browser->session_id().id()); |
| 230 // Create a temporary file via the blocking pool for snapshot storage. | 218 // Create a temporary file via the blocking pool for snapshot storage. |
| 231 if (!content::BrowserThread::PostBlockingPoolTask(FROM_HERE, | 219 if (!content::BrowserThread::PostBlockingPoolTask(FROM_HERE, |
| 232 base::Bind(&CreateSnapshotFile, callback))) { | 220 base::Bind(&CreateSnapshotFile, callback))) { |
| 233 NOTREACHED(); | 221 NOTREACHED(); |
| 234 } | 222 } |
| 235 } | 223 } |
| 236 | 224 |
| 237 void ChromeToMobileService::SendToMobile(const base::DictionaryValue& mobile, | 225 void ChromeToMobileService::SendToMobile(const base::DictionaryValue* mobile, |
| 238 const FilePath& snapshot, | 226 const FilePath& snapshot, |
| 239 Browser* browser, | 227 Browser* browser, |
| 240 base::WeakPtr<Observer> observer) { | 228 base::WeakPtr<Observer> observer) { |
| 229 if (access_token_.empty()) { | |
| 230 // Enqueue this task to perform after obtaining an access token. | |
| 231 task_queue_.push(base::Bind(&ChromeToMobileService::SendToMobile, | |
| 232 weak_ptr_factory_.GetWeakPtr(), base::Owned(mobile->DeepCopy()), | |
| 233 snapshot, browser, observer)); | |
| 234 RequestAccessToken(); | |
| 235 return; | |
| 236 } | |
| 237 | |
| 241 LogMetric(SENDING_URL); | 238 LogMetric(SENDING_URL); |
| 242 | 239 |
| 243 JobData data; | 240 JobData data; |
| 244 std::string mobile_os; | 241 std::string mobile_os; |
| 245 if (!mobile.GetString("type", &mobile_os)) | 242 if (!mobile->GetString("type", &mobile_os)) |
| 246 NOTREACHED(); | 243 NOTREACHED(); |
| 247 data.mobile_os = (mobile_os.compare(kTypeAndroid) == 0) ? | 244 data.mobile_os = (mobile_os.compare(kTypeAndroid) == 0) ? |
| 248 ChromeToMobileService::ANDROID : ChromeToMobileService::IOS; | 245 ChromeToMobileService::ANDROID : ChromeToMobileService::IOS; |
| 249 if (!mobile.GetString("id", &data.mobile_id)) | 246 if (!mobile->GetString("id", &data.mobile_id)) |
| 250 NOTREACHED(); | 247 NOTREACHED(); |
| 251 content::WebContents* web_contents = chrome::GetActiveWebContents(browser); | 248 content::WebContents* web_contents = chrome::GetActiveWebContents(browser); |
| 252 data.url = web_contents->GetURL(); | 249 data.url = web_contents->GetURL(); |
| 253 data.title = web_contents->GetTitle(); | 250 data.title = web_contents->GetTitle(); |
| 254 data.snapshot = snapshot; | 251 data.snapshot = snapshot; |
| 255 data.snapshot_id = base::GenerateGUID(); | 252 data.snapshot_id = base::GenerateGUID(); |
| 256 data.type = !snapshot.empty() ? DELAYED_SNAPSHOT : URL; | 253 data.type = !snapshot.empty() ? DELAYED_SNAPSHOT : URL; |
| 257 | 254 |
| 258 net::URLFetcher* submit_url = CreateRequest(data); | 255 net::URLFetcher* submit_url = CreateRequest(data); |
| 259 request_observer_map_[submit_url] = observer; | 256 request_observer_map_[submit_url] = observer; |
| (...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 294 } | 291 } |
| 295 | 292 |
| 296 void ChromeToMobileService::LearnMore(Browser* browser) const { | 293 void ChromeToMobileService::LearnMore(Browser* browser) const { |
| 297 LogMetric(LEARN_MORE_CLICKED); | 294 LogMetric(LEARN_MORE_CLICKED); |
| 298 chrome::NavigateParams params(browser, | 295 chrome::NavigateParams params(browser, |
| 299 GURL(chrome::kChromeToMobileLearnMoreURL), content::PAGE_TRANSITION_LINK); | 296 GURL(chrome::kChromeToMobileLearnMoreURL), content::PAGE_TRANSITION_LINK); |
| 300 params.disposition = NEW_FOREGROUND_TAB; | 297 params.disposition = NEW_FOREGROUND_TAB; |
| 301 chrome::Navigate(¶ms); | 298 chrome::Navigate(¶ms); |
| 302 } | 299 } |
| 303 | 300 |
| 304 void ChromeToMobileService::OnURLFetchComplete( | 301 void ChromeToMobileService::OnURLFetchComplete(const net::URLFetcher* source) { |
| 305 const net::URLFetcher* source) { | 302 if (source == search_request_.get()) |
| 306 if (source == account_info_request_.get()) | |
| 307 HandleAccountInfoResponse(); | |
| 308 else if (source == search_request_.get()) | |
| 309 HandleSearchResponse(); | 303 HandleSearchResponse(); |
| 310 else | 304 else |
| 311 HandleSubmitResponse(source); | 305 HandleSubmitResponse(source); |
| 312 } | 306 } |
| 313 | 307 |
| 314 void ChromeToMobileService::Observe( | 308 void ChromeToMobileService::Observe( |
| 315 int type, | 309 int type, |
| 316 const content::NotificationSource& source, | 310 const content::NotificationSource& source, |
| 317 const content::NotificationDetails& details) { | 311 const content::NotificationDetails& details) { |
| 318 DCHECK_EQ(type, chrome::NOTIFICATION_TOKEN_AVAILABLE); | 312 DCHECK_EQ(type, chrome::NOTIFICATION_TOKEN_AVAILABLE); |
| 319 TokenService::TokenAvailableDetails* token_details = | 313 TokenService::TokenAvailableDetails* token_details = |
| 320 content::Details<TokenService::TokenAvailableDetails>(details).ptr(); | 314 content::Details<TokenService::TokenAvailableDetails>(details).ptr(); |
| 315 // Invalidate the cloud print access token on Gaia login token updates. | |
| 321 if (token_details->service() == GaiaConstants::kGaiaOAuth2LoginRefreshToken) | 316 if (token_details->service() == GaiaConstants::kGaiaOAuth2LoginRefreshToken) |
| 322 RequestAccessToken(); | 317 access_token_.clear(); |
| 323 } | 318 } |
| 324 | 319 |
| 325 void ChromeToMobileService::OnGetTokenSuccess( | 320 void ChromeToMobileService::OnGetTokenSuccess( |
| 326 const std::string& access_token, | 321 const std::string& access_token, |
| 327 const base::Time& expiration_time) { | 322 const base::Time& expiration_time) { |
| 328 DCHECK(!access_token.empty()); | 323 DCHECK(!access_token.empty()); |
| 329 access_token_fetcher_.reset(); | 324 access_token_fetcher_.reset(); |
| 330 auth_retry_timer_.Stop(); | 325 auth_retry_timer_.Stop(); |
| 331 access_token_ = access_token; | 326 access_token_ = access_token; |
| 332 RequestAccountInfo(); | 327 |
| 328 while (!task_queue_.empty()) { | |
| 329 // Post all tasks that were queued and waiting on a valid access token. | |
| 330 if (!content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, | |
| 331 task_queue_.front())) { | |
| 332 NOTREACHED(); | |
| 333 } | |
| 334 task_queue_.pop(); | |
| 335 } | |
| 333 } | 336 } |
| 334 | 337 |
| 335 void ChromeToMobileService::OnGetTokenFailure( | 338 void ChromeToMobileService::OnGetTokenFailure( |
| 336 const GoogleServiceAuthError& error) { | 339 const GoogleServiceAuthError& error) { |
| 337 access_token_fetcher_.reset(); | 340 access_token_fetcher_.reset(); |
| 338 auth_retry_timer_.Stop(); | 341 auth_retry_timer_.Stop(); |
| 342 | |
| 343 // TODO(msw): UMA Logging access token success/failure... | |
| 344 // TODO(msw): Special handling if |task_queue| is waiting? | |
| 339 auth_retry_timer_.Start( | 345 auth_retry_timer_.Start( |
| 340 FROM_HERE, base::TimeDelta::FromHours(kAuthRetryDelayHours), | 346 FROM_HERE, base::TimeDelta::FromHours(kAuthRetryDelayHours), |
| 341 this, &ChromeToMobileService::RequestAccessToken); | 347 this, &ChromeToMobileService::RequestAccessToken); |
| 342 } | 348 } |
| 343 | 349 |
| 350 void ChromeToMobileService::OnNotificationsEnabled() { | |
| 351 sync_invalidation_enabled_ = true; | |
| 352 UpdateCommandState(); | |
| 353 } | |
| 354 | |
| 355 void ChromeToMobileService::OnNotificationsDisabled( | |
| 356 syncer::NotificationsDisabledReason reason) { | |
| 357 sync_invalidation_enabled_ = false; | |
| 358 UpdateCommandState(); | |
| 359 } | |
| 360 | |
| 361 void ChromeToMobileService::OnIncomingNotification( | |
| 362 const syncer::ObjectIdPayloadMap& id_payloads, | |
| 363 syncer::IncomingNotificationSource source) { | |
| 364 DCHECK_EQ(id_payloads.size(), 1U); | |
| 365 DCHECK_EQ(id_payloads.count(invalidation::ObjectId( | |
| 366 ipc::invalidation::ObjectSource::CHROME_COMPONENTS, | |
| 367 kSyncInvalidationObjectIdChromeToMobileDeviceList)), 1U); | |
| 368 RequestDeviceSearch(); | |
| 369 } | |
| 370 | |
| 344 void ChromeToMobileService::UpdateCommandState() const { | 371 void ChromeToMobileService::UpdateCommandState() const { |
| 345 // Ensure the feature is not disabled by commandline options. | 372 // Ensure the feature is not disabled by commandline options. |
| 346 DCHECK(IsChromeToMobileEnabled()); | 373 DCHECK(IsChromeToMobileEnabled()); |
| 347 const bool has_mobiles = HasMobiles(); | 374 const bool has_mobiles = HasMobiles(); |
| 348 for (BrowserList::const_iterator i = BrowserList::begin(); | 375 for (BrowserList::const_iterator i = BrowserList::begin(); |
| 349 i != BrowserList::end(); ++i) { | 376 i != BrowserList::end(); ++i) { |
| 350 Browser* browser = *i; | 377 Browser* browser = *i; |
| 351 if (browser->profile() == profile_) | 378 if (browser->profile() == profile_) |
| 352 browser->command_controller()->SendToMobileStateChanged(has_mobiles); | 379 browser->command_controller()->SendToMobileStateChanged(has_mobiles); |
| 353 } | 380 } |
| (...skipping 73 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 427 return; | 454 return; |
| 428 } | 455 } |
| 429 cloud_print::AddMultipartValueForUpload("content", file, bound, | 456 cloud_print::AddMultipartValueForUpload("content", file, bound, |
| 430 "text/mhtml", &post); | 457 "text/mhtml", &post); |
| 431 | 458 |
| 432 post.append("--" + bound + "--\r\n"); | 459 post.append("--" + bound + "--\r\n"); |
| 433 request->SetUploadData("multipart/form-data; boundary=" + bound, post); | 460 request->SetUploadData("multipart/form-data; boundary=" + bound, post); |
| 434 request->Start(); | 461 request->Start(); |
| 435 } | 462 } |
| 436 | 463 |
| 464 void ChromeToMobileService::RegisterForDeviceListInvalidations() { | |
| 465 ProfileSyncService* profile_sync_service = | |
| 466 ProfileSyncServiceFactory::GetForProfile(profile_); | |
| 467 profile_sync_service->RegisterInvalidationHandler(this); | |
|
akalin
2012/08/17 22:09:33
seems iffy to have this here instead of in the con
msw
2012/08/18 00:09:56
Done.
| |
| 468 syncer::ObjectIdSet ids; | |
| 469 ids.insert(invalidation::ObjectId( | |
| 470 ipc::invalidation::ObjectSource::CHROME_COMPONENTS, | |
| 471 kSyncInvalidationObjectIdChromeToMobileDeviceList)); | |
| 472 profile_sync_service->UpdateRegisteredInvalidationIds(this, ids); | |
| 473 } | |
| 474 | |
| 437 void ChromeToMobileService::RequestAccessToken() { | 475 void ChromeToMobileService::RequestAccessToken() { |
| 476 // Register to observe Gaia login refresh token updates. | |
| 477 TokenService* token_service = TokenServiceFactory::GetForProfile(profile_); | |
| 478 if (registrar_.IsEmpty()) | |
| 479 registrar_.Add(this, chrome::NOTIFICATION_TOKEN_AVAILABLE, | |
| 480 content::Source<TokenService>(token_service)); | |
| 481 | |
| 438 // Deny concurrent requests and bail without a valid Gaia login refresh token. | 482 // Deny concurrent requests and bail without a valid Gaia login refresh token. |
| 439 TokenService* token_service = TokenServiceFactory::GetForProfile(profile_); | |
| 440 if (access_token_fetcher_.get() || !token_service->HasOAuthLoginToken()) | 483 if (access_token_fetcher_.get() || !token_service->HasOAuthLoginToken()) |
| 441 return; | 484 return; |
| 442 | 485 |
| 443 auth_retry_timer_.Stop(); | 486 auth_retry_timer_.Stop(); |
| 444 access_token_fetcher_.reset( | 487 access_token_fetcher_.reset( |
| 445 new OAuth2AccessTokenFetcher(this, profile_->GetRequestContext())); | 488 new OAuth2AccessTokenFetcher(this, profile_->GetRequestContext())); |
| 446 GaiaUrls* gaia_urls = GaiaUrls::GetInstance(); | 489 GaiaUrls* gaia_urls = GaiaUrls::GetInstance(); |
| 447 access_token_fetcher_->Start(gaia_urls->oauth2_chrome_client_id(), | 490 access_token_fetcher_->Start(gaia_urls->oauth2_chrome_client_id(), |
| 448 gaia_urls->oauth2_chrome_client_secret(), | 491 gaia_urls->oauth2_chrome_client_secret(), |
| 449 token_service->GetOAuth2LoginRefreshToken(), | 492 token_service->GetOAuth2LoginRefreshToken(), |
| 450 std::vector<std::string>(1, kCloudPrintAuth)); | 493 std::vector<std::string>(1, kCloudPrintAuth)); |
| 451 } | 494 } |
| 452 | 495 |
| 453 void ChromeToMobileService::RequestAccountInfo() { | 496 void ChromeToMobileService::RequestDeviceSearch() { |
| 454 // Deny concurrent requests. | 497 DCHECK(sync_invalidation_enabled_); |
| 455 if (account_info_request_.get()) | 498 if (access_token_.empty()) { |
| 456 return; | 499 // Enqueue this task to perform after obtaining an access token. |
| 457 | 500 task_queue_.push(base::Bind(&ChromeToMobileService::RequestDeviceSearch, |
| 458 std::string url_string = StringPrintf(kAccountInfoURL, | 501 weak_ptr_factory_.GetWeakPtr())); |
| 459 base::GenerateGUID().c_str(), kChromeToMobileRequestor); | 502 RequestAccessToken(); |
| 460 GURL url(url_string); | |
| 461 | |
| 462 // Account information is read from the profile's cookie. If cookies are | |
| 463 // blocked, access cloud print directly to list any potential devices. | |
| 464 scoped_refptr<CookieSettings> cookie_settings = | |
| 465 CookieSettings::Factory::GetForProfile(profile_); | |
| 466 if (cookie_settings && !cookie_settings->IsReadingCookieAllowed(url, url)) { | |
| 467 cloud_print_accessible_ = true; | |
| 468 RequestMobileListUpdate(); | |
| 469 return; | 503 return; |
| 470 } | 504 } |
| 471 | 505 |
| 472 account_info_request_.reset( | 506 // Deny concurrent requests. |
| 473 net::URLFetcher::Create(url, net::URLFetcher::GET, this)); | 507 if (search_request_.get()) |
| 474 account_info_request_->SetRequestContext(profile_->GetRequestContext()); | |
| 475 account_info_request_->SetMaxRetries(kMaxRetries); | |
| 476 // This request sends the user's cookie to check the cloud print service flag. | |
| 477 account_info_request_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES); | |
| 478 account_info_request_->Start(); | |
| 479 } | |
| 480 | |
| 481 void ChromeToMobileService::RequestDeviceSearch() { | |
| 482 // Deny requests if cloud print is inaccessible, and deny concurrent requests. | |
| 483 if (!cloud_print_accessible_ || search_request_.get()) | |
| 484 return; | |
| 485 | |
| 486 PrefService* prefs = profile_->GetPrefs(); | |
| 487 base::TimeTicks previous_search_time = base::TimeTicks::FromInternalValue( | |
| 488 prefs->GetInt64(prefs::kChromeToMobileTimestamp)); | |
| 489 | |
| 490 // Deny requests before the delay period has passed since the last request. | |
| 491 base::TimeDelta elapsed_time = base::TimeTicks::Now() - previous_search_time; | |
| 492 if (!previous_search_time.is_null() && | |
| 493 elapsed_time.InHours() < kSearchRequestDelayHours) | |
| 494 return; | 508 return; |
| 495 | 509 |
| 496 LogMetric(DEVICES_REQUESTED); | 510 LogMetric(DEVICES_REQUESTED); |
| 497 | 511 |
| 498 const GURL service_url(cloud_print_url_->GetCloudPrintServiceURL()); | 512 const GURL service_url(cloud_print_url_->GetCloudPrintServiceURL()); |
| 499 search_request_.reset(net::URLFetcher::Create(GetSearchURL(service_url), | 513 search_request_.reset(net::URLFetcher::Create(GetSearchURL(service_url), |
| 500 net::URLFetcher::GET, this)); | 514 net::URLFetcher::GET, this)); |
| 501 InitRequest(search_request_.get()); | 515 InitRequest(search_request_.get()); |
| 502 search_request_->Start(); | 516 search_request_->Start(); |
| 503 } | 517 } |
| 504 | 518 |
| 505 void ChromeToMobileService::HandleAccountInfoResponse() { | |
| 506 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); | |
| 507 | |
| 508 std::string data; | |
| 509 account_info_request_->GetResponseAsString(&data); | |
| 510 account_info_request_.reset(); | |
| 511 | |
| 512 ListValue* services = NULL; | |
| 513 DictionaryValue* dictionary = NULL; | |
| 514 scoped_ptr<Value> json(base::JSONReader::Read(data)); | |
| 515 StringValue cloud_print_service(kCloudPrintSerivceValue); | |
| 516 if (json.get() && json->GetAsDictionary(&dictionary) && dictionary && | |
| 517 dictionary->GetList(kAccountServicesKey, &services) && services && | |
| 518 services->Find(cloud_print_service) != services->end()) { | |
| 519 cloud_print_accessible_ = true; | |
| 520 RequestMobileListUpdate(); | |
| 521 } | |
| 522 } | |
| 523 | |
| 524 void ChromeToMobileService::HandleSearchResponse() { | 519 void ChromeToMobileService::HandleSearchResponse() { |
| 525 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); | 520 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); |
| 526 | 521 |
| 527 std::string data; | 522 std::string data; |
| 528 search_request_->GetResponseAsString(&data); | 523 search_request_->GetResponseAsString(&data); |
| 529 search_request_.reset(); | 524 search_request_.reset(); |
| 530 | 525 |
| 526 // TODO(msw): Acknowledge the sync invalidation when API exists. | |
| 527 // TODO(msw): Detect, log, potentially retry on failure / bad responses. | |
| 528 // TODO(msw): Handle removing all devices or cloud print account altogether. | |
| 529 | |
| 531 ListValue* list = NULL; | 530 ListValue* list = NULL; |
| 532 DictionaryValue* dictionary = NULL; | 531 DictionaryValue* dictionary = NULL; |
| 533 scoped_ptr<Value> json(base::JSONReader::Read(data)); | 532 scoped_ptr<Value> json(base::JSONReader::Read(data)); |
| 534 if (json.get() && json->GetAsDictionary(&dictionary) && dictionary && | 533 if (json.get() && json->GetAsDictionary(&dictionary) && dictionary && |
| 535 dictionary->GetList(cloud_print::kPrinterListValue, &list)) { | 534 dictionary->GetList(cloud_print::kPrinterListValue, &list)) { |
| 536 ListValue mobiles; | 535 ListValue mobiles; |
| 537 std::string type, name, id; | 536 std::string type, name, id; |
| 538 DictionaryValue* printer = NULL; | 537 DictionaryValue* printer = NULL; |
| 539 DictionaryValue* mobile = NULL; | 538 DictionaryValue* mobile = NULL; |
| 540 for (size_t index = 0; index < list->GetSize(); ++index) { | 539 for (size_t index = 0; index < list->GetSize(); ++index) { |
| 541 if (list->GetDictionary(index, &printer) && | 540 if (list->GetDictionary(index, &printer) && |
| 542 printer->GetString("type", &type) && | 541 printer->GetString("type", &type) && |
| 543 (type.compare(kTypeAndroid) == 0 || type.compare(kTypeIOS) == 0)) { | 542 (type.compare(kTypeAndroid) == 0 || type.compare(kTypeIOS) == 0)) { |
| 544 // Copy just the requisite values from the full |printer| definition. | 543 // Copy just the requisite values from the full |printer| definition. |
| 545 if (printer->GetString("displayName", &name) && | 544 if (printer->GetString("displayName", &name) && |
| 546 printer->GetString("id", &id)) { | 545 printer->GetString("id", &id)) { |
| 547 mobile = new DictionaryValue(); | 546 mobile = new DictionaryValue(); |
| 548 mobile->SetString("type", type); | 547 mobile->SetString("type", type); |
| 549 mobile->SetString("name", name); | 548 mobile->SetString("name", name); |
| 550 mobile->SetString("id", id); | 549 mobile->SetString("id", id); |
| 551 mobiles.Append(mobile); | 550 mobiles.Append(mobile); |
| 552 } else { | 551 } else { |
| 553 NOTREACHED(); | 552 NOTREACHED(); |
| 554 } | 553 } |
| 555 } | 554 } |
| 556 } | 555 } |
| 557 | 556 |
| 558 // Update the mobile list and timestamp in prefs. | 557 // Update the cached mobile device list in profile prefs. |
| 559 PrefService* prefs = profile_->GetPrefs(); | 558 profile_->GetPrefs()->Set(prefs::kChromeToMobileDeviceList, mobiles); |
| 560 prefs->Set(prefs::kChromeToMobileDeviceList, mobiles); | |
| 561 prefs->SetInt64(prefs::kChromeToMobileTimestamp, | |
| 562 base::TimeTicks::Now().ToInternalValue()); | |
| 563 | 559 |
| 564 if (HasMobiles()) | 560 if (HasMobiles()) |
| 565 LogMetric(DEVICES_AVAILABLE); | 561 LogMetric(DEVICES_AVAILABLE); |
| 566 UpdateCommandState(); | 562 UpdateCommandState(); |
| 567 } | 563 } |
| 568 } | 564 } |
| 569 | 565 |
| 570 void ChromeToMobileService::HandleSubmitResponse( | 566 void ChromeToMobileService::HandleSubmitResponse( |
| 571 const net::URLFetcher* source) { | 567 const net::URLFetcher* source) { |
| 572 // Get the observer for this response; bail if there is none or it is NULL. | 568 // Get the observer for this response; bail if there is none or it is NULL. |
| (...skipping 24 matching lines...) Expand all Loading... | |
| 597 | 593 |
| 598 // Ensure a second response is not sent after reporting failure below. | 594 // Ensure a second response is not sent after reporting failure below. |
| 599 request_observer_map_.erase(other); | 595 request_observer_map_.erase(other); |
| 600 break; | 596 break; |
| 601 } | 597 } |
| 602 } | 598 } |
| 603 | 599 |
| 604 LogMetric(success ? SEND_SUCCESS : SEND_ERROR); | 600 LogMetric(success ? SEND_SUCCESS : SEND_ERROR); |
| 605 observer->OnSendComplete(success); | 601 observer->OnSendComplete(success); |
| 606 } | 602 } |
| OLD | NEW |