Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Improve trip surfacing

laurenspriem831263a1a2db
diff --git a/mobile/apps/photos/lib/models/memories/memories_cache.dart b/mobile/apps/photos/lib/models/memories/memories_cache.dart
index 10d4fca5e7..99b3338cd4 100644
--- a/mobile/apps/photos/lib/models/memories/memories_cache.dart
+++ b/mobile/apps/photos/lib/models/memories/memories_cache.dart
@@ -95,12 +95,19 @@ class ToShowMemory {
return now > lastTimeToShow;
}
+ bool isRelevantAt(int timestamp) {
+ return timestamp >= firstTimeToShow && timestamp < lastTimeToShow;
+ }
+
bool shouldShowNow() {
final now = DateTime.now().microsecondsSinceEpoch;
- final relevantForNow = now >= firstTimeToShow && now < lastTimeToShow;
+ final relevantForNow = isRelevantAt(now);
final calculatedForNow = (now >= calculationTime) &&
(now < calculationTime + kMemoriesUpdateFrequency.inMicroseconds);
- return relevantForNow && (calculatedForNow || type == MemoryType.onThisDay);
+ return relevantForNow &&
+ (calculatedForNow ||
+ type == MemoryType.onThisDay ||
+ type == MemoryType.trips);
}
ToShowMemory(
@@ -254,6 +261,28 @@ class ToShowMemory {
bool get hasTypedSpec => spec != null;
+ String? get tripKey {
+ final currentSpec = spec;
+ if (currentSpec is TripMemorySpec) {
+ return currentSpec.tripKey;
+ }
+ return null;
+ }
+
+ String get tripIdentityKey {
+ final key = tripKey;
+ if (key != null && key.isNotEmpty) {
+ return "trip:$key";
+ }
+ final loc = location;
+ if (loc == null) {
+ return "legacy:$id";
+ }
+ final latitude = (loc.latitude ?? 0).toStringAsFixed(2);
+ final longitude = (loc.longitude ?? 0).toStringAsFixed(2);
+ return "legacy:$latitude:$longitude";
+ }
+
SmartMemory toSmartMemory(List<Memory> memories) {
if (spec != null) {
return spec!.toSmartMemory(
@@ -388,10 +417,12 @@ class ClipShownLog {
class TripsShownLog {
final Location location;
final int lastTimeShown;
+ final String? tripKey;
TripsShownLog(
this.location,
this.lastTimeShown,
+ this.tripKey,
);
factory TripsShownLog.fromOldCacheMemory(ToShowMemory memory) {
@@ -399,6 +430,7 @@ class TripsShownLog {
return TripsShownLog(
memory.location!,
memory.lastTimeToShow,
+ memory.tripKey,
);
}
@@ -409,6 +441,7 @@ class TripsShownLog {
longitude: json['location']['longitude'],
),
json['lastTimeShown'],
+ json['tripKey'] as String?,
);
}
@@ -419,6 +452,7 @@ class TripsShownLog {
'longitude': location.longitude!,
},
'lastTimeShown': lastTimeShown,
+ 'tripKey': tripKey,
};
}
diff --git a/mobile/apps/photos/lib/models/memories/memory_spec.dart b/mobile/apps/photos/lib/models/memories/memory_spec.dart
index 36518ae7d8..e58592c82d 100644
--- a/mobile/apps/photos/lib/models/memories/memory_spec.dart
+++ b/mobile/apps/photos/lib/models/memories/memory_spec.dart
@@ -42,6 +42,7 @@ abstract class MemorySpec {
location: memory.location,
locationName: memory.locationName,
tripYear: memory.tripYear,
+ tripKey: memory.tripKey,
);
}
if (memory is ClipMemory) {
@@ -173,11 +174,13 @@ class TripMemorySpec extends MemorySpec {
final Location location;
final String? locationName;
final int? tripYear;
+ final String? tripKey;
const TripMemorySpec({
required this.location,
required this.locationName,
required this.tripYear,
+ required this.tripKey,
});
factory TripMemorySpec.fromJson(Map<String, dynamic> json) {
@@ -189,6 +192,7 @@ class TripMemorySpec extends MemorySpec {
),
locationName: json["locationName"] as String?,
tripYear: json["tripYear"] as int?,
+ tripKey: json["tripKey"] as String?,
);
}
@@ -214,6 +218,7 @@ class TripMemorySpec extends MemorySpec {
id: id,
locationName: locationName,
tripYear: tripYear,
+ tripKey: tripKey,
);
tripMemory.title = title;
return tripMemory;
@@ -229,6 +234,7 @@ class TripMemorySpec extends MemorySpec {
},
"locationName": locationName,
"tripYear": tripYear,
+ "tripKey": tripKey,
};
}
}
diff --git a/mobile/apps/photos/lib/models/memories/smart_memory_constants.dart b/mobile/apps/photos/lib/models/memories/smart_memory_constants.dart
index 35a8b4130c..a858e91377 100644
--- a/mobile/apps/photos/lib/models/memories/smart_memory_constants.dart
+++ b/mobile/apps/photos/lib/models/memories/smart_memory_constants.dart
@@ -3,3 +3,4 @@ const kMemoriesUpdateFrequencyDays = 3;
const kMemoriesUpdateFrequency = Duration(days: kMemoriesUpdateFrequencyDays);
const kMemoriesMargin = Duration(days: 1);
const kDayItself = Duration(days: 1);
+const kTripSurfaceSlots = 2;
diff --git a/mobile/apps/photos/lib/models/memories/trip_memory.dart b/mobile/apps/photos/lib/models/memories/trip_memory.dart
index 367fa8498a..cdd52212d1 100644
--- a/mobile/apps/photos/lib/models/memories/trip_memory.dart
+++ b/mobile/apps/photos/lib/models/memories/trip_memory.dart
@@ -5,6 +5,7 @@ import "package:photos/models/memories/smart_memory.dart";
class TripMemory extends SmartMemory {
final Location location;
+ final String? tripKey;
// Stuff for the title
String? locationName;
@@ -18,6 +19,7 @@ class TripMemory extends SmartMemory {
String? id,
this.locationName,
this.tripYear,
+ this.tripKey,
super.firstCreationTime,
super.lastCreationTime,
}) : super(
@@ -35,14 +37,17 @@ class TripMemory extends SmartMemory {
int? lastDateToShow,
String? locationName,
int? tripYear,
+ String? tripKey,
}) {
return TripMemory(
memories ?? this.memories,
firstDateToShow ?? this.firstDateToShow,
lastDateToShow ?? this.lastDateToShow,
location,
+ id: id,
locationName: locationName ?? this.locationName,
tripYear: tripYear ?? this.tripYear,
+ tripKey: tripKey ?? this.tripKey,
firstCreationTime: firstCreationTime,
lastCreationTime: lastCreationTime,
);
diff --git a/mobile/apps/photos/lib/services/memories_cache_service.dart b/mobile/apps/photos/lib/services/memories_cache_service.dart
index 6add6791a6..c432ba9d59 100644
--- a/mobile/apps/photos/lib/services/memories_cache_service.dart
+++ b/mobile/apps/photos/lib/services/memories_cache_service.dart
@@ -21,6 +21,7 @@ import "package:photos/models/memories/memory.dart";
import "package:photos/models/memories/people_memory.dart";
import "package:photos/models/memories/smart_memory.dart";
import "package:photos/models/memories/smart_memory_constants.dart";
+import "package:photos/models/memories/trip_memory.dart";
import "package:photos/service_locator.dart";
import "package:photos/services/app_navigation_service.dart";
import "package:photos/services/language_service.dart";
@@ -39,6 +40,7 @@ class MemoriesCacheService {
static const _lastMemoriesCacheUpdateTimeKey = "lastMemoriesCacheUpdateTime";
static const _showAnyMemoryKey = "memories.enabled";
static const _shouldUpdateCacheKey = "memories.shouldUpdateCache";
+ static const _tripMemoryCarryForwardLimit = kTripSurfaceSlots;
/// Delay is for cache update to be done not during app init, during which a
/// lot of other things are happening.
@@ -522,16 +524,20 @@ class MemoriesCacheService {
final next = now.add(kMemoriesUpdateFrequency);
final nowResult =
await smartMemoriesService.calcSmartMemories(now, newCache);
- if (nowResult.isEmpty) {
- _cachedMemories = [];
- _logger.warning(
- "No memories found for now, not updating cache and returning early",
- );
- return;
- }
+ final carriedForwardTripEntries = List<ToShowMemory>.from(
+ newCache.toShowMemories,
+ );
+ newCache.toShowMemories.addAll(
+ nowResult.memories
+ .whereType<TripMemory>()
+ .map((memory) => ToShowMemory.fromSmartMemory(memory, now)),
+ );
final nextResult =
await smartMemoriesService.calcSmartMemories(next, newCache);
w?.log("calculated new memories");
+ newCache.toShowMemories
+ ..clear()
+ ..addAll(carriedForwardTripEntries);
final localIdToIntId = isOfflineMode
? await _buildLocalIntIdMapForMemories(
[...nowResult.memories, ...nextResult.memories],
@@ -545,15 +551,21 @@ class MemoriesCacheService {
newCache.toShowMemories
.add(_toCacheMemory(nextMemory, next, localIdToIntId));
}
+ final nowMicros = now.microsecondsSinceEpoch;
+ final dedupedMemories = _dedupeTripCacheEntriesInOrder(
+ List<ToShowMemory>.from(newCache.toShowMemories),
+ nowMicros: nowMicros,
+ );
+ newCache.toShowMemories
+ ..clear()
+ ..addAll(dedupedMemories);
newCache.baseLocations.addAll(nowResult.baseLocations);
w?.log("added memories to cache");
- _cachedMemories = nowResult.memories
- .where((memory) => memory.shouldShowNow())
- .toList();
+ _cachedMemories = await fromCacheToMemories(newCache);
await _scheduleMemoryNotifications(
[...nowResult.memories, ...nextResult.memories],
);
- locationService.baseLocations = nowResult.baseLocations;
+ locationService.baseLocations = newCache.baseLocations;
await writeToJsonFile<MemoriesCache>(
await _getCachePath(),
newCache,
@@ -636,6 +648,89 @@ class MemoriesCacheService {
);
}
+ static bool _shouldPreferTripCacheEntry(
+ ToShowMemory candidate,
+ ToShowMemory existing, {
+ required int nowMicros,
+ }) {
+ final candidateActive = candidate.isRelevantAt(nowMicros);
+ final existingActive = existing.isRelevantAt(nowMicros);
+ if (candidateActive != existingActive) {
+ return candidateActive;
+ }
+ if (candidate.firstTimeToShow != existing.firstTimeToShow) {
+ return candidate.firstTimeToShow < existing.firstTimeToShow;
+ }
+ if (candidate.lastTimeToShow != existing.lastTimeToShow) {
+ return candidate.lastTimeToShow > existing.lastTimeToShow;
+ }
+ return candidate.calculationTime > existing.calculationTime;
+ }
+
+ static List<ToShowMemory> _dedupeTripCacheEntriesInOrder(
+ List<ToShowMemory> memories, {
+ required int nowMicros,
+ }) {
+ final preferredEntries = <String, ToShowMemory>{};
+ for (final memory in memories) {
+ if (memory.type != MemoryType.trips) continue;
+ final identityKey = memory.tripIdentityKey;
+ final existing = preferredEntries[identityKey];
+ if (existing == null ||
+ _shouldPreferTripCacheEntry(
+ memory,
+ existing,
+ nowMicros: nowMicros,
+ )) {
+ preferredEntries[identityKey] = memory;
+ }
+ }
+
+ final emittedKeys = <String>{};
+ final result = <ToShowMemory>[];
+ for (final memory in memories) {
+ if (memory.type != MemoryType.trips) {
+ result.add(memory);
+ continue;
+ }
+ final identityKey = memory.tripIdentityKey;
+ if (emittedKeys.contains(identityKey)) {
+ continue;
+ }
+ if (preferredEntries[identityKey] == memory) {
+ result.add(memory);
+ emittedKeys.add(identityKey);
+ }
+ }
+ return result;
+ }
+
+ static List<ToShowMemory> _activeTripEntriesForTime(
+ Iterable<ToShowMemory> memories, {
+ required int timestamp,
+ }) {
+ final activeTrips = memories
+ .where(
+ (memory) =>
+ memory.type == MemoryType.trips && memory.isRelevantAt(timestamp),
+ )
+ .toList();
+ final dedupedActiveTrips = _dedupeTripCacheEntriesInOrder(
+ activeTrips,
+ nowMicros: timestamp,
+ );
+ dedupedActiveTrips.sort((a, b) {
+ final firstCompare = a.firstTimeToShow.compareTo(b.firstTimeToShow);
+ if (firstCompare != 0) {
+ return firstCompare;
+ }
+ return a.lastTimeToShow.compareTo(b.lastTimeToShow);
+ });
+ return dedupedActiveTrips
+ .take(_tripMemoryCarryForwardLimit)
+ .toList(growable: false);
+ }
+
Future<String> _getCachePath() async {
final suffix = isOfflineMode ? "_offline" : "";
return (await getApplicationSupportDirectory()).path +
@@ -687,8 +782,10 @@ class MemoriesCacheService {
final List<PeopleShownLog> peopleShownLogs = [];
final List<ClipShownLog> clipShownLogs = [];
final List<TripsShownLog> tripsShownLogs = [];
+ final List<ToShowMemory> toShowMemories = [];
if (oldCache != null) {
final now = DateTime.now();
+ final nowMicros = now.microsecondsSinceEpoch;
for (final peopleLog in oldCache.peopleShownLogs) {
if (now.difference(
DateTime.fromMicrosecondsSinceEpoch(peopleLog.lastTimeShown),
@@ -713,6 +810,12 @@ class MemoriesCacheService {
clipShownLogs.add(clipLog);
}
}
+ toShowMemories.addAll(
+ _activeTripEntriesForTime(
+ oldCache.toShowMemories,
+ timestamp: nowMicros,
+ ),
+ );
for (final oldMemory in oldCache.toShowMemories) {
if (oldMemory.isOld) {
if (oldMemory.type == MemoryType.people) {
@@ -726,7 +829,7 @@ class MemoriesCacheService {
}
}
return MemoriesCache(
- toShowMemories: [],
+ toShowMemories: toShowMemories,
peopleShownLogs: peopleShownLogs,
clipShownLogs: clipShownLogs,
tripsShownLogs: tripsShownLogs,
diff --git a/mobile/apps/photos/lib/services/smart_memories_service.dart b/mobile/apps/photos/lib/services/smart_memories_service.dart
index 8864d273da..4908fe7571 100644
--- a/mobile/apps/photos/lib/services/smart_memories_service.dart
+++ b/mobile/apps/photos/lib/services/smart_memories_service.dart
@@ -749,6 +749,7 @@ class SmartMemoriesService {
now,
oldCache.tripsShownLogs,
surfaceAll: debugSurfaceAll,
+ cachedTripMemories: oldCache.toShowMemories,
isOfflineMode: isOfflineMode,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
@@ -937,6 +938,7 @@ class SmartMemoriesService {
DateTime currentTime,
List<TripsShownLog> shownTrips, {
bool surfaceAll = false,
+ required Iterable<ToShowMemory> cachedTripMemories,
required bool isOfflineMode,
required Map<int, int> seenTimes,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
@@ -951,6 +953,7 @@ class SmartMemoriesService {
currentTime,
shownTrips,
surfaceAll: surfaceAll,
+ cachedTripMemories: cachedTripMemories,
isOfflineMode: isOfflineMode,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
diff --git a/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dart b/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dart
index 29a677d013..ff84530761 100644
--- a/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dart
+++ b/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dart
@@ -56,6 +56,34 @@ class _LocationCluster {
}
}
+class _TripAnniversaryWindow {
+ final DateTime start;
+ final DateTime end;
+ final int distanceDays;
+
+ const _TripAnniversaryWindow({
+ required this.start,
+ required this.end,
+ required this.distanceDays,
+ });
+}
+
+class _TripSurfaceCandidate {
+ final TripMemory trip;
+ final String identityKey;
+ final _TripAnniversaryWindow anniversaryWindow;
+ final DateTime? lastShownAt;
+ final bool cooldownExpired;
+
+ const _TripSurfaceCandidate({
+ required this.trip,
+ required this.identityKey,
+ required this.anniversaryWindow,
+ required this.lastShownAt,
+ required this.cooldownExpired,
+ });
+}
+
class TripMemoriesCalculatorV2 {
// Temporal gap to split photos into separate time windows.
static const _maxTemporalGapDays = 15;
@@ -100,12 +128,16 @@ class TripMemoriesCalculatorV2 {
// Max spatial distance (in km) for merging trips across temporal blocks.
static const _mergeMaxDistance = 25.0;
+ static const _tripDisplayDuration = Duration(days: 10);
+ static const _seasonalTripBandDays = 45;
+
static Future<(List<TripMemory>, List<BaseLocation>)> compute(
Iterable<EnteFile> allFiles,
Map<int, EnteFile> allFileIdsToFile,
DateTime currentTime,
List<TripsShownLog> shownTrips, {
bool surfaceAll = false,
+ required Iterable<ToShowMemory> cachedTripMemories,
required bool isOfflineMode,
required Map<int, int> seenTimes,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
@@ -119,7 +151,6 @@ class TripMemoriesCalculatorV2 {
final nowInMicroseconds = currentTime.microsecondsSinceEpoch;
final windowEnd =
currentTime.add(kMemoriesUpdateFrequency).microsecondsSinceEpoch;
- final currentMonth = currentTime.month;
final cutOffTime = currentTime.subtract(const Duration(days: 365));
// ── Phase 1: Base location detection ──
@@ -168,6 +199,11 @@ class TripMemoriesCalculatorV2 {
0,
0,
location,
+ tripKey: _buildTripKey(
+ location,
+ files.first.creationTime!,
+ files.last.creationTime!,
+ ),
firstCreationTime: files.first.creationTime!,
lastCreationTime: files.last.creationTime!,
),
@@ -185,6 +221,7 @@ class TripMemoriesCalculatorV2 {
t.memories.length >= _minTripPhotos &&
t.averageCreationTime() < cutOffTime.microsecondsSinceEpoch,
)
+ .map(_ensureTripKey)
.toList();
// ── Phase 3: Surface selection ──
@@ -214,10 +251,9 @@ class TripMemoriesCalculatorV2 {
baseLocations,
validTrips,
currentTime,
- currentMonth,
nowInMicroseconds,
- windowEnd,
shownTrips,
+ cachedTripMemories: cachedTripMemories,
isOfflineMode: isOfflineMode,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
@@ -382,12 +418,9 @@ class TripMemoriesCalculatorV2 {
) {
if (clusters.length <= 1) return clusters;
- // Sort clusters by their earliest photo time
final sortedClusters = List<_LocationCluster>.from(clusters)
..sort((a, b) => a.firstCreationTime.compareTo(b.firstCreationTime));
- // Separate clusters large enough to chain from tiny ones that should
- // stay standalone (they'll be filtered out later by _isValidTrip).
final chainable = <_LocationCluster>[];
final tooSmall = <_LocationCluster>[];
for (final cluster in sortedClusters) {
@@ -410,7 +443,8 @@ class TripMemoriesCalculatorV2 {
DateTime.fromMicrosecondsSinceEpoch(next.firstCreationTime)
.difference(
DateTime.fromMicrosecondsSinceEpoch(
- currentCluster.lastCreationTime),
+ currentCluster.lastCreationTime,
+ ),
)
.inDays;
final allFiles = [...currentCluster.files, ...next.files];
@@ -429,7 +463,6 @@ class TripMemoriesCalculatorV2 {
}
merged.add(currentCluster);
- // Return both chained results and the too-small standalone clusters
return [...merged, ...tooSmall];
}
@@ -546,15 +579,24 @@ class TripMemoriesCalculatorV2 {
final mergedSpanDays = mergedLast.difference(mergedFirst).inDays;
if (timeClose && spaceClose && mergedSpanDays <= _maxTripDays) {
final combinedMemories = other.memories + trip.memories;
+ final mergedLocation =
+ _representativeLocationFromMemories(combinedMemories);
+ final mergedFirstCreationTime =
+ min(other.firstCreationTime!, trip.firstCreationTime!);
+ final mergedLastCreationTime =
+ max(other.lastCreationTime!, trip.lastCreationTime!);
merged[i] = TripMemory(
combinedMemories,
0,
0,
- _representativeLocationFromMemories(combinedMemories),
- firstCreationTime:
- min(other.firstCreationTime!, trip.firstCreationTime!),
- lastCreationTime:
- max(other.lastCreationTime!, trip.lastCreationTime!),
+ mergedLocation,
+ tripKey: _buildTripKey(
+ mergedLocation,
+ mergedFirstCreationTime,
+ mergedLastCreationTime,
+ ),
+ firstCreationTime: mergedFirstCreationTime,
+ lastCreationTime: mergedLastCreationTime,
);
didMerge = true;
break;
@@ -603,6 +645,210 @@ class TripMemoriesCalculatorV2 {
);
}
+ static TripMemory _ensureTripKey(TripMemory trip) {
+ if (trip.tripKey != null && trip.tripKey!.isNotEmpty) {
+ return trip;
+ }
+ return trip.copyWith(
+ tripKey: _buildTripKey(
+ trip.location,
+ trip.firstCreationTime!,
+ trip.lastCreationTime!,
+ ),
+ );
+ }
+
+ static String _buildTripKey(
+ Location location,
+ int firstCreationTime,
+ int lastCreationTime,
+ ) {
+ final latitude = (location.latitude ?? 0).toStringAsFixed(2);
+ final longitude = (location.longitude ?? 0).toStringAsFixed(2);
+ final firstDay = firstCreationTime ~/ microSecondsInDay;
+ final lastDay = lastCreationTime ~/ microSecondsInDay;
+ return "trip_${latitude}_${longitude}_${firstDay}_$lastDay";
+ }
+
+ static String _tripIdentityKey(TripMemory trip) {
+ return "trip:${_ensureTripKey(trip).tripKey!}";
+ }
+
+ static List<String> _activeCachedTripIdentityKeys(
+ Iterable<ToShowMemory> cachedTripMemories,
+ DateTime currentTime,
+ ) {
+ final nowMicros = currentTime.microsecondsSinceEpoch;
+ final active = <String>[];
+ final seen = <String>{};
+ for (final cachedTrip in cachedTripMemories) {
+ if (cachedTrip.type != MemoryType.trips ||
+ !cachedTrip.isRelevantAt(nowMicros)) {
+ continue;
+ }
+ final identityKey = cachedTrip.tripIdentityKey;
+ if (seen.add(identityKey)) {
+ active.add(identityKey);
+ }
+ }
+ return active.take(kTripSurfaceSlots).toList(growable: false);
+ }
+
+ static DateTime? _lastShownAtForTrip(
+ TripMemory trip,
+ List<TripsShownLog> shownTrips,
+ ) {
+ DateTime? latestShownAt;
+ final tripKey = trip.tripKey;
+ for (final shownTrip in shownTrips) {
+ final sameTripKey = tripKey != null &&
+ shownTrip.tripKey != null &&
+ tripKey == shownTrip.tripKey;
+ final sameLegacyLocation = shownTrip.tripKey == null &&
+ calculateDistance(trip.location, shownTrip.location) <
+ _baseOverlapRadius;
+ if (!sameTripKey && !sameLegacyLocation) {
+ continue;
+ }
+ final shownAt = DateTime.fromMicrosecondsSinceEpoch(
+ shownTrip.lastTimeShown,
+ );
+ if (latestShownAt == null || shownAt.isAfter(latestShownAt)) {
+ latestShownAt = shownAt;
+ }
+ }
+ return latestShownAt;
+ }
+
+ static _TripAnniversaryWindow _nearestAnniversaryWindow(
+ TripMemory trip,
+ DateTime currentTime,
+ ) {
+ final tripStart =
+ DateTime.fromMicrosecondsSinceEpoch(trip.firstCreationTime!);
+ final tripEnd = DateTime.fromMicrosecondsSinceEpoch(trip.lastCreationTime!);
+ final yearOffset = tripEnd.year - tripStart.year;
+ _TripAnniversaryWindow? bestWindow;
+
+ for (final startYear in <int>[
+ currentTime.year - 1,
+ currentTime.year,
+ currentTime.year + 1,
+ ]) {
+ final projectedStart = _copyDateToYear(tripStart, startYear);
+ final projectedEnd = _copyDateToYear(tripEnd, startYear + yearOffset);
+ final candidateWindow = _TripAnniversaryWindow(
+ start: projectedStart,
+ end: projectedEnd,
+ distanceDays: _distanceToWindowInDays(
+ currentTime,
+ projectedStart,
+ projectedEnd,
+ ),
+ );
+ if (bestWindow == null ||
+ candidateWindow.distanceDays < bestWindow.distanceDays ||
+ (candidateWindow.distanceDays == bestWindow.distanceDays &&
+ candidateWindow.start.difference(currentTime).abs().compareTo(
+ bestWindow.start.difference(currentTime).abs(),
+ ) <
+ 0)) {
+ bestWindow = candidateWindow;
+ }
+ }
+
+ return bestWindow!;
+ }
+
+ static DateTime _copyDateToYear(DateTime source, int year) {
+ final lastDayOfMonth = DateTime(year, source.month + 1, 0).day;
+ final day = min(source.day, lastDayOfMonth);
+ return DateTime(
+ year,
+ source.month,
+ day,
+ source.hour,
+ source.minute,
+ source.second,
+ source.millisecond,
+ source.microsecond,
+ );
+ }
+
+ static int _distanceToWindowInDays(
+ DateTime currentTime,
+ DateTime start,
+ DateTime end,
+ ) {
+ if (!currentTime.isBefore(start) && !currentTime.isAfter(end)) {
+ return 0;
+ }
+ if (currentTime.isBefore(start)) {
+ return start.difference(currentTime).inDays;
+ }
+ return currentTime.difference(end).inDays;
+ }
+
+ static int _compareBoolFalseFirst(bool a, bool b) {
+ if (a == b) return 0;
+ return a ? 1 : -1;
+ }
+
+ static int _compareLastShownOldestFirst(DateTime? a, DateTime? b) {
+ if (a == null && b == null) return 0;
+ if (a == null) return -1;
+ if (b == null) return 1;
+ return a.compareTo(b);
+ }
+
+ static int _compareSeasonalCandidates(
+ _TripSurfaceCandidate a,
+ _TripSurfaceCandidate b,
+ ) {
+ final cooldownCompare = _compareBoolFalseFirst(
+ !a.cooldownExpired,
+ !b.cooldownExpired,
+ );
+ if (cooldownCompare != 0) return cooldownCompare;
+
+ final distanceCompare = a.anniversaryWindow.distanceDays.compareTo(
+ b.anniversaryWindow.distanceDays,
+ );
+ if (distanceCompare != 0) return distanceCompare;
+
+ final shownCompare = _compareLastShownOldestFirst(
+ a.lastShownAt,
+ b.lastShownAt,
+ );
+ if (shownCompare != 0) return shownCompare;
+
+ return b.trip.averageCreationTime().compareTo(a.trip.averageCreationTime());
+ }
+
+ static int _compareEvergreenCandidates(
+ _TripSurfaceCandidate a,
+ _TripSurfaceCandidate b,
+ ) {
+ final cooldownCompare = _compareBoolFalseFirst(
+ !a.cooldownExpired,
+ !b.cooldownExpired,
+ );
+ if (cooldownCompare != 0) return cooldownCompare;
+
+ final shownCompare = _compareLastShownOldestFirst(
+ a.lastShownAt,
+ b.lastShownAt,
+ );
+ if (shownCompare != 0) return shownCompare;
+
+ final distanceCompare = a.anniversaryWindow.distanceDays.compareTo(
+ b.anniversaryWindow.distanceDays,
+ );
+ if (distanceCompare != 0) return distanceCompare;
+
+ return b.trip.averageCreationTime().compareTo(a.trip.averageCreationTime());
+ }
+
// ── Surface all (debug mode) ──
static Future<(List<TripMemory>, List<BaseLocation>)> _surfaceAll(
@@ -680,10 +926,9 @@ class TripMemoriesCalculatorV2 {
List<BaseLocation> baseLocations,
List<TripMemory> validTrips,
DateTime currentTime,
- int currentMonth,
int nowInMicroseconds,
- int windowEnd,
List<TripsShownLog> shownTrips, {
+ required Iterable<ToShowMemory> cachedTripMemories,
required bool isOfflineMode,
required Map<int, int> seenTimes,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
@@ -692,130 +937,123 @@ class TripMemoriesCalculatorV2 {
required Vector clipPositiveTextVector,
required List<City> cities,
}) async {
- final Map<int, Map<int, List<TripMemory>>> tripsByMonthYear = {};
- for (final trip in validTrips) {
- final tripDate =
- DateTime.fromMicrosecondsSinceEpoch(trip.averageCreationTime());
- tripsByMonthYear
- .putIfAbsent(tripDate.month, () => {})
- .putIfAbsent(tripDate.year, () => [])
- .add(trip);
+ final activeTripIdentityKeys = _activeCachedTripIdentityKeys(
+ cachedTripMemories,
+ currentTime,
+ );
+ final remainingSlots =
+ max(0, kTripSurfaceSlots - activeTripIdentityKeys.length);
+ if (remainingSlots == 0 || validTrips.isEmpty) {
+ return (memoryResults, baseLocations);
}
- final List<TripMemory> currentMonthTrips = [];
- if (tripsByMonthYear.containsKey(currentMonth)) {
- for (final trips in tripsByMonthYear[currentMonth]!.values) {
- currentMonthTrips.addAll(trips);
+ final excludedIdentityKeys = activeTripIdentityKeys.toSet();
+ final candidates = <_TripSurfaceCandidate>[];
+ for (final trip in validTrips) {
+ final identityKey = _tripIdentityKey(trip);
+ if (excludedIdentityKeys.contains(identityKey)) {
+ continue;
}
+ final lastShownAt = _lastShownAtForTrip(trip, shownTrips);
+ final cooldownExpired = lastShownAt == null ||
+ currentTime.difference(lastShownAt) >= kTripShowTimeout;
+ candidates.add(
+ _TripSurfaceCandidate(
+ trip: trip,
+ identityKey: identityKey,
+ anniversaryWindow: _nearestAnniversaryWindow(trip, currentTime),
+ lastShownAt: lastShownAt,
+ cooldownExpired: cooldownExpired,
+ ),
+ );
}
- if (currentMonthTrips.isNotEmpty) {
- currentMonthTrips.sort(
- (a, b) => b.averageCreationTime().compareTo(a.averageCreationTime()),
- );
- final tripsToShow = currentMonthTrips.take(2);
- for (final trip in tripsToShow) {
- final year =
- DateTime.fromMicrosecondsSinceEpoch(trip.averageCreationTime())
- .year;
- final String? locationName = SmartMemoriesService._tryFindLocationName(
- trip.memories,
- cities,
- );
- final photoSelection = await SmartMemoriesService._bestSelection(
- trip.memories,
- isOfflineMode: isOfflineMode,
- fileIdToFaces: fileIdToFaces,
- faceIDsToPersonID: faceIDsToPersonID,
- fileIDToImageEmbedding: fileIDToImageEmbedding,
- clipPositiveTextVector: clipPositiveTextVector,
- );
- final firstCreationDate = DateTime.fromMicrosecondsSinceEpoch(
- trip.firstCreationTime!,
- );
- final firstDateToShow = DateTime(
- currentTime.year,
- firstCreationDate.month,
- firstCreationDate.day,
- ).subtract(kMemoriesMargin).microsecondsSinceEpoch;
- final lastCreationDate = DateTime.fromMicrosecondsSinceEpoch(
- trip.lastCreationTime!,
- );
- final lastDateToShow = DateTime(
- currentTime.year,
- lastCreationDate.month,
- lastCreationDate.day,
- ).add(kMemoriesMargin).microsecondsSinceEpoch;
- memoryResults.add(
- trip.copyWith(
- memories: photoSelection,
- tripYear: year,
- locationName: locationName,
- firstDateToShow: firstDateToShow,
- lastDateToShow: lastDateToShow,
- ),
- );
+ final selectedCandidates = <_TripSurfaceCandidate>[];
+ final selectedKeys = <String>{...excludedIdentityKeys};
+
+ final seasonalCandidates = candidates
+ .where(
+ (candidate) =>
+ candidate.cooldownExpired &&
+ candidate.anniversaryWindow.distanceDays <= _seasonalTripBandDays,
+ )
+ .where((candidate) => !selectedKeys.contains(candidate.identityKey))
+ .toList()
+ ..sort(_compareSeasonalCandidates);
+ for (final seasonalCandidate in seasonalCandidates) {
+ if (selectedCandidates.length >= remainingSlots) break;
+ selectedCandidates.add(seasonalCandidate);
+ selectedKeys.add(seasonalCandidate.identityKey);
+ }
+
+ final evergreenCandidates = candidates
+ .where(
+ (candidate) =>
+ candidate.cooldownExpired &&
+ !selectedKeys.contains(candidate.identityKey),
+ )
+ .toList()
+ ..sort(_compareEvergreenCandidates);
+ for (final candidate in evergreenCandidates) {
+ if (selectedCandidates.length >= remainingSlots) {
+ break;
}
- } else {
- final sortedUpcomingMonths =
- List<int>.generate(6, (i) => ((currentMonth + i) % 12) + 1);
- checkUpcomingMonths:
- for (final month in sortedUpcomingMonths) {
- if (tripsByMonthYear.containsKey(month)) {
- final List<TripMemory> thatMonthTrips = [];
- for (final trips in tripsByMonthYear[month]!.values) {
- thatMonthTrips.addAll(trips);
- }
- if (thatMonthTrips.length >= 3) {
- thatMonthTrips.sort(
- (a, b) =>
- a.averageCreationTime().compareTo(b.averageCreationTime()),
- );
- checkPotentialTrips:
- for (final trip in thatMonthTrips.sublist(2)) {
- for (final shownTrip in shownTrips) {
- final distance =
- calculateDistance(trip.location, shownTrip.location);
- final shownTripDate = DateTime.fromMicrosecondsSinceEpoch(
- shownTrip.lastTimeShown,
- );
- final shownRecently =
- currentTime.difference(shownTripDate) < kTripShowTimeout;
- if (distance < _baseOverlapRadius && shownRecently) {
- continue checkPotentialTrips;
- }
- }
- final year = DateTime.fromMicrosecondsSinceEpoch(
- trip.averageCreationTime(),
- ).year;
- final String? locationName =
- SmartMemoriesService._tryFindLocationName(
- trip.memories,
- cities,
- );
- final photoSelection = await SmartMemoriesService._bestSelection(
- trip.memories,
- isOfflineMode: isOfflineMode,
- fileIdToFaces: fileIdToFaces,
- faceIDsToPersonID: faceIDsToPersonID,
- fileIDToImageEmbedding: fileIDToImageEmbedding,
- clipPositiveTextVector: clipPositiveTextVector,
- );
- memoryResults.add(
- trip.copyWith(
- memories: photoSelection,
- tripYear: year,
- locationName: locationName,
- firstDateToShow: nowInMicroseconds,
- lastDateToShow: windowEnd,
- ),
- );
- break checkUpcomingMonths;
- }
- }
- }
+ selectedCandidates.add(candidate);
+ selectedKeys.add(candidate.identityKey);
+ }
+
+ final currentShownCount =
+ activeTripIdentityKeys.length + selectedCandidates.length;
+ if (isOfflineMode && currentShownCount == 0 && candidates.isNotEmpty) {
+ final fallbackSeasonalCandidates = candidates
+ .where(
+ (candidate) =>
+ candidate.anniversaryWindow.distanceDays <=
+ _seasonalTripBandDays &&
+ !selectedKeys.contains(candidate.identityKey),
+ )
+ .toList()
+ ..sort(_compareSeasonalCandidates);
+ final fallbackCandidates = fallbackSeasonalCandidates.isNotEmpty
+ ? fallbackSeasonalCandidates
+ : (candidates..sort(_compareEvergreenCandidates))
+ .where(
+ (candidate) => !selectedKeys.contains(candidate.identityKey),
+ )
+ .toList();
+ if (fallbackCandidates.isNotEmpty) {
+ selectedCandidates.add(fallbackCandidates.first);
}
}
+
+ final lastDateToShow =
+ currentTime.add(_tripDisplayDuration).microsecondsSinceEpoch;
+ for (final candidate in selectedCandidates) {
+ final trip = candidate.trip;
+ final year =
+ DateTime.fromMicrosecondsSinceEpoch(trip.averageCreationTime()).year;
+ final String? locationName = SmartMemoriesService._tryFindLocationName(
+ trip.memories,
+ cities,
+ );
+ final photoSelection = await SmartMemoriesService._bestSelection(
+ trip.memories,
+ isOfflineMode: isOfflineMode,
+ fileIdToFaces: fileIdToFaces,
+ faceIDsToPersonID: faceIDsToPersonID,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipPositiveTextVector: clipPositiveTextVector,
+ );
+ memoryResults.add(
+ trip.copyWith(
+ memories: photoSelection,
+ tripYear: year,
+ locationName: locationName,
+ firstDateToShow: nowInMicroseconds,
+ lastDateToShow: lastDateToShow,
+ ),
+ );
+ }
return (memoryResults, baseLocations);
}
}
diff --git a/mobile/apps/photos/test/models/memories/memories_cache_validation_test.dart b/mobile/apps/photos/test/models/memories/memories_cache_validation_test.dart
index 7c9bf58f65..15b76fd645 100644
--- a/mobile/apps/photos/test/models/memories/memories_cache_validation_test.dart
+++ b/mobile/apps/photos/test/models/memories/memories_cache_validation_test.dart
@@ -108,6 +108,7 @@ void main() {
id: "trip-typed",
locationName: "Paris",
tripYear: 2021,
+ tripKey: "trip-paris-2021",
)..title = "Stored trip title";
final timeMemory = TimeMemory(
@@ -179,6 +180,7 @@ void main() {
id: "trip-cache",
locationName: "New York",
tripYear: 2020,
+ tripKey: "trip-nyc-2020",
)..title = "Stored typed trip title",
calcTime,
);
@@ -214,6 +216,7 @@ void main() {
expect(decoded.toShowMemories.last.hasTypedSpec, isFalse);
expect(decoded.toShowMemories.first.id, "trip-cache");
expect(decoded.toShowMemories.last.id, "trip-legacy-cache");
+ expect(decoded.toShowMemories.first.tripKey, "trip-nyc-2020");
});
});
}