1 // Copyright 2014 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/sync/sessions/sessions_sync_manager.h"
7 #include "base/metrics/field_trial.h"
8 #include "chrome/browser/chrome_notification_types.h"
9 #include "chrome/browser/favicon/favicon_service_factory.h"
10 #include "chrome/browser/history/history_service_factory.h"
11 #include "chrome/browser/profiles/profile.h"
12 #include "chrome/browser/search/search.h"
13 #include "chrome/browser/sync/glue/synced_tab_delegate.h"
14 #include "chrome/browser/sync/glue/synced_window_delegate.h"
15 #include "chrome/browser/sync/sessions/synced_window_delegates_getter.h"
16 #include "chrome/common/url_constants.h"
17 #include "components/sessions/content/content_serialized_navigation_builder.h"
18 #include "components/sync_driver/local_device_info_provider.h"
19 #include "content/public/browser/favicon_status.h"
20 #include "content/public/browser/navigation_entry.h"
21 #include "content/public/browser/notification_details.h"
22 #include "content/public/browser/notification_service.h"
23 #include "content/public/browser/notification_source.h"
24 #include "content/public/common/url_constants.h"
25 #include "sync/api/sync_error.h"
26 #include "sync/api/sync_error_factory.h"
27 #include "sync/api/sync_merge_result.h"
28 #include "sync/api/time.h"
30 using content::NavigationEntry
;
31 using sessions::ContentSerializedNavigationBuilder
;
32 using sessions::SerializedNavigationEntry
;
33 using sync_driver::DeviceInfo
;
34 using sync_driver::LocalDeviceInfoProvider
;
35 using syncer::SyncChange
;
36 using syncer::SyncData
;
38 namespace browser_sync
{
42 // Maximum number of favicons to sync.
43 // TODO(zea): pull this from the server.
44 const int kMaxSyncFavicons
= 200;
46 // The maximum number of navigations in each direction we care to sync.
47 const int kMaxSyncNavigationCount
= 6;
49 // The URL at which the set of synced tabs is displayed. We treat it differently
50 // from all other URL's as accessing it triggers a sync refresh of Sessions.
51 const char kNTPOpenTabSyncURL
[] = "chrome://newtab/#open_tabs";
53 // Default number of days without activity after which a session is considered
54 // stale and becomes a candidate for garbage collection.
55 const size_t kDefaultStaleSessionThresholdDays
= 14; // 2 weeks.
57 // Comparator function for use with std::sort that will sort tabs by
58 // descending timestamp (i.e., most recent first).
59 bool TabsRecencyComparator(const sessions::SessionTab
* t1
,
60 const sessions::SessionTab
* t2
) {
61 return t1
->timestamp
> t2
->timestamp
;
64 // Comparator function for use with std::sort that will sort sessions by
65 // descending modified_time (i.e., most recent first).
66 bool SessionsRecencyComparator(const sync_driver::SyncedSession
* s1
,
67 const sync_driver::SyncedSession
* s2
) {
68 return s1
->modified_time
> s2
->modified_time
;
73 // |local_device| is owned by ProfileSyncService, its lifetime exceeds
74 // lifetime of SessionSyncManager.
75 SessionsSyncManager::SessionsSyncManager(
77 LocalDeviceInfoProvider
* local_device
,
78 scoped_ptr
<LocalSessionEventRouter
> router
)
79 : favicon_cache_(FaviconServiceFactory::GetForProfile(
81 ServiceAccessType::EXPLICIT_ACCESS
),
82 HistoryServiceFactory::GetForProfile(
84 ServiceAccessType::EXPLICIT_ACCESS
),
86 local_tab_pool_out_of_sync_(true),
87 sync_prefs_(profile
->GetPrefs()),
89 local_device_(local_device
),
90 local_session_header_node_id_(TabNodePool::kInvalidTabNodeID
),
91 stale_session_threshold_days_(kDefaultStaleSessionThresholdDays
),
92 local_event_router_(router
.Pass()),
93 synced_window_getter_(new SyncedWindowDelegatesGetter()) {}
95 LocalSessionEventRouter::~LocalSessionEventRouter() {}
97 SessionsSyncManager::~SessionsSyncManager() {
100 // Returns the GUID-based string that should be used for
101 // |SessionsSyncManager::current_machine_tag_|.
102 static std::string
BuildMachineTag(const std::string
& cache_guid
) {
103 std::string machine_tag
= "session_sync";
104 machine_tag
.append(cache_guid
);
108 syncer::SyncMergeResult
SessionsSyncManager::MergeDataAndStartSyncing(
109 syncer::ModelType type
,
110 const syncer::SyncDataList
& initial_sync_data
,
111 scoped_ptr
<syncer::SyncChangeProcessor
> sync_processor
,
112 scoped_ptr
<syncer::SyncErrorFactory
> error_handler
) {
113 syncer::SyncMergeResult
merge_result(type
);
114 DCHECK(session_tracker_
.Empty());
115 DCHECK_EQ(0U, local_tab_pool_
.Capacity());
117 error_handler_
= error_handler
.Pass();
118 sync_processor_
= sync_processor
.Pass();
120 local_session_header_node_id_
= TabNodePool::kInvalidTabNodeID
;
122 // Make sure we have a machine tag. We do this now (versus earlier) as it's
123 // a conveniently safe time to assert sync is ready and the cache_guid is
125 if (current_machine_tag_
.empty()) {
126 InitializeCurrentMachineTag();
129 // SessionDataTypeController ensures that the local device info
130 // is available before activating this datatype.
131 DCHECK(local_device_
);
132 const DeviceInfo
* local_device_info
= local_device_
->GetLocalDeviceInfo();
133 if (local_device_info
) {
134 current_session_name_
= local_device_info
->client_name();
136 merge_result
.set_error(error_handler_
->CreateAndUploadError(
138 "Failed to get local device info."));
142 session_tracker_
.SetLocalSessionTag(current_machine_tag_
);
144 syncer::SyncChangeList new_changes
;
146 // First, we iterate over sync data to update our session_tracker_.
147 syncer::SyncDataList restored_tabs
;
148 if (!InitFromSyncModel(initial_sync_data
, &restored_tabs
, &new_changes
)) {
149 // The sync db didn't have a header node for us. Create one.
150 sync_pb::EntitySpecifics specifics
;
151 sync_pb::SessionSpecifics
* base_specifics
= specifics
.mutable_session();
152 base_specifics
->set_session_tag(current_machine_tag());
153 sync_pb::SessionHeader
* header_s
= base_specifics
->mutable_header();
154 header_s
->set_client_name(current_session_name_
);
155 header_s
->set_device_type(local_device_info
->device_type());
156 syncer::SyncData data
= syncer::SyncData::CreateLocalData(
157 current_machine_tag(), current_session_name_
, specifics
);
158 new_changes
.push_back(syncer::SyncChange(
159 FROM_HERE
, syncer::SyncChange::ACTION_ADD
, data
));
162 #if defined(OS_ANDROID)
163 std::string
sync_machine_tag(BuildMachineTag(
164 local_device_
->GetLocalSyncCacheGUID()));
165 if (current_machine_tag_
.compare(sync_machine_tag
) != 0)
166 DeleteForeignSessionInternal(sync_machine_tag
, &new_changes
);
169 // Check if anything has changed on the local client side.
170 AssociateWindows(RELOAD_TABS
, restored_tabs
, &new_changes
);
171 local_tab_pool_out_of_sync_
= false;
173 merge_result
.set_error(
174 sync_processor_
->ProcessSyncChanges(FROM_HERE
, new_changes
));
176 local_event_router_
->StartRoutingTo(this);
180 void SessionsSyncManager::AssociateWindows(
181 ReloadTabsOption option
,
182 const syncer::SyncDataList
& restored_tabs
,
183 syncer::SyncChangeList
* change_output
) {
184 const std::string local_tag
= current_machine_tag();
185 sync_pb::SessionSpecifics specifics
;
186 specifics
.set_session_tag(local_tag
);
187 sync_pb::SessionHeader
* header_s
= specifics
.mutable_header();
188 sync_driver::SyncedSession
* current_session
=
189 session_tracker_
.GetSession(local_tag
);
190 current_session
->modified_time
= base::Time::Now();
191 header_s
->set_client_name(current_session_name_
);
192 // SessionDataTypeController ensures that the local device info
193 // is available before activating this datatype.
194 DCHECK(local_device_
);
195 const DeviceInfo
* local_device_info
= local_device_
->GetLocalDeviceInfo();
196 header_s
->set_device_type(local_device_info
->device_type());
198 session_tracker_
.ResetSessionTracking(local_tag
);
199 std::set
<const SyncedWindowDelegate
*> windows
=
200 synced_window_getter_
->GetSyncedWindowDelegates();
202 for (std::set
<const SyncedWindowDelegate
*>::const_iterator i
=
203 windows
.begin(); i
!= windows
.end(); ++i
) {
204 // Make sure the window has tabs and a viewable window. The viewable window
205 // check is necessary because, for example, when a browser is closed the
206 // destructor is not necessarily run immediately. This means its possible
207 // for us to get a handle to a browser that is about to be removed. If
208 // the tab count is 0 or the window is NULL, the browser is about to be
209 // deleted, so we ignore it.
210 if ((*i
)->ShouldSync() && (*i
)->GetTabCount() && (*i
)->HasWindow()) {
211 sync_pb::SessionWindow window_s
;
212 SessionID::id_type window_id
= (*i
)->GetSessionId();
213 DVLOG(1) << "Associating window " << window_id
<< " with "
214 << (*i
)->GetTabCount() << " tabs.";
215 window_s
.set_window_id(window_id
);
216 // Note: We don't bother to set selected tab index anymore. We still
217 // consume it when receiving foreign sessions, as reading it is free, but
218 // it triggers too many sync cycles with too little value to make setting
220 if ((*i
)->IsTypeTabbed()) {
221 window_s
.set_browser_type(
222 sync_pb::SessionWindow_BrowserType_TYPE_TABBED
);
224 window_s
.set_browser_type(
225 sync_pb::SessionWindow_BrowserType_TYPE_POPUP
);
228 bool found_tabs
= false;
229 for (int j
= 0; j
< (*i
)->GetTabCount(); ++j
) {
230 SessionID::id_type tab_id
= (*i
)->GetTabIdAt(j
);
231 SyncedTabDelegate
* synced_tab
= (*i
)->GetTabAt(j
);
233 // GetTabAt can return a null tab; in that case just skip it.
237 if (!synced_tab
->HasWebContents()) {
238 // For tabs without WebContents update the |tab_id|, as it could have
239 // changed after a session restore.
240 // Note: We cannot check if a tab is valid if it has no WebContents.
241 // We assume any such tab is valid and leave the contents of
242 // corresponding sync node unchanged.
243 if (synced_tab
->GetSyncId() > TabNodePool::kInvalidTabNodeID
&&
244 tab_id
> TabNodePool::kInvalidTabID
) {
245 AssociateRestoredPlaceholderTab(*synced_tab
, tab_id
,
246 restored_tabs
, change_output
);
248 window_s
.add_tab(tab_id
);
253 if (RELOAD_TABS
== option
)
254 AssociateTab(synced_tab
, change_output
);
256 // If the tab is valid, it would have been added to the tracker either
257 // by the above AssociateTab call (at association time), or by the
258 // change processor calling AssociateTab for all modified tabs.
259 // Therefore, we can key whether this window has valid tabs based on
260 // the tab's presence in the tracker.
261 const sessions::SessionTab
* tab
= NULL
;
262 if (session_tracker_
.LookupSessionTab(local_tag
, tab_id
, &tab
)) {
264 window_s
.add_tab(tab_id
);
268 sync_pb::SessionWindow
* header_window
= header_s
->add_window();
269 *header_window
= window_s
;
271 // Update this window's representation in the synced session tracker.
272 session_tracker_
.PutWindowInSession(local_tag
, window_id
);
273 BuildSyncedSessionFromSpecifics(local_tag
,
275 current_session
->modified_time
,
276 current_session
->windows
[window_id
]);
280 local_tab_pool_
.DeleteUnassociatedTabNodes(change_output
);
281 session_tracker_
.CleanupSession(local_tag
);
283 // Always update the header. Sync takes care of dropping this update
284 // if the entity specifics are identical (i.e windows, client name did
286 sync_pb::EntitySpecifics entity
;
287 entity
.mutable_session()->CopyFrom(specifics
);
288 syncer::SyncData data
= syncer::SyncData::CreateLocalData(
289 current_machine_tag(), current_session_name_
, entity
);
290 change_output
->push_back(syncer::SyncChange(
291 FROM_HERE
, syncer::SyncChange::ACTION_UPDATE
, data
));
294 void SessionsSyncManager::AssociateTab(SyncedTabDelegate
* const tab
,
295 syncer::SyncChangeList
* change_output
) {
296 DCHECK(tab
->HasWebContents());
297 SessionID::id_type tab_id
= tab
->GetSessionId();
298 if (tab
->profile() != profile_
)
301 if (tab
->IsBeingDestroyed()) {
302 // This tab is closing.
303 TabLinksMap::iterator tab_iter
= local_tab_map_
.find(tab_id
);
304 if (tab_iter
== local_tab_map_
.end()) {
305 // We aren't tracking this tab (for example, sync setting page).
308 local_tab_pool_
.FreeTabNode(tab_iter
->second
->tab_node_id(),
310 local_tab_map_
.erase(tab_iter
);
314 if (!tab
->ShouldSync())
317 TabLinksMap::iterator local_tab_map_iter
= local_tab_map_
.find(tab_id
);
318 TabLink
* tab_link
= NULL
;
320 if (local_tab_map_iter
== local_tab_map_
.end()) {
321 int tab_node_id
= tab
->GetSyncId();
322 // If there is an old sync node for the tab, reuse it. If this is a new
323 // tab, get a sync node for it.
324 if (!local_tab_pool_
.IsUnassociatedTabNode(tab_node_id
)) {
325 tab_node_id
= local_tab_pool_
.GetFreeTabNode(change_output
);
326 tab
->SetSyncId(tab_node_id
);
328 local_tab_pool_
.AssociateTabNode(tab_node_id
, tab_id
);
329 tab_link
= new TabLink(tab_node_id
, tab
);
330 local_tab_map_
[tab_id
] = make_linked_ptr
<TabLink
>(tab_link
);
332 // This tab is already associated with a sync node, reuse it.
333 // Note: on some platforms the tab object may have changed, so we ensure
334 // the tab link is up to date.
335 tab_link
= local_tab_map_iter
->second
.get();
336 local_tab_map_iter
->second
->set_tab(tab
);
339 DCHECK_NE(tab_link
->tab_node_id(), TabNodePool::kInvalidTabNodeID
);
340 DVLOG(1) << "Reloading tab " << tab_id
<< " from window "
341 << tab
->GetWindowId();
343 // Write to sync model.
344 sync_pb::EntitySpecifics specifics
;
345 LocalTabDelegateToSpecifics(*tab
, specifics
.mutable_session());
346 syncer::SyncData data
= syncer::SyncData::CreateLocalData(
347 TabNodePool::TabIdToTag(current_machine_tag_
,
348 tab_link
->tab_node_id()),
349 current_session_name_
,
351 change_output
->push_back(syncer::SyncChange(
352 FROM_HERE
, syncer::SyncChange::ACTION_UPDATE
, data
));
354 const GURL new_url
= GetCurrentVirtualURL(*tab
);
355 if (new_url
!= tab_link
->url()) {
356 tab_link
->set_url(new_url
);
357 favicon_cache_
.OnFaviconVisited(new_url
, GetCurrentFaviconURL(*tab
));
360 session_tracker_
.GetSession(current_machine_tag())->modified_time
=
364 void SessionsSyncManager::RebuildAssociations() {
365 syncer::SyncDataList
data(
366 sync_processor_
->GetAllSyncData(syncer::SESSIONS
));
367 scoped_ptr
<syncer::SyncErrorFactory
> error_handler(error_handler_
.Pass());
368 scoped_ptr
<syncer::SyncChangeProcessor
> processor(sync_processor_
.Pass());
370 StopSyncing(syncer::SESSIONS
);
371 MergeDataAndStartSyncing(
372 syncer::SESSIONS
, data
, processor
.Pass(), error_handler
.Pass());
375 bool SessionsSyncManager::IsValidSessionHeader(
376 const sync_pb::SessionHeader
& header
) {
377 // Verify that tab IDs appear only once within a session.
378 // Intended to prevent http://crbug.com/360822.
379 std::set
<int> session_tab_ids
;
380 for (int i
= 0; i
< header
.window_size(); ++i
) {
381 const sync_pb::SessionWindow
& window
= header
.window(i
);
382 for (int j
= 0; j
< window
.tab_size(); ++j
) {
383 const int tab_id
= window
.tab(j
);
384 bool success
= session_tab_ids
.insert(tab_id
).second
;
393 void SessionsSyncManager::OnLocalTabModified(SyncedTabDelegate
* modified_tab
) {
394 const content::NavigationEntry
* entry
= modified_tab
->GetActiveEntry();
395 if (!modified_tab
->IsBeingDestroyed() &&
397 entry
->GetVirtualURL().is_valid() &&
398 entry
->GetVirtualURL().spec() == kNTPOpenTabSyncURL
) {
399 DVLOG(1) << "Triggering sync refresh for sessions datatype.";
400 const syncer::ModelTypeSet
types(syncer::SESSIONS
);
401 content::NotificationService::current()->Notify(
402 chrome::NOTIFICATION_SYNC_REFRESH_LOCAL
,
403 content::Source
<Profile
>(profile_
),
404 content::Details
<const syncer::ModelTypeSet
>(&types
));
407 if (local_tab_pool_out_of_sync_
) {
408 // If our tab pool is corrupt, pay the price of a full re-association to
409 // fix things up. This takes care of the new tab modification as well.
410 RebuildAssociations();
411 DCHECK(!local_tab_pool_out_of_sync_
);
415 syncer::SyncChangeList changes
;
416 // Associate tabs first so the synced session tracker is aware of them.
417 AssociateTab(modified_tab
, &changes
);
418 // Note, we always associate windows because it's possible a tab became
419 // "interesting" by going to a valid URL, in which case it needs to be added
420 // to the window's tab information.
421 AssociateWindows(DONT_RELOAD_TABS
, syncer::SyncDataList(), &changes
);
422 sync_processor_
->ProcessSyncChanges(FROM_HERE
, changes
);
425 void SessionsSyncManager::OnFaviconsChanged(
426 const std::set
<GURL
>& page_urls
,
427 const GURL
& /* icon_url */) {
428 // TODO(zea): consider a separate container for tabs with outstanding favicon
429 // loads so we don't have to iterate through all tabs comparing urls.
430 for (const GURL
& page_url
: page_urls
) {
431 for (TabLinksMap::iterator tab_iter
= local_tab_map_
.begin();
432 tab_iter
!= local_tab_map_
.end();
434 if (tab_iter
->second
->url() == page_url
)
435 favicon_cache_
.OnPageFaviconUpdated(page_url
);
440 void SessionsSyncManager::StopSyncing(syncer::ModelType type
) {
441 local_event_router_
->Stop();
442 sync_processor_
.reset(NULL
);
443 error_handler_
.reset();
444 session_tracker_
.Clear();
445 local_tab_map_
.clear();
446 local_tab_pool_
.Clear();
447 current_machine_tag_
.clear();
448 current_session_name_
.clear();
449 local_session_header_node_id_
= TabNodePool::kInvalidTabNodeID
;
452 syncer::SyncDataList
SessionsSyncManager::GetAllSyncData(
453 syncer::ModelType type
) const {
454 syncer::SyncDataList list
;
455 const sync_driver::SyncedSession
* session
= NULL
;
456 if (!session_tracker_
.LookupLocalSession(&session
))
457 return syncer::SyncDataList();
459 // First construct the header node.
460 sync_pb::EntitySpecifics header_entity
;
461 header_entity
.mutable_session()->set_session_tag(current_machine_tag());
462 sync_pb::SessionHeader
* header_specifics
=
463 header_entity
.mutable_session()->mutable_header();
464 header_specifics
->MergeFrom(session
->ToSessionHeader());
465 syncer::SyncData data
= syncer::SyncData::CreateLocalData(
466 current_machine_tag(), current_session_name_
, header_entity
);
467 list
.push_back(data
);
469 sync_driver::SyncedSession::SyncedWindowMap::const_iterator win_iter
;
470 for (win_iter
= session
->windows
.begin();
471 win_iter
!= session
->windows
.end(); ++win_iter
) {
472 std::vector
<sessions::SessionTab
*>::const_iterator tabs_iter
;
473 for (tabs_iter
= win_iter
->second
->tabs
.begin();
474 tabs_iter
!= win_iter
->second
->tabs
.end(); ++tabs_iter
) {
475 sync_pb::EntitySpecifics entity
;
476 sync_pb::SessionSpecifics
* specifics
= entity
.mutable_session();
477 specifics
->mutable_tab()->MergeFrom((*tabs_iter
)->ToSyncData());
478 specifics
->set_session_tag(current_machine_tag_
);
480 TabLinksMap::const_iterator tab_map_iter
= local_tab_map_
.find(
481 (*tabs_iter
)->tab_id
.id());
482 DCHECK(tab_map_iter
!= local_tab_map_
.end());
483 specifics
->set_tab_node_id(tab_map_iter
->second
->tab_node_id());
484 syncer::SyncData data
= syncer::SyncData::CreateLocalData(
485 TabNodePool::TabIdToTag(current_machine_tag_
,
486 specifics
->tab_node_id()),
487 current_session_name_
,
489 list
.push_back(data
);
495 bool SessionsSyncManager::GetLocalSession(
496 const sync_driver::SyncedSession
** local_session
) {
497 if (current_machine_tag_
.empty())
499 *local_session
= session_tracker_
.GetSession(current_machine_tag());
503 syncer::SyncError
SessionsSyncManager::ProcessSyncChanges(
504 const tracked_objects::Location
& from_here
,
505 const syncer::SyncChangeList
& change_list
) {
506 if (!sync_processor_
.get()) {
507 syncer::SyncError
error(FROM_HERE
,
508 syncer::SyncError::DATATYPE_ERROR
,
509 "Models not yet associated.",
514 for (syncer::SyncChangeList::const_iterator it
= change_list
.begin();
515 it
!= change_list
.end(); ++it
) {
516 DCHECK(it
->IsValid());
517 DCHECK(it
->sync_data().GetSpecifics().has_session());
518 const sync_pb::SessionSpecifics
& session
=
519 it
->sync_data().GetSpecifics().session();
520 switch (it
->change_type()) {
521 case syncer::SyncChange::ACTION_DELETE
:
522 // Deletions are all or nothing (since we only ever delete entire
523 // sessions). Therefore we don't care if it's a tab node or meta node,
524 // and just ensure we've disassociated.
525 if (current_machine_tag() == session
.session_tag()) {
526 // Another client has attempted to delete our local data (possibly by
527 // error or a clock is inaccurate). Just ignore the deletion for now
528 // to avoid any possible ping-pong delete/reassociate sequence, but
529 // remember that this happened as our TabNodePool is inconsistent.
530 local_tab_pool_out_of_sync_
= true;
531 LOG(WARNING
) << "Local session data deleted. Ignoring until next "
532 << "local navigation event.";
533 } else if (session
.has_header()) {
534 // Disassociate only when header node is deleted. For tab node
535 // deletions, the header node will be updated and foreign tab will
537 DisassociateForeignSession(session
.session_tag());
540 case syncer::SyncChange::ACTION_ADD
:
541 case syncer::SyncChange::ACTION_UPDATE
:
542 if (current_machine_tag() == session
.session_tag()) {
543 // We should only ever receive a change to our own machine's session
544 // info if encryption was turned on. In that case, the data is still
545 // the same, so we can ignore.
546 LOG(WARNING
) << "Dropping modification to local session.";
547 return syncer::SyncError();
549 UpdateTrackerWithForeignSession(
550 session
, syncer::SyncDataRemote(it
->sync_data()).GetModifiedTime());
553 NOTREACHED() << "Processing sync changes failed, unknown change type.";
557 content::NotificationService::current()->Notify(
558 chrome::NOTIFICATION_FOREIGN_SESSION_UPDATED
,
559 content::Source
<Profile
>(profile_
),
560 content::NotificationService::NoDetails());
561 return syncer::SyncError();
564 syncer::SyncChange
SessionsSyncManager::TombstoneTab(
565 const sync_pb::SessionSpecifics
& tab
) {
566 if (!tab
.has_tab_node_id()) {
567 LOG(WARNING
) << "Old sessions node without tab node id; can't tombstone.";
568 return syncer::SyncChange();
570 return syncer::SyncChange(
572 SyncChange::ACTION_DELETE
,
573 SyncData::CreateLocalDelete(
574 TabNodePool::TabIdToTag(current_machine_tag(),
580 bool SessionsSyncManager::GetAllForeignSessions(
581 std::vector
<const sync_driver::SyncedSession
*>* sessions
) {
582 if (!session_tracker_
.LookupAllForeignSessions(sessions
))
584 std::sort(sessions
->begin(), sessions
->end(), SessionsRecencyComparator
);
588 bool SessionsSyncManager::InitFromSyncModel(
589 const syncer::SyncDataList
& sync_data
,
590 syncer::SyncDataList
* restored_tabs
,
591 syncer::SyncChangeList
* new_changes
) {
592 bool found_current_header
= false;
593 for (syncer::SyncDataList::const_iterator it
= sync_data
.begin();
594 it
!= sync_data
.end();
596 const syncer::SyncData
& data
= *it
;
597 DCHECK(data
.GetSpecifics().has_session());
598 const sync_pb::SessionSpecifics
& specifics
= data
.GetSpecifics().session();
599 if (specifics
.session_tag().empty() ||
600 (specifics
.has_tab() && (!specifics
.has_tab_node_id() ||
601 !specifics
.tab().has_tab_id()))) {
602 syncer::SyncChange
tombstone(TombstoneTab(specifics
));
603 if (tombstone
.IsValid())
604 new_changes
->push_back(tombstone
);
605 } else if (specifics
.session_tag() != current_machine_tag()) {
606 UpdateTrackerWithForeignSession(
607 specifics
, syncer::SyncDataRemote(data
).GetModifiedTime());
609 // This is previously stored local session information.
610 if (specifics
.has_header() && !found_current_header
) {
611 // This is our previous header node, reuse it.
612 found_current_header
= true;
613 if (specifics
.header().has_client_name())
614 current_session_name_
= specifics
.header().client_name();
616 if (specifics
.has_header() || !specifics
.has_tab()) {
617 LOG(WARNING
) << "Found more than one session header node with local "
619 syncer::SyncChange
tombstone(TombstoneTab(specifics
));
620 if (tombstone
.IsValid())
621 new_changes
->push_back(tombstone
);
623 // This is a valid old tab node, add it to the pool so it can be
624 // reused for reassociation.
625 local_tab_pool_
.AddTabNode(specifics
.tab_node_id());
626 restored_tabs
->push_back(*it
);
631 return found_current_header
;
634 void SessionsSyncManager::UpdateTrackerWithForeignSession(
635 const sync_pb::SessionSpecifics
& specifics
,
636 const base::Time
& modification_time
) {
637 std::string foreign_session_tag
= specifics
.session_tag();
638 DCHECK_NE(foreign_session_tag
, current_machine_tag());
640 sync_driver::SyncedSession
* foreign_session
=
641 session_tracker_
.GetSession(foreign_session_tag
);
642 if (specifics
.has_header()) {
643 // Read in the header data for this foreign session.
644 // Header data contains window information and ordered tab id's for each
647 if (!IsValidSessionHeader(specifics
.header())) {
648 LOG(WARNING
) << "Ignoring foreign session node with invalid header "
649 << "and tag " << foreign_session_tag
<< ".";
653 // Load (or create) the SyncedSession object for this client.
654 const sync_pb::SessionHeader
& header
= specifics
.header();
655 PopulateSessionHeaderFromSpecifics(header
,
659 // Reset the tab/window tracking for this session (must do this before
660 // we start calling PutWindowInSession and PutTabInWindow so that all
661 // unused tabs/windows get cleared by the CleanupSession(...) call).
662 session_tracker_
.ResetSessionTracking(foreign_session_tag
);
664 // Process all the windows and their tab information.
665 int num_windows
= header
.window_size();
666 DVLOG(1) << "Associating " << foreign_session_tag
<< " with "
667 << num_windows
<< " windows.";
669 for (int i
= 0; i
< num_windows
; ++i
) {
670 const sync_pb::SessionWindow
& window_s
= header
.window(i
);
671 SessionID::id_type window_id
= window_s
.window_id();
672 session_tracker_
.PutWindowInSession(foreign_session_tag
,
674 BuildSyncedSessionFromSpecifics(foreign_session_tag
,
677 foreign_session
->windows
[window_id
]);
679 // Delete any closed windows and unused tabs as necessary.
680 session_tracker_
.CleanupSession(foreign_session_tag
);
681 } else if (specifics
.has_tab()) {
682 const sync_pb::SessionTab
& tab_s
= specifics
.tab();
683 SessionID::id_type tab_id
= tab_s
.tab_id();
685 const sessions::SessionTab
* existing_tab
;
686 if (session_tracker_
.LookupSessionTab(
687 foreign_session_tag
, tab_id
, &existing_tab
) &&
688 existing_tab
->timestamp
> modification_time
) {
689 DVLOG(1) << "Ignoring " << foreign_session_tag
<< "'s session tab "
690 << tab_id
<< " with earlier modification time";
694 sessions::SessionTab
* tab
=
695 session_tracker_
.GetTab(foreign_session_tag
,
697 specifics
.tab_node_id());
699 // Update SessionTab based on protobuf.
700 tab
->SetFromSyncData(tab_s
, modification_time
);
702 // If a favicon or favicon urls are present, load the URLs and visit
703 // times into the in-memory favicon cache.
704 RefreshFaviconVisitTimesFromForeignTab(tab_s
, modification_time
);
706 // Update the last modified time.
707 if (foreign_session
->modified_time
< modification_time
)
708 foreign_session
->modified_time
= modification_time
;
710 LOG(WARNING
) << "Ignoring foreign session node with missing header/tab "
711 << "fields and tag " << foreign_session_tag
<< ".";
715 void SessionsSyncManager::InitializeCurrentMachineTag() {
716 DCHECK(current_machine_tag_
.empty());
717 std::string persisted_guid
;
718 persisted_guid
= sync_prefs_
.GetSyncSessionsGUID();
719 if (!persisted_guid
.empty()) {
720 current_machine_tag_
= persisted_guid
;
721 DVLOG(1) << "Restoring persisted session sync guid: " << persisted_guid
;
723 DCHECK(local_device_
);
724 std::string cache_guid
= local_device_
->GetLocalSyncCacheGUID();
725 DCHECK(!cache_guid
.empty());
726 current_machine_tag_
= BuildMachineTag(cache_guid
);
727 DVLOG(1) << "Creating session sync guid: " << current_machine_tag_
;
728 sync_prefs_
.SetSyncSessionsGUID(current_machine_tag_
);
731 local_tab_pool_
.SetMachineTag(current_machine_tag_
);
735 void SessionsSyncManager::PopulateSessionHeaderFromSpecifics(
736 const sync_pb::SessionHeader
& header_specifics
,
738 sync_driver::SyncedSession
* session_header
) {
739 if (header_specifics
.has_client_name())
740 session_header
->session_name
= header_specifics
.client_name();
741 if (header_specifics
.has_device_type()) {
742 switch (header_specifics
.device_type()) {
743 case sync_pb::SyncEnums_DeviceType_TYPE_WIN
:
744 session_header
->device_type
= sync_driver::SyncedSession::TYPE_WIN
;
746 case sync_pb::SyncEnums_DeviceType_TYPE_MAC
:
747 session_header
->device_type
= sync_driver::SyncedSession::TYPE_MACOSX
;
749 case sync_pb::SyncEnums_DeviceType_TYPE_LINUX
:
750 session_header
->device_type
= sync_driver::SyncedSession::TYPE_LINUX
;
752 case sync_pb::SyncEnums_DeviceType_TYPE_CROS
:
753 session_header
->device_type
= sync_driver::SyncedSession::TYPE_CHROMEOS
;
755 case sync_pb::SyncEnums_DeviceType_TYPE_PHONE
:
756 session_header
->device_type
= sync_driver::SyncedSession::TYPE_PHONE
;
758 case sync_pb::SyncEnums_DeviceType_TYPE_TABLET
:
759 session_header
->device_type
= sync_driver::SyncedSession::TYPE_TABLET
;
761 case sync_pb::SyncEnums_DeviceType_TYPE_OTHER
:
762 // Intentionally fall-through
764 session_header
->device_type
= sync_driver::SyncedSession::TYPE_OTHER
;
768 session_header
->modified_time
= mtime
;
772 void SessionsSyncManager::BuildSyncedSessionFromSpecifics(
773 const std::string
& session_tag
,
774 const sync_pb::SessionWindow
& specifics
,
776 sessions::SessionWindow
* session_window
) {
777 if (specifics
.has_window_id())
778 session_window
->window_id
.set_id(specifics
.window_id());
779 if (specifics
.has_selected_tab_index())
780 session_window
->selected_tab_index
= specifics
.selected_tab_index();
781 if (specifics
.has_browser_type()) {
782 // TODO(skuhne): Sync data writes |BrowserType| not
783 // |SessionWindow::WindowType|. This should get changed.
784 if (specifics
.browser_type() ==
785 sync_pb::SessionWindow_BrowserType_TYPE_TABBED
) {
786 session_window
->type
= sessions::SessionWindow::TYPE_TABBED
;
788 session_window
->type
= sessions::SessionWindow::TYPE_POPUP
;
791 session_window
->timestamp
= mtime
;
792 session_window
->tabs
.resize(specifics
.tab_size(), NULL
);
793 for (int i
= 0; i
< specifics
.tab_size(); i
++) {
794 SessionID::id_type tab_id
= specifics
.tab(i
);
795 session_tracker_
.PutTabInWindow(session_tag
,
796 session_window
->window_id
.id(),
802 void SessionsSyncManager::RefreshFaviconVisitTimesFromForeignTab(
803 const sync_pb::SessionTab
& tab
, const base::Time
& modification_time
) {
804 // First go through and iterate over all the navigations, checking if any
805 // have valid favicon urls.
806 for (int i
= 0; i
< tab
.navigation_size(); ++i
) {
807 if (!tab
.navigation(i
).favicon_url().empty()) {
808 const std::string
& page_url
= tab
.navigation(i
).virtual_url();
809 const std::string
& favicon_url
= tab
.navigation(i
).favicon_url();
810 favicon_cache_
.OnReceivedSyncFavicon(GURL(page_url
),
813 syncer::TimeToProtoTime(
819 bool SessionsSyncManager::GetSyncedFaviconForPageURL(
820 const std::string
& page_url
,
821 scoped_refptr
<base::RefCountedMemory
>* favicon_png
) const {
822 return favicon_cache_
.GetSyncedFaviconForPageURL(GURL(page_url
), favicon_png
);
825 void SessionsSyncManager::DeleteForeignSession(const std::string
& tag
) {
826 syncer::SyncChangeList changes
;
827 DeleteForeignSessionInternal(tag
, &changes
);
828 sync_processor_
->ProcessSyncChanges(FROM_HERE
, changes
);
831 void SessionsSyncManager::DeleteForeignSessionInternal(
832 const std::string
& tag
, syncer::SyncChangeList
* change_output
) {
833 if (tag
== current_machine_tag()) {
834 LOG(ERROR
) << "Attempting to delete local session. This is not currently "
839 std::set
<int> tab_node_ids_to_delete
;
840 session_tracker_
.LookupTabNodeIds(tag
, &tab_node_ids_to_delete
);
841 if (!DisassociateForeignSession(tag
)) {
842 // We don't have any data for this session, our work here is done!
846 // Prepare deletes for the meta-node as well as individual tab nodes.
847 change_output
->push_back(syncer::SyncChange(
849 SyncChange::ACTION_DELETE
,
850 SyncData::CreateLocalDelete(tag
, syncer::SESSIONS
)));
852 for (std::set
<int>::const_iterator it
= tab_node_ids_to_delete
.begin();
853 it
!= tab_node_ids_to_delete
.end();
855 change_output
->push_back(syncer::SyncChange(
857 SyncChange::ACTION_DELETE
,
858 SyncData::CreateLocalDelete(TabNodePool::TabIdToTag(tag
, *it
),
861 content::NotificationService::current()->Notify(
862 chrome::NOTIFICATION_FOREIGN_SESSION_UPDATED
,
863 content::Source
<Profile
>(profile_
),
864 content::NotificationService::NoDetails());
867 bool SessionsSyncManager::DisassociateForeignSession(
868 const std::string
& foreign_session_tag
) {
869 if (foreign_session_tag
== current_machine_tag()) {
870 DVLOG(1) << "Local session deleted! Doing nothing until a navigation is "
874 DVLOG(1) << "Disassociating session " << foreign_session_tag
;
875 return session_tracker_
.DeleteSession(foreign_session_tag
);
879 GURL
SessionsSyncManager::GetCurrentVirtualURL(
880 const SyncedTabDelegate
& tab_delegate
) {
881 const NavigationEntry
* current_entry
=
882 tab_delegate
.GetCurrentEntryMaybePending();
883 return current_entry
->GetVirtualURL();
887 GURL
SessionsSyncManager::GetCurrentFaviconURL(
888 const SyncedTabDelegate
& tab_delegate
) {
889 const NavigationEntry
* current_entry
=
890 tab_delegate
.GetCurrentEntryMaybePending();
891 return (current_entry
->GetFavicon().valid
?
892 current_entry
->GetFavicon().url
:
896 bool SessionsSyncManager::GetForeignSession(
897 const std::string
& tag
,
898 std::vector
<const sessions::SessionWindow
*>* windows
) {
899 return session_tracker_
.LookupSessionWindows(tag
, windows
);
902 bool SessionsSyncManager::GetForeignSessionTabs(
903 const std::string
& tag
,
904 std::vector
<const sessions::SessionTab
*>* tabs
) {
905 std::vector
<const sessions::SessionWindow
*> windows
;
906 if (!session_tracker_
.LookupSessionWindows(tag
, &windows
))
909 // Prune those tabs that are not syncable or are NewTabPage, then sort them
910 // from most recent to least recent, independent of which window the tabs were
912 for (size_t j
= 0; j
< windows
.size(); ++j
) {
913 const sessions::SessionWindow
* window
= windows
[j
];
914 for (size_t t
= 0; t
< window
->tabs
.size(); ++t
) {
915 sessions::SessionTab
* const tab
= window
->tabs
[t
];
916 if (tab
->navigations
.empty())
918 const sessions::SerializedNavigationEntry
& current_navigation
=
919 tab
->navigations
.at(tab
->normalized_navigation_index());
920 if (search::IsNTPURL(current_navigation
.virtual_url(), profile_
)) {
923 tabs
->push_back(tab
);
926 std::sort(tabs
->begin(), tabs
->end(), TabsRecencyComparator
);
930 bool SessionsSyncManager::GetForeignTab(
931 const std::string
& tag
,
932 const SessionID::id_type tab_id
,
933 const sessions::SessionTab
** tab
) {
934 const sessions::SessionTab
* synced_tab
= NULL
;
935 bool success
= session_tracker_
.LookupSessionTab(tag
,
943 void SessionsSyncManager::LocalTabDelegateToSpecifics(
944 const SyncedTabDelegate
& tab_delegate
,
945 sync_pb::SessionSpecifics
* specifics
) {
946 sessions::SessionTab
* session_tab
= NULL
;
948 session_tracker_
.GetTab(current_machine_tag(),
949 tab_delegate
.GetSessionId(),
950 tab_delegate
.GetSyncId());
951 SetSessionTabFromDelegate(tab_delegate
, base::Time::Now(), session_tab
);
952 SetVariationIds(session_tab
);
953 sync_pb::SessionTab tab_s
= session_tab
->ToSyncData();
954 specifics
->set_session_tag(current_machine_tag_
);
955 specifics
->set_tab_node_id(tab_delegate
.GetSyncId());
956 specifics
->mutable_tab()->CopyFrom(tab_s
);
959 void SessionsSyncManager::AssociateRestoredPlaceholderTab(
960 const SyncedTabDelegate
& tab_delegate
,
961 SessionID::id_type new_tab_id
,
962 const syncer::SyncDataList
& restored_tabs
,
963 syncer::SyncChangeList
* change_output
) {
964 DCHECK_NE(tab_delegate
.GetSyncId(), TabNodePool::kInvalidTabNodeID
);
965 // Rewrite the tab using |restored_tabs| to retrieve the specifics.
966 if (restored_tabs
.empty()) {
967 DLOG(WARNING
) << "Can't Update tab ID.";
971 for (syncer::SyncDataList::const_iterator it
= restored_tabs
.begin();
972 it
!= restored_tabs
.end();
974 if (it
->GetSpecifics().session().tab_node_id() !=
975 tab_delegate
.GetSyncId()) {
979 sync_pb::EntitySpecifics entity
;
980 sync_pb::SessionSpecifics
* specifics
= entity
.mutable_session();
981 specifics
->CopyFrom(it
->GetSpecifics().session());
982 DCHECK(specifics
->has_tab());
984 // Update tab node pool with the new association.
985 local_tab_pool_
.ReassociateTabNode(tab_delegate
.GetSyncId(),
987 TabLink
* tab_link
= new TabLink(tab_delegate
.GetSyncId(),
989 local_tab_map_
[new_tab_id
] = make_linked_ptr
<TabLink
>(tab_link
);
991 if (specifics
->tab().tab_id() == new_tab_id
)
994 // The tab_id changed (e.g due to session restore), so update sync.
995 specifics
->mutable_tab()->set_tab_id(new_tab_id
);
996 syncer::SyncData data
= syncer::SyncData::CreateLocalData(
997 TabNodePool::TabIdToTag(current_machine_tag_
,
998 specifics
->tab_node_id()),
999 current_session_name_
,
1001 change_output
->push_back(syncer::SyncChange(
1002 FROM_HERE
, syncer::SyncChange::ACTION_UPDATE
, data
));
1008 void SessionsSyncManager::SetSessionTabFromDelegate(
1009 const SyncedTabDelegate
& tab_delegate
,
1011 sessions::SessionTab
* session_tab
) {
1012 DCHECK(session_tab
);
1013 session_tab
->window_id
.set_id(tab_delegate
.GetWindowId());
1014 session_tab
->tab_id
.set_id(tab_delegate
.GetSessionId());
1015 session_tab
->tab_visual_index
= 0;
1016 // Use -1 to indicate that the index hasn't been set properly yet.
1017 session_tab
->current_navigation_index
= -1;
1018 session_tab
->pinned
= tab_delegate
.IsPinned();
1019 session_tab
->extension_app_id
= tab_delegate
.GetExtensionAppId();
1020 session_tab
->user_agent_override
.clear();
1021 session_tab
->timestamp
= mtime
;
1022 const int current_index
= tab_delegate
.GetCurrentEntryIndex();
1023 const int min_index
= std::max(0, current_index
- kMaxSyncNavigationCount
);
1024 const int max_index
= std::min(current_index
+ kMaxSyncNavigationCount
,
1025 tab_delegate
.GetEntryCount());
1026 bool is_supervised
= tab_delegate
.ProfileIsSupervised();
1027 session_tab
->navigations
.clear();
1029 for (int i
= min_index
; i
< max_index
; ++i
) {
1030 const NavigationEntry
* entry
= tab_delegate
.GetEntryAtIndexMaybePending(i
);
1032 if (!entry
->GetVirtualURL().is_valid())
1035 // Set current_navigation_index to the index in navigations.
1036 if (i
== current_index
)
1037 session_tab
->current_navigation_index
= session_tab
->navigations
.size();
1039 session_tab
->navigations
.push_back(
1040 ContentSerializedNavigationBuilder::FromNavigationEntry(i
, *entry
));
1041 if (is_supervised
) {
1042 session_tab
->navigations
.back().set_blocked_state(
1043 SerializedNavigationEntry::STATE_ALLOWED
);
1047 // If the current navigation is invalid, set the index to the end of the
1048 // navigation array.
1049 if (session_tab
->current_navigation_index
< 0) {
1050 session_tab
->current_navigation_index
=
1051 session_tab
->navigations
.size() - 1;
1054 if (is_supervised
) {
1055 const std::vector
<const NavigationEntry
*>& blocked_navigations
=
1056 *tab_delegate
.GetBlockedNavigations();
1057 int offset
= session_tab
->navigations
.size();
1058 for (size_t i
= 0; i
< blocked_navigations
.size(); ++i
) {
1059 session_tab
->navigations
.push_back(
1060 ContentSerializedNavigationBuilder::FromNavigationEntry(
1061 i
+ offset
, *blocked_navigations
[i
]));
1062 session_tab
->navigations
.back().set_blocked_state(
1063 SerializedNavigationEntry::STATE_BLOCKED
);
1064 // TODO(bauerb): Add categories
1067 session_tab
->session_storage_persistent_id
.clear();
1071 void SessionsSyncManager::SetVariationIds(sessions::SessionTab
* session_tab
) {
1072 base::FieldTrial::ActiveGroups active_groups
;
1073 base::FieldTrialList::GetActiveFieldTrialGroups(&active_groups
);
1074 for (const base::FieldTrial::ActiveGroup
& group
: active_groups
) {
1075 const variations::VariationID id
=
1076 variations::GetGoogleVariationID(variations::CHROME_SYNC_SERVICE
,
1077 group
.trial_name
, group
.group_name
);
1078 if (id
!= variations::EMPTY_ID
)
1079 session_tab
->variation_ids
.push_back(id
);
1083 FaviconCache
* SessionsSyncManager::GetFaviconCache() {
1084 return &favicon_cache_
;
1087 SyncedWindowDelegatesGetter
*
1088 SessionsSyncManager::GetSyncedWindowDelegatesGetter() const {
1089 return synced_window_getter_
.get();
1092 void SessionsSyncManager::DoGarbageCollection() {
1093 std::vector
<const sync_driver::SyncedSession
*> sessions
;
1094 if (!GetAllForeignSessions(&sessions
))
1095 return; // No foreign sessions.
1097 // Iterate through all the sessions and delete any with age older than
1098 // |stale_session_threshold_days_|.
1099 syncer::SyncChangeList changes
;
1100 for (std::vector
<const sync_driver::SyncedSession
*>::const_iterator iter
=
1102 iter
!= sessions
.end(); ++iter
) {
1103 const sync_driver::SyncedSession
* session
= *iter
;
1104 int session_age_in_days
=
1105 (base::Time::Now() - session
->modified_time
).InDays();
1106 std::string session_tag
= session
->session_tag
;
1107 if (session_age_in_days
> 0 && // If false, local clock is not trustworty.
1108 static_cast<size_t>(session_age_in_days
) >
1109 stale_session_threshold_days_
) {
1110 DVLOG(1) << "Found stale session " << session_tag
1111 << " with age " << session_age_in_days
<< ", deleting.";
1112 DeleteForeignSessionInternal(session_tag
, &changes
);
1116 if (!changes
.empty())
1117 sync_processor_
->ProcessSyncChanges(FROM_HERE
, changes
);
1120 }; // namespace browser_sync