π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] base locations in locations section
laurensprieme2aea632761f
diff --git a/mobile/lib/models/base_location.dart b/mobile/lib/models/base_location.dartindex 38b7847c64..b7834fd089 100644--- a/mobile/lib/models/base_location.dart+++ b/mobile/lib/models/base_location.dart@@ -1,6 +1,10 @@+import "dart:convert";+import "package:photos/models/file/file.dart";import "package:photos/models/location/location.dart";+const baseRadius = 0.6;+class BaseLocation {final List<EnteFile> files;int? firstCreationTime;@@ -16,6 +20,54 @@ class BaseLocation {this.lastCreationTime,});+ static List<BaseLocation> decodeJsonToList(+ String jsonString,+ Map<int, EnteFile> filesMap,+ ) {+ final jsonList = jsonDecode(jsonString) as List;+ return jsonList+ .map((json) => BaseLocation.fromJson(json, filesMap))+ .toList();+ }++ static String encodeListToJson(List<BaseLocation> baseLocations) {+ final jsonList =+ baseLocations.map((location) => location.toJson()).toList();+ return jsonEncode(jsonList);+ }++ static BaseLocation fromJson(+ Map<String, dynamic> json,+ Map<int, EnteFile> filesMap,+ ) {+ return BaseLocation(+ (json['fileIDs'] as List).map((e) => filesMap[e]!).toList(),+ Location(+ latitude: json['location']['latitude'],+ longitude: json['location']['longitude'],+ ),+ json['isCurrentBase'] as bool,+ firstCreationTime: json['firstCreationTime'] as int?,+ lastCreationTime: json['lastCreationTime'] as int?,+ );+ }++ Map<String, dynamic> toJson() {+ return {+ 'fileIDs': files+ .where((file) => file.uploadedFileID != null)+ .map((file) => file.uploadedFileID!)+ .toList(),+ 'location': {+ 'latitude': location.latitude!,+ 'longitude': location.longitude!,+ },+ 'isCurrentBase': isCurrentBase,+ 'firstCreationTime': firstCreationTime,+ 'lastCreationTime': lastCreationTime,+ };+ }+int averageCreationTime() {if (firstCreationTime != null && lastCreationTime != null) {return (firstCreationTime! + lastCreationTime!) ~/ 2;diff --git a/mobile/lib/models/memories/memories_cache.dart b/mobile/lib/models/memories/memories_cache.dartindex 5298c7f81a..06a57341d9 100644--- a/mobile/lib/models/memories/memories_cache.dart+++ b/mobile/lib/models/memories/memories_cache.dart@@ -1,5 +1,7 @@import "dart:convert";+import "package:photos/models/base_location.dart";+import "package:photos/models/file/file.dart";import "package:photos/models/location/location.dart";import "package:photos/models/memories/people_memory.dart";import "package:photos/models/memories/smart_memory.dart";@@ -20,18 +22,29 @@ class MemoriesCache {final List<ToShowMemory> toShowMemories;final List<PeopleShownLog> peopleShownLogs;final List<TripsShownLog> tripsShownLogs;+ final List<BaseLocation> baseLocations;MemoriesCache({required this.toShowMemories,required this.peopleShownLogs,required this.tripsShownLogs,+ required this.baseLocations,});- factory MemoriesCache.fromJson(Map<String, dynamic> json) {+ factory MemoriesCache.fromJson(+ Map<String, dynamic> json,+ Map<int, EnteFile> filesMap,+ ) {return MemoriesCache(toShowMemories: ToShowMemory.decodeJsonToList(json['toShowMemories']),peopleShownLogs: PeopleShownLog.decodeJsonToList(json['peopleShownLogs']),tripsShownLogs: TripsShownLog.decodeJsonToList(json['tripsShownLogs']),+ baseLocations: json['baseLocations'] != null+ ? BaseLocation.decodeJsonToList(+ json['baseLocations'],+ filesMap,+ )+ : [],);}@@ -40,6 +53,7 @@ class MemoriesCache {'toShowMemories': ToShowMemory.encodeListToJson(toShowMemories),'peopleShownLogs': PeopleShownLog.encodeListToJson(peopleShownLogs),'tripsShownLogs': TripsShownLog.encodeListToJson(tripsShownLogs),+ 'baseLocations': BaseLocation.encodeListToJson(baseLocations),};}@@ -47,8 +61,11 @@ class MemoriesCache {return jsonEncode(cache.toJson());}- static MemoriesCache decodeFromJsonString(String jsonString) {- return MemoriesCache.fromJson(jsonDecode(jsonString));+ static MemoriesCache decodeFromJsonString(+ String jsonString,+ Map<int, EnteFile> filesMap,+ ) {+ return MemoriesCache.fromJson(jsonDecode(jsonString), filesMap);}}diff --git a/mobile/lib/services/location_service.dart b/mobile/lib/services/location_service.dartindex cd00ac4c85..f0b20a44a4 100644--- a/mobile/lib/services/location_service.dart+++ b/mobile/lib/services/location_service.dart@@ -10,6 +10,7 @@ import "package:photos/core/event_bus.dart";import "package:photos/events/location_tag_updated_event.dart";import "package:photos/extensions/stop_watch.dart";import "package:photos/models/api/entity/type.dart";+import "package:photos/models/base_location.dart";import "package:photos/models/file/file.dart";import "package:photos/models/local_entity_data.dart";import "package:photos/models/location/location.dart";@@ -33,6 +34,8 @@ class LocationService {List<City> _cities = [];+ List<BaseLocation> baseLocations = [];+LocationService(this.prefs) {debugPrint('LocationService constructor');Future.delayed(const Duration(seconds: 3), () {diff --git a/mobile/lib/services/memories_cache_service.dart b/mobile/lib/services/memories_cache_service.dartindex fdbb362d3f..649204e719 100644--- a/mobile/lib/services/memories_cache_service.dart+++ b/mobile/lib/services/memories_cache_service.dart@@ -140,26 +140,27 @@ class MemoriesCacheService {// calculate memories for this period and for the next periodfinal now = DateTime.now();final next = now.add(kMemoriesUpdateFrequency);- final nowMemories =- await smartMemoriesService.calcMemories(now, newCache);- final nextMemories =+ final nowResult = await smartMemoriesService.calcMemories(now, newCache);+ final nextResult =await smartMemoriesService.calcMemories(next, newCache);w?.log("calculated new memories");- for (final nowMemory in nowMemories) {+ for (final nowMemory in nowResult.memories) {newCache.toShowMemories.add(ToShowMemory.fromSmartMemory(nowMemory, now));}- for (final nextMemory in nextMemories) {+ for (final nextMemory in nextResult.memories) {newCache.toShowMemories.add(ToShowMemory.fromSmartMemory(nextMemory, next));}+ newCache.baseLocations.addAll(nowResult.baseLocations);w?.log("added memories to cache");final file = File(await _getCachePath());if (!file.existsSync()) {file.createSync(recursive: true);}_cachedMemories =- nowMemories.where((memory) => memory.shouldShowNow()).toList();+ nowResult.memories.where((memory) => memory.shouldShowNow()).toList();+ locationService.baseLocations = nowResult.baseLocations;await file.writeAsBytes(MemoriesCache.encodeToJsonString(newCache).codeUnits,);@@ -174,8 +175,14 @@ class MemoriesCacheService {}}+ /// WARNING: Use for testing only, TODO: lau: remove later+ Future<MemoriesCache> debugCacheForTesting() async {+ final oldCache = await _readCacheFromDisk();+ final MemoriesCache newCache = _processOldCache(oldCache);+ return newCache;+ }+MemoriesCache _processOldCache(MemoriesCache? oldCache) {- final List<ToShowMemory> toShowMemories = [];final List<PeopleShownLog> peopleShownLogs = [];final List<TripsShownLog> tripsShownLogs = [];if (oldCache != null) {@@ -221,9 +228,10 @@ class MemoriesCacheService {}}return MemoriesCache(- toShowMemories: toShowMemories,+ toShowMemories: [],peopleShownLogs: peopleShownLogs,tripsShownLogs: tripsShownLogs,+ baseLocations: [],);}@@ -259,6 +267,7 @@ class MemoriesCacheService {);}}+ locationService.baseLocations = cache.baseLocations;_logger.info('Processing of disk cache memories done');return memories;} catch (e, s) {@@ -294,8 +303,17 @@ class MemoriesCacheService {_logger.info("No memories cache found");return null;}+ final allFiles = Set<EnteFile>.from(+ await SearchService.instance.getAllFilesForSearch(),+ );+ final allFileIdsToFile = <int, EnteFile>{};+ for (final file in allFiles) {+ if (file.uploadedFileID != null) {+ allFileIdsToFile[file.uploadedFileID!] = file;+ }+ }final jsonString = file.readAsStringSync();- return MemoriesCache.decodeFromJsonString(jsonString);+ return MemoriesCache.decodeFromJsonString(jsonString, allFileIdsToFile);}Future<void> clearMemoriesCache() async {diff --git a/mobile/lib/services/search_service.dart b/mobile/lib/services/search_service.dartindex ce67a5c229..5e47fae7ee 100644--- a/mobile/lib/services/search_service.dart+++ b/mobile/lib/services/search_service.dart@@ -15,6 +15,7 @@ import "package:photos/db/ml/db.dart";import 'package:photos/events/local_photos_updated_event.dart';import "package:photos/extensions/user_extension.dart";import "package:photos/models/api/collection/user.dart";+import "package:photos/models/base_location.dart";import 'package:photos/models/collection/collection.dart';import 'package:photos/models/collection/collection_items.dart';import "package:photos/models/file/extensions/file_props.dart";@@ -23,7 +24,6 @@ import 'package:photos/models/file/file_type.dart';import "package:photos/models/local_entity_data.dart";import "package:photos/models/location/location.dart";import "package:photos/models/location_tag/location_tag.dart";-import "package:photos/models/memories/memories_cache.dart";import "package:photos/models/memories/memory.dart";import "package:photos/models/ml/face/person.dart";import 'package:photos/models/search/album_search_result.dart';@@ -1049,6 +1049,42 @@ class SearchService {);}}+ // Add the found base locations from the location/memories service+ // TODO: lau: Add base location names+ if (limit == null || tagSearchResults.length < limit) {+ for (final BaseLocation base in locationService.baseLocations) {+ final a = (baseRadius * scaleFactor(base.location.latitude!)) /+ kilometersPerDegree;+ const b = baseRadius / kilometersPerDegree;+ tagSearchResults.add(+ GenericSearchResult(+ ResultType.location,+ "Base",+ base.files,+ onResultTap: (ctx) {+ showAddLocationSheet(+ ctx,+ base.location,+ name: "Base",+ radius: baseRadius,+ );+ },+ hierarchicalSearchFilter: LocationFilter(+ locationTag: LocationTag(+ name: "Base",+ radius: baseRadius,+ centerPoint: base.location,+ aSquare: a * a,+ bSquare: b * b,+ ),+ occurrence: kMostRelevantFilter,+ matchedUploadedIDs: filesToUploadedFileIDs(base.files),+ ),+ ),+ );+ }+ }+if (limit == null || tagSearchResults.length < limit) {final results =await locationService.getFilesInCity(filesWithNoLocTag, '');@@ -1194,15 +1230,12 @@ class SearchService {BuildContext context,int? limit,) async {- final fakeCache = MemoriesCache(- toShowMemories: [],- peopleShownLogs: [],- tripsShownLogs: [],- );- final memories =- await smartMemoriesService.calcMemories(DateTime.now(), fakeCache);+ final cache = await memoriesCacheService.debugCacheForTesting();+ final memoriesResult =+ await smartMemoriesService.calcMemories(DateTime.now(), cache);+ locationService.baseLocations = memoriesResult.baseLocations;final searchResults = <GenericSearchResult>[];- for (final memory in memories) {+ for (final memory in memoriesResult.memories) {final files = Memory.filesFromMemories(memory.memories);searchResults.add(GenericSearchResult(diff --git a/mobile/lib/services/smart_memories_service.dart b/mobile/lib/services/smart_memories_service.dartindex 8a6ce2a7c0..887fc4eedc 100644--- a/mobile/lib/services/smart_memories_service.dart+++ b/mobile/lib/services/smart_memories_service.dart@@ -34,6 +34,13 @@ import "package:photos/services/machine_learning/ml_result.dart";import "package:photos/services/machine_learning/semantic_search/semantic_search_service.dart";import "package:photos/services/search_service.dart";+class MemoriesResult {+ final List<SmartMemory> memories;+ final List<BaseLocation> baseLocations;++ MemoriesResult(this.memories, this.baseLocations);+}+class SmartMemoriesService {final _logger = Logger("SmartMemoriesService");final _memoriesDB = MemoriesDB.instance;@@ -73,7 +80,7 @@ class SmartMemoriesService {}// One general method to get all memories, which calls on internal methods for each separate memory type- Future<List<SmartMemory>> calcMemories(+ Future<MemoriesResult> calcMemories(DateTime now,MemoriesCache oldCache,) async {@@ -94,7 +101,7 @@ class SmartMemoriesService {_logger.finest("All files length: ${allFiles.length}");// Trip memories- final tripMemories =+ final (tripMemories, bases) =await _getTripsResults(allFiles, now, oldCache.tripsShownLogs);_deductUsedMemories(allFiles, tripMemories);memories.addAll(tripMemories);@@ -109,10 +116,10 @@ class SmartMemoriesService {// Filler memoriesfinal fillerMemories = await _getFillerResults(allFiles, now);memories.addAll(fillerMemories);- return memories;+ return MemoriesResult(memories, bases);} catch (e, s) {_logger.severe("Error calculating smart memories", e, s);- return [];+ return MemoriesResult(<SmartMemory>[], <BaseLocation>[]);}}@@ -476,7 +483,7 @@ class SmartMemoriesService {return memoryResults;}- Future<List<TripMemory>> _getTripsResults(+ Future<(List<TripMemory>, List<BaseLocation>)> _getTripsResults(Iterable<EnteFile> allFiles,DateTime currentTime,List<TripsShownLog> shownTrips,@@ -484,14 +491,13 @@ class SmartMemoriesService {final List<TripMemory> memoryResults = [];final Iterable<LocalEntity<LocationTag>> locationTagEntities =(await locationService.getLocationTags());- if (allFiles.isEmpty) return [];+ if (allFiles.isEmpty) return (<TripMemory>[], <BaseLocation>[]);final nowInMicroseconds = currentTime.microsecondsSinceEpoch;final windowEnd =currentTime.add(kMemoriesUpdateFrequency).microsecondsSinceEpoch;final currentMonth = currentTime.month;final cutOffTime = currentTime.subtract(const Duration(days: 365));- const baseRadius = 0.6;const tripRadius = 100.0;const overlapRadius = 10.0;@@ -767,26 +773,27 @@ class SmartMemoriesService {}// For now for testing let's just surface all base locations- for (final baseLocation in baseLocations) {- String name = "Base (${baseLocation.isCurrentBase ? 'current' : 'old'})";- final String? locationName = _tryFindLocationName(- Memory.fromFiles(baseLocation.files, _seenTimes),- base: true,- );- if (locationName != null) {- name =- "$locationName (Base, ${baseLocation.isCurrentBase ? 'current' : 'old'})";- }- memoryResults.add(- TripMemory(- Memory.fromFiles(baseLocation.files, _seenTimes),- name,- 0,- 0,- baseLocation.location,- ),- );- }+ // For now surface these on the location section TODO: lau: remove internal flag title+ // for (final baseLocation in baseLocations) {+ // String name = "Base (${baseLocation.isCurrentBase ? 'current' : 'old'})";+ // final String? locationName = _tryFindLocationName(+ // Memory.fromFiles(baseLocation.files, _seenTimes),+ // base: true,+ // );+ // if (locationName != null) {+ // name =+ // "$locationName (Base, ${baseLocation.isCurrentBase ? 'current' : 'old'})";+ // }+ // memoryResults.add(+ // TripMemory(+ // Memory.fromFiles(baseLocation.files, _seenTimes),+ // name,+ // 0,+ // 0,+ // baseLocation.location,+ // ),+ // );+ // }// For now we surface the two most recent trips of current month, and if none, the earliest upcoming redundant trip// Group the trips per month and then year@@ -912,7 +919,7 @@ class SmartMemoriesService {}}}- return memoryResults;+ return (memoryResults, baseLocations);}Future<List<TimeMemory>> _onThisDayOrWeekResults(