π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
bug fix + handle possible errors with try catch
ashilkn5cf9c30b5f42
diff --git a/lib/services/search_service.dart b/lib/services/search_service.dartindex d00a628c48..db41f88283 100644--- a/lib/services/search_service.dart+++ b/lib/services/search_service.dart@@ -1,3 +1,5 @@+import "dart:math";+import "package:flutter/cupertino.dart";import 'package:logging/logging.dart';import 'package:photos/core/event_bus.dart';@@ -94,25 +96,31 @@ class SearchService {Future<List<AlbumSearchResult>> getAllCollectionSearchResults(int? limit,) async {- final List<Collection> collections = _collectionService.getCollectionsForUI(- includedShared: true,- );+ try {+ final List<Collection> collections =+ _collectionService.getCollectionsForUI(+ includedShared: true,+ );- final List<AlbumSearchResult> collectionSearchResults = [];+ final List<AlbumSearchResult> collectionSearchResults = [];- for (var c in collections) {- if (limit != null && collectionSearchResults.length >= limit) {- break;- }+ for (var c in collections) {+ if (limit != null && collectionSearchResults.length >= limit) {+ break;+ }- if (!c.isHidden() && c.type != CollectionType.uncategorized) {- final EnteFile? thumbnail = await _collectionService.getCover(c);- collectionSearchResults- .add(AlbumSearchResult(CollectionWithThumbnail(c, thumbnail)));+ if (!c.isHidden() && c.type != CollectionType.uncategorized) {+ final EnteFile? thumbnail = await _collectionService.getCover(c);+ collectionSearchResults+ .add(AlbumSearchResult(CollectionWithThumbnail(c, thumbnail)));+ }}- }- return collectionSearchResults;+ return collectionSearchResults;+ } catch (e) {+ _logger.severe("error gettin allCollectionSearchResults", e);+ return Future.value([]);+ }}Future<List<GenericSearchResult>> getYearSearchResults(@@ -140,11 +148,16 @@ class SearchService {Future<List<GenericSearchResult>> getRandomMomentsSearchResults(BuildContext context,) {- final randomYear = getRadomYearSearchResult();- final randomMonth = getRandomMonthSearchResult(context);- final randomHoliday = getRandomHolidaySearchResult(context);+ try {+ final randomYear = getRadomYearSearchResult();+ final randomMonth = getRandomMonthSearchResult(context);+ final randomHoliday = getRandomHolidaySearchResult(context);- return Future.wait([randomYear, randomMonth, randomHoliday]);+ return Future.wait([randomYear, randomMonth, randomHoliday]);+ } catch (e) {+ _logger.severe("Error getting RandomMomentsSearchResult", e);+ return Future.value([]);+ }}Future<GenericSearchResult> getRadomYearSearchResult() async {@@ -293,44 +306,51 @@ class SearchService {final List<EnteFile> allFiles = await getAllFiles();final fileTypesAndMatchingFiles = <FileType, List<EnteFile>>{};final extensionsAndMatchingFiles = <String, List<EnteFile>>{};-- for (EnteFile file in allFiles) {- if (!fileTypesAndMatchingFiles.containsKey(file.fileType)) {- fileTypesAndMatchingFiles[file.fileType] = <EnteFile>[];- }- fileTypesAndMatchingFiles[file.fileType]!.add(file);-- final String fileName = file.displayName;- late final String ext;- //Noticed that some old edited files do not have extensions and a '.'- ext =- fileName.contains(".") ? fileName.split(".").last.toUpperCase() : "";-- if (ext != "") {- if (!extensionsAndMatchingFiles.containsKey(ext)) {- extensionsAndMatchingFiles[ext] = <EnteFile>[];+ try {+ for (EnteFile file in allFiles) {+ if (!fileTypesAndMatchingFiles.containsKey(file.fileType)) {+ fileTypesAndMatchingFiles[file.fileType] = <EnteFile>[];+ }+ fileTypesAndMatchingFiles[file.fileType]!.add(file);++ final String fileName = file.displayName;+ late final String ext;+ //Noticed that some old edited files do not have extensions and a '.'+ ext = fileName.contains(".")+ ? fileName.split(".").last.toUpperCase()+ : "";++ if (ext != "") {+ if (!extensionsAndMatchingFiles.containsKey(ext)) {+ extensionsAndMatchingFiles[ext] = <EnteFile>[];+ }+ extensionsAndMatchingFiles[ext]!.add(file);}- extensionsAndMatchingFiles[ext]!.add(file);}- }- fileTypesAndMatchingFiles.forEach((key, value) {- searchResults- .add(GenericSearchResult(ResultType.fileType, key.name, value));- });+ fileTypesAndMatchingFiles.forEach((key, value) {+ searchResults+ .add(GenericSearchResult(ResultType.fileType, key.name, value));+ });- extensionsAndMatchingFiles.forEach((key, value) {- searchResults- .add(GenericSearchResult(ResultType.fileExtension, key, value));- });+ extensionsAndMatchingFiles.forEach((key, value) {+ searchResults+ .add(GenericSearchResult(ResultType.fileExtension, key, value));+ });- if (limit != null) {- return (searchResults..shuffle()).sublist(0, limit);- } else {- return searchResults;+ if (limit != null) {+ return (searchResults..shuffle())+ .sublist(0, min(limit, searchResults.length));+ } else {+ return searchResults;+ }+ } catch (e) {+ _logger.severe("Error getting allFileTypesAndExtensionsResults", e);+ return Future.value([]);}}+ ///Todo: Optimise + make this function more readable//This can be furthur optimized by not just limiting keys to 0 and 1. Use key//0 for single word, 1 for 2 word, 2 for 3 ..... and only check the substrings//in higher key if there are matches in the lower key.@@ -338,84 +358,72 @@ class SearchService {//todo: use limitint? limit,) async {- final List<GenericSearchResult> searchResults = [];- final List<EnteFile> allFiles = await getAllFiles();-- //each list element will be substrings from a description mapped by- //word count = 1 and word count > 1- //New items will be added to [orderedSubDescriptions] list for every- //description. If total of 5 items have description, there will be 5 items- //in [orderedSubDescriptions] (assuming limit is null).- //[orderedSubDescriptions[x]] has two keys, 0 & 1. Value of key 0 will be single- //word substrings. Value of key 1 will be multi word subStrings. When- //iterating through [allFiles], we check for matching substrings from- //[orderedSubDescriptions[x]] with the file's description. Starts from value- //of key 0 (x=0). If there are no substring matches from key 0, there will- //be none from key 1 as well. So these two keys are for avoiding unnecessary- //checking of all subDescriptions with file description.- final orderedSubDescs = <Map<int, List<String>>>[];- final descAndMatchingFiles = <String, Set<EnteFile>>{};- int distinctFullDescCount = 0;- final allDistinctFullDescs = <String>[];-- for (EnteFile file in allFiles) {- if (file.caption != null && file.caption!.isNotEmpty) {- //This limit doesn't necessarily have to be the limit parameter of the- //method. Using the same variable to avoid unwanted iterations when- //iterating over [orderedSubDescriptions] in case there is a limit- //passed. Using the limit passed here so that there will be almost- //always be more than 7 descriptionAndMatchingFiles and can shuffle- //and choose only limited elements from it. Without shuffling,- //result will be ["hello", "world", "hello world"] for the string- //"hello world"-- if (limit == null || distinctFullDescCount < limit) {- final descAlreadyRecorded = allDistinctFullDescs- .any((element) => element.contains(file.caption!.trim()));-- if (!descAlreadyRecorded) {- distinctFullDescCount++;- allDistinctFullDescs.add(file.caption!.trim());- final words = file.caption!.trim().split(" ");- orderedSubDescs.add({0: <String>[], 1: <String>[]});-- for (int i = 1; i <= words.length; i++) {- for (int j = 0; j <= words.length - i; j++) {- final subList = words.sublist(j, j + i);- final substring = subList.join(" ").toLowerCase();- if (i == 1) {- orderedSubDescs.last[0]!.add(substring);- } else {- orderedSubDescs.last[1]!.add(substring);+ try {+ final List<GenericSearchResult> searchResults = [];+ final List<EnteFile> allFiles = await getAllFiles();++ //each list element will be substrings from a description mapped by+ //word count = 1 and word count > 1+ //New items will be added to [orderedSubDescriptions] list for every+ //distinct description.+ //[orderedSubDescriptions[x]] has two keys, 0 & 1. Value of key 0 will be single+ //word substrings. Value of key 1 will be multi word subStrings. When+ //iterating through [allFiles], we check for matching substrings from+ //[orderedSubDescriptions[x]] with the file's description. Starts from value+ //of key 0 (x=0). If there are no substring matches from key 0, there will+ //be none from key 1 as well. So these two keys are for avoiding unnecessary+ //checking of all subDescriptions with file description.+ final orderedSubDescs = <Map<int, List<String>>>[];+ final descAndMatchingFiles = <String, Set<EnteFile>>{};+ int distinctFullDescCount = 0;+ final allDistinctFullDescs = <String>[];++ for (EnteFile file in allFiles) {+ if (file.caption != null && file.caption!.isNotEmpty) {+ //This limit doesn't necessarily have to be the limit parameter of the+ //method. Using the same variable to avoid unwanted iterations when+ //iterating over [orderedSubDescriptions] in case there is a limit+ //passed. Using the limit passed here so that there will be almost+ //always be more than 7 descriptionAndMatchingFiles and can shuffle+ //and choose only limited elements from it. Without shuffling,+ //result will be ["hello", "world", "hello world"] for the string+ //"hello world"++ if (limit == null || distinctFullDescCount < limit) {+ final descAlreadyRecorded = allDistinctFullDescs+ .any((element) => element.contains(file.caption!.trim()));++ if (!descAlreadyRecorded) {+ distinctFullDescCount++;+ allDistinctFullDescs.add(file.caption!.trim());+ final words = file.caption!.trim().split(" ");+ orderedSubDescs.add({0: <String>[], 1: <String>[]});++ for (int i = 1; i <= words.length; i++) {+ for (int j = 0; j <= words.length - i; j++) {+ final subList = words.sublist(j, j + i);+ final substring = subList.join(" ").toLowerCase();+ if (i == 1) {+ orderedSubDescs.last[0]!.add(substring);+ } else {+ orderedSubDescs.last[1]!.add(substring);+ }}}}}- }-- for (Map<int, List<String>> orderedSubDescription in orderedSubDescs) {- bool matchesSingleWordSubString = false;- for (String subDescription in orderedSubDescription[0]!) {- if (file.caption!.toLowerCase().contains(subDescription)) {- matchesSingleWordSubString = true;- //continue only after setting [matchesSingleWordSubString] to true- if (subDescription.isAllConnectWords ||- subDescription.isLastWordConnectWord) continue;+ for (Map<int, List<String>> orderedSubDescription+ in orderedSubDescs) {+ bool matchesSingleWordSubString = false;+ for (String subDescription in orderedSubDescription[0]!) {+ if (file.caption!.toLowerCase().contains(subDescription)) {+ matchesSingleWordSubString = true;- if (descAndMatchingFiles.containsKey(subDescription)) {- descAndMatchingFiles[subDescription]!.add(file);- } else {- descAndMatchingFiles[subDescription] = {file};- }- }- }- if (matchesSingleWordSubString) {- for (String subDescription in orderedSubDescription[1]!) {- if (subDescription.isAllConnectWords ||- subDescription.isLastWordConnectWord) continue;+ //continue only after setting [matchesSingleWordSubString] to true+ if (subDescription.isAllConnectWords ||+ subDescription.isLastWordConnectWord) continue;- if (file.caption!.toLowerCase().contains(subDescription)) {if (descAndMatchingFiles.containsKey(subDescription)) {descAndMatchingFiles[subDescription]!.add(file);} else {@@ -423,51 +431,70 @@ class SearchService {}}}+ if (matchesSingleWordSubString) {+ for (String subDescription in orderedSubDescription[1]!) {+ if (subDescription.isAllConnectWords ||+ subDescription.isLastWordConnectWord) continue;++ if (file.caption!.toLowerCase().contains(subDescription)) {+ if (descAndMatchingFiles.containsKey(subDescription)) {+ descAndMatchingFiles[subDescription]!.add(file);+ } else {+ descAndMatchingFiles[subDescription] = {file};+ }+ }+ }+ }}}}- }- ///[relevantDescAndFiles] will be a filterd version of [descriptionAndMatchingFiles]- ///In [descriptionAndMatchingFiles], there will be descriptions with the same- ///set of matching files. These descriptions will be substrings of a full- ///description. [relevantDescAndFiles] will keep only the entry which has the- ///longest description among enties with matching set of files.- final relevantDescAndFiles = <String, Set<EnteFile>>{};- while (descAndMatchingFiles.isNotEmpty) {- final baseEntry = descAndMatchingFiles.entries.first;- final descsWithSameFiles = <String, Set<EnteFile>>{};- final baseUploadedFileIDs =- baseEntry.value.map((e) => e.uploadedFileID).toSet();-- descAndMatchingFiles.forEach((desc, files) {- final uploadedFileIDs = files.map((e) => e.uploadedFileID).toSet();-- final hasSameFiles = uploadedFileIDs.containsAll(baseUploadedFileIDs) &&- baseUploadedFileIDs.containsAll(uploadedFileIDs);- if (hasSameFiles) {- descsWithSameFiles.addAll({desc: files});- }- });- descAndMatchingFiles- .removeWhere((desc, files) => descsWithSameFiles.containsKey(desc));- final longestDescription = descsWithSameFiles.keys.reduce(- (desc1, desc2) => desc1.length > desc2.length ? desc1 : desc2,- );- relevantDescAndFiles.addAll(- {longestDescription: descsWithSameFiles[longestDescription]!},- );- }+ ///[relevantDescAndFiles] will be a filterd version of [descriptionAndMatchingFiles]+ ///In [descriptionAndMatchingFiles], there will be descriptions with the same+ ///set of matching files. These descriptions will be substrings of a full+ ///description. [relevantDescAndFiles] will keep only the entry which has the+ ///longest description among enties with matching set of files.+ final relevantDescAndFiles = <String, Set<EnteFile>>{};+ while (descAndMatchingFiles.isNotEmpty) {+ final baseEntry = descAndMatchingFiles.entries.first;+ final descsWithSameFiles = <String, Set<EnteFile>>{};+ final baseUploadedFileIDs =+ baseEntry.value.map((e) => e.uploadedFileID).toSet();++ descAndMatchingFiles.forEach((desc, files) {+ final uploadedFileIDs = files.map((e) => e.uploadedFileID).toSet();++ final hasSameFiles =+ uploadedFileIDs.containsAll(baseUploadedFileIDs) &&+ baseUploadedFileIDs.containsAll(uploadedFileIDs);+ if (hasSameFiles) {+ descsWithSameFiles.addAll({desc: files});+ }+ });+ descAndMatchingFiles+ .removeWhere((desc, files) => descsWithSameFiles.containsKey(desc));+ final longestDescription = descsWithSameFiles.keys.reduce(+ (desc1, desc2) => desc1.length > desc2.length ? desc1 : desc2,+ );+ relevantDescAndFiles.addAll(+ {longestDescription: descsWithSameFiles[longestDescription]!},+ );+ }- relevantDescAndFiles.forEach((key, value) {- searchResults.add(- GenericSearchResult(ResultType.fileCaption, key, value.toList()),- );- });- if (limit != null && distinctFullDescCount >= limit) {- return (searchResults..shuffle()).sublist(0, limit);- } else {- return searchResults;+ relevantDescAndFiles.forEach((key, value) {+ searchResults.add(+ GenericSearchResult(ResultType.fileCaption, key, value.toList()),+ );+ });+ if (limit != null) {+ return (searchResults..shuffle())+ .sublist(0, min(limit, searchResults.length));+ } else {+ return searchResults;+ }+ } catch (e) {+ _logger.severe("Error in getAllDescriptionSearchResults", e);+ return Future.value([]);}}@@ -631,53 +658,58 @@ class SearchService {}Future<List<GenericSearchResult>> getAllLocationTags(int? limit) async {- final Map<LocalEntity<LocationTag>, List<EnteFile>> tagToItemsMap = {};- final List<GenericSearchResult> tagSearchResults = [];- final locationTagEntities =- (await LocationService.instance.getLocationTags());- final allFiles = await getAllFiles();-- for (int i = 0; i < locationTagEntities.length; i++) {- if (limit != null && i >= limit) break;- tagToItemsMap[locationTagEntities.elementAt(i)] = [];- }+ try {+ final Map<LocalEntity<LocationTag>, List<EnteFile>> tagToItemsMap = {};+ final List<GenericSearchResult> tagSearchResults = [];+ final locationTagEntities =+ (await LocationService.instance.getLocationTags());+ final allFiles = await getAllFiles();++ for (int i = 0; i < locationTagEntities.length; i++) {+ if (limit != null && i >= limit) break;+ tagToItemsMap[locationTagEntities.elementAt(i)] = [];+ }- for (EnteFile file in allFiles) {- if (file.hasLocation) {- for (LocalEntity<LocationTag> tag in tagToItemsMap.keys) {- if (LocationService.instance.isFileInsideLocationTag(- tag.item.centerPoint,- file.location!,- tag.item.radius,- )) {- tagToItemsMap[tag]!.add(file);+ for (EnteFile file in allFiles) {+ if (file.hasLocation) {+ for (LocalEntity<LocationTag> tag in tagToItemsMap.keys) {+ if (LocationService.instance.isFileInsideLocationTag(+ tag.item.centerPoint,+ file.location!,+ tag.item.radius,+ )) {+ tagToItemsMap[tag]!.add(file);+ }}}}- }- for (MapEntry<LocalEntity<LocationTag>, List<EnteFile>> entry- in tagToItemsMap.entries) {- if (entry.value.isNotEmpty) {- tagSearchResults.add(- GenericSearchResult(- ResultType.location,- entry.key.item.name,- entry.value,- onResultTap: (ctx) {- routeToPage(- ctx,- LocationScreenStateProvider(- entry.key,- const LocationScreen(),- ),- );- },- ),- );+ for (MapEntry<LocalEntity<LocationTag>, List<EnteFile>> entry+ in tagToItemsMap.entries) {+ if (entry.value.isNotEmpty) {+ tagSearchResults.add(+ GenericSearchResult(+ ResultType.location,+ entry.key.item.name,+ entry.value,+ onResultTap: (ctx) {+ routeToPage(+ ctx,+ LocationScreenStateProvider(+ entry.key,+ const LocationScreen(),+ ),+ );+ },+ ),+ );+ }}+ return tagSearchResults;+ } catch (e) {+ _logger.severe("Error in getAllLocationTags", e);+ return Future.value([]);}- return tagSearchResults;}Future<List<GenericSearchResult>> getDateResults(@@ -711,35 +743,40 @@ class SearchService {}Future<List<GenericSearchResult>> getPeopleSearchResults(int? limit) async {- final searchResults = <GenericSearchResult>[];- final allFiles = await getAllFiles();- final peopleToSharedFiles = <User, List<EnteFile>>{};- int peopleCount = 0;- for (EnteFile file in allFiles) {- if (file.isOwner) continue;-- final fileOwner = CollectionsService.instance- .getFileOwner(file.ownerID!, file.collectionID);- if (peopleToSharedFiles.containsKey(fileOwner)) {- peopleToSharedFiles[fileOwner]!.add(file);- } else {- if (limit != null && limit <= peopleCount) continue;- peopleToSharedFiles[fileOwner] = [file];- peopleCount++;+ try {+ final searchResults = <GenericSearchResult>[];+ final allFiles = await getAllFiles();+ final peopleToSharedFiles = <User, List<EnteFile>>{};+ int peopleCount = 0;+ for (EnteFile file in allFiles) {+ if (file.isOwner) continue;++ final fileOwner = CollectionsService.instance+ .getFileOwner(file.ownerID!, file.collectionID);+ if (peopleToSharedFiles.containsKey(fileOwner)) {+ peopleToSharedFiles[fileOwner]!.add(file);+ } else {+ if (limit != null && limit <= peopleCount) continue;+ peopleToSharedFiles[fileOwner] = [file];+ peopleCount++;+ }}- }- peopleToSharedFiles.forEach((key, value) {- searchResults.add(- GenericSearchResult(- ResultType.shared,- key.name != null && key.name!.isNotEmpty ? key.name! : key.email,- value,- ),- );- });+ peopleToSharedFiles.forEach((key, value) {+ searchResults.add(+ GenericSearchResult(+ ResultType.shared,+ key.name != null && key.name!.isNotEmpty ? key.name! : key.email,+ value,+ ),+ );+ });- return searchResults;+ return searchResults;+ } catch (e) {+ _logger.severe("Error in getAllLocationTags", e);+ return Future.value([]);+ }}List<MonthData> _getMatchingMonths(BuildContext context, String query) {diff --git a/lib/ui/search_tab.dart b/lib/ui/search_tab.dartindex 4a575df8d5..a22b4fa9e3 100644--- a/lib/ui/search_tab.dart+++ b/lib/ui/search_tab.dart@@ -105,6 +105,8 @@ class _AllSearchSectionsState extends State<AllSearchSections> {);} else if (snapshot.hasError) {//todo: Show something went wrong here+ //Errors are handled and this else if condition will be false always+ //is the understanding.return const Padding(padding: EdgeInsets.only(bottom: 72),child: EnteLoadingWidget(),