From b8ceac59f9c28a7c17db7987aa35fdedbf509005 Mon Sep 17 00:00:00 2001 From: Dion Date: Mon, 24 Jul 2023 15:12:22 +0200 Subject: [PATCH 01/10] add paste async --- .../detail-view-sidebar.tsx | 2 +- .../src/shared/clipboard-helper.spec.ts | 50 +++++++++++++++++++ .../clientapp/src/shared/clipboard-helper.ts | 25 ++++++++++ 3 files changed, 76 insertions(+), 1 deletion(-) diff --git a/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/detail-view-sidebar.tsx b/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/detail-view-sidebar.tsx index 87d8f6380c..650e2d0109 100644 --- a/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/detail-view-sidebar.tsx +++ b/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/detail-view-sidebar.tsx @@ -197,7 +197,7 @@ const DetailViewSidebar: React.FunctionComponent = state ); - const paste = new ClipboardHelper().Paste(updateChange.Update); + const paste = new ClipboardHelper().PasteAsync(updateChange.Update); if (!paste) return; setCopyPasteAction(MessagePasteLabels); diff --git a/starsky/starsky/clientapp/src/shared/clipboard-helper.spec.ts b/starsky/starsky/clientapp/src/shared/clipboard-helper.spec.ts index 895680db9a..37468888cb 100644 --- a/starsky/starsky/clientapp/src/shared/clipboard-helper.spec.ts +++ b/starsky/starsky/clientapp/src/shared/clipboard-helper.spec.ts @@ -79,4 +79,54 @@ describe("ClipboardHelper", () => { ]); }); }); + + describe("PasteAsync", () => { + it("non valid ref", async () => { + expect(await clipboardHelper.PasteAsync(null as any)).toBeFalsy(); + }); + + it("should return false if updateChange returns false", async () => { + const clipboardHelper = new ClipboardHelper(); + const mockUpdateChange = jest.fn().mockResolvedValue(false); + const mockRead = jest.spyOn(clipboardHelper, "Read").mockReturnValue({ + tags: "test tags", + description: "test description", + title: "test title" + }); + + await clipboardHelper.PasteAsync(mockUpdateChange); + + expect(mockRead).toHaveBeenCalledTimes(1); + expect(mockUpdateChange).toHaveBeenCalledTimes(1); + expect(mockUpdateChange).toHaveBeenCalledWith([ + ["tags", "test tags"], + ["description", "test description"], + ["title", "test title"] + ]); + + mockRead.mockRestore(); + }); + + it("Copy and Paste", () => { + const callback = jest.fn(); + + clipboardHelper.Copy( + refGenerator("A"), + refGenerator("B"), + refGenerator("C") + ); + + const result = clipboardHelper.PasteAsync(callback); + + expect(result).toBeTruthy(); + + expect(callback).toBeCalled(); + + expect(callback).toHaveBeenNthCalledWith(1, [ + ["tags", "A"], + ["description", "B"], + ["title", "C"] + ]); + }); + }); }); diff --git a/starsky/starsky/clientapp/src/shared/clipboard-helper.ts b/starsky/starsky/clientapp/src/shared/clipboard-helper.ts index 2d67eacf9f..1e5036ef09 100644 --- a/starsky/starsky/clientapp/src/shared/clipboard-helper.ts +++ b/starsky/starsky/clientapp/src/shared/clipboard-helper.ts @@ -71,4 +71,29 @@ export class ClipboardHelper { return true; } + + /** + * Paste values in callback + * @param updateChange callback function + */ + public async PasteAsync( + updateChange: (items: [string, string][]) => Promise + ): Promise { + if (!updateChange) { + return false; + } + const readData = this.Read(); + + if (!readData) { + return false; + } + + await updateChange([ + ["tags", readData.tags], + ["description", readData.description], + ["title", readData.title] + ]); + + return true; + } } From 33d6fdcc5a134dacc6b1942b6965a45cbd501ab5 Mon Sep 17 00:00:00 2001 From: Dion Date: Mon, 24 Jul 2023 15:21:59 +0200 Subject: [PATCH 02/10] small fixes --- .../detail-view-sidebar/update-change.ts | 5 ++++- .../menu-detail-view/menu-detail-view.tsx | 20 ++++++++++--------- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/update-change.ts b/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/update-change.ts index 595ee9001e..7d04293896 100644 --- a/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/update-change.ts +++ b/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/update-change.ts @@ -52,7 +52,10 @@ export class UpdateChange { // compare const fileIndexObject: any = this.fileIndexItem; - if (!fileIndexObject[name] === undefined) continue; //to update empty start to first fill + if (fileIndexObject[name] === undefined) { + console.log("missing name", name); + continue; //to update empty start to first fill + } const currentString: string = fileIndexObject[name]; if (replacedValue === currentString) continue; diff --git a/starsky/starsky/clientapp/src/components/organisms/menu-detail-view/menu-detail-view.tsx b/starsky/starsky/clientapp/src/components/organisms/menu-detail-view/menu-detail-view.tsx index 597df01c96..b45466255a 100644 --- a/starsky/starsky/clientapp/src/components/organisms/menu-detail-view/menu-detail-view.tsx +++ b/starsky/starsky/clientapp/src/components/organisms/menu-detail-view/menu-detail-view.tsx @@ -282,15 +282,17 @@ const MenuDetailView: React.FunctionComponent = ({ } // there is an async backend event triggered, sometimes there is an que - setTimeout(async () => { - const result = await requestNewFileHash(); - if (result === false) { - setTimeout(async () => { - await requestNewFileHash(); - // when it didn't change after two tries - setIsLoading(false); - }, 7000); - } + setTimeout(() => { + requestNewFileHash().then((result) => { + if (result === false) { + setTimeout(() => { + requestNewFileHash().then(() => { + // when it didn't change after two tries + setIsLoading(false); + }); + }, 7000); + } + }); }, 3000); } From 2c8f3ccf46480a5619203503037e9dd0c7dfa2f1 Mon Sep 17 00:00:00 2001 From: Dion Date: Mon, 24 Jul 2023 15:23:47 +0200 Subject: [PATCH 03/10] change test --- .../detail-view-sidebar/update-change.spec.ts | 11 +++-------- .../organisms/detail-view-sidebar/update-change.ts | 2 +- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/update-change.spec.ts b/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/update-change.spec.ts index c09677532a..c34839beac 100644 --- a/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/update-change.spec.ts +++ b/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/update-change.spec.ts @@ -2,7 +2,6 @@ import { IConnectionDefault } from "../../../interfaces/IConnectionDefault"; import { IFileIndexItem } from "../../../interfaces/IFileIndexItem"; import * as FetchPost from "../../../shared/fetch-post"; import { FileListCache } from "../../../shared/filelist-cache"; -import { UrlQuery } from "../../../shared/url-query"; import { UpdateChange } from "./update-change"; describe("Update Change", () => { @@ -165,14 +164,14 @@ describe("Update Change", () => { expect(fetchPostSpy).toBeCalledTimes(1); }); - it("no content 2", () => { + it("no content 2", async () => { const fetchPostSpy = jest .spyOn(FetchPost, "default") .mockImplementationOnce(() => { return Promise.resolve({} as IConnectionDefault); }); - new UpdateChange( + await new UpdateChange( {} as any, jest.fn(), jest.fn(), @@ -180,11 +179,7 @@ describe("Update Change", () => { {} as any ).Update([["tags", "test"]]); - expect(fetchPostSpy).toBeCalledTimes(1); - expect(fetchPostSpy).toBeCalledWith( - new UrlQuery().UrlUpdateApi(), - "tags=test" - ); + expect(fetchPostSpy).toBeCalledTimes(0); }); }); }); diff --git a/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/update-change.ts b/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/update-change.ts index 7d04293896..4e923993b1 100644 --- a/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/update-change.ts +++ b/starsky/starsky/clientapp/src/components/organisms/detail-view-sidebar/update-change.ts @@ -53,7 +53,7 @@ export class UpdateChange { const fileIndexObject: any = this.fileIndexItem; if (fileIndexObject[name] === undefined) { - console.log("missing name", name); + console.error("missing name", name); continue; //to update empty start to first fill } From 42cb54c836caab45eafa5af7b4e2d85f8c9d5cf8 Mon Sep 17 00:00:00 2001 From: Dion Date: Tue, 25 Jul 2023 11:09:14 +0200 Subject: [PATCH 04/10] small changes --- starsky/starsky.foundation.database/Query/Query.cs | 1 - .../starsky/clientapp/src/hooks/realtime/websocket-service.ts | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/starsky/starsky.foundation.database/Query/Query.cs b/starsky/starsky.foundation.database/Query/Query.cs index 7e98e87325..f21cfab9f1 100644 --- a/starsky/starsky.foundation.database/Query/Query.cs +++ b/starsky/starsky.foundation.database/Query/Query.cs @@ -93,7 +93,6 @@ internal static string GetObjectByFilePathAsyncCacheName(string subPath) _cache.TryGetValue( GetObjectByFilePathAsyncCacheName(filePath), out var data) ) { - _logger.LogInformation("Get from cache " + GetObjectByFilePathAsyncCacheName(filePath)); if ( !(data is FileIndexItem fileIndexItem) ) return null; fileIndexItem.Status = FileIndexItem.ExifStatus.OkAndSame; return fileIndexItem; diff --git a/starsky/starsky/clientapp/src/hooks/realtime/websocket-service.ts b/starsky/starsky/clientapp/src/hooks/realtime/websocket-service.ts index 9046496303..800e2e061a 100644 --- a/starsky/starsky/clientapp/src/hooks/realtime/websocket-service.ts +++ b/starsky/starsky/clientapp/src/hooks/realtime/websocket-service.ts @@ -6,7 +6,7 @@ export default class WebSocketService { } catch (error) {} } - public onOpen(callback: (ev: Event) => void): void { + public onOpen(callback: (ev: Event) => Promise): void { if (!this.websocket) return; this.websocket.onopen = callback; } From 2b20108e8253d63b442634e8c91ab8924654caf2 Mon Sep 17 00:00:00 2001 From: Dion Date: Tue, 25 Jul 2023 11:17:58 +0200 Subject: [PATCH 05/10] code smells --- .../HealthCheck/DiskStorageHealthCheck.cs | 5 +++-- .../HealthCheck/PathExistHealthCheck.cs | 2 +- .../UpdateCheck/Models/ReleaseModel.cs | 2 +- .../UpdateCheck/Services/CheckForUpdates.cs | 5 ++++- starsky/starsky.feature.import/Services/Import.cs | 2 +- 5 files changed, 10 insertions(+), 6 deletions(-) diff --git a/starsky/starsky.feature.health/HealthCheck/DiskStorageHealthCheck.cs b/starsky/starsky.feature.health/HealthCheck/DiskStorageHealthCheck.cs index 7826d8bb8d..bb2dba5e4b 100644 --- a/starsky/starsky.feature.health/HealthCheck/DiskStorageHealthCheck.cs +++ b/starsky/starsky.feature.health/HealthCheck/DiskStorageHealthCheck.cs @@ -59,8 +59,9 @@ private static (bool Exists, long ActualFreeMegabytes) GetSystemDriveInfo(string return ( false, 0L ); } - var driveInfo = drivesList.FirstOrDefault( - drive => string.Equals(drive.Name, driveName, StringComparison.InvariantCultureIgnoreCase)); + var driveInfo = Array.Find(drivesList, + drive => string.Equals(drive.Name, driveName, + StringComparison.InvariantCultureIgnoreCase)); return driveInfo?.AvailableFreeSpace != null ? (true, driveInfo.AvailableFreeSpace / 1024L / 1024L) : (false, 0L); } } diff --git a/starsky/starsky.feature.health/HealthCheck/PathExistHealthCheck.cs b/starsky/starsky.feature.health/HealthCheck/PathExistHealthCheck.cs index 704ef39231..7ee4d4d437 100644 --- a/starsky/starsky.feature.health/HealthCheck/PathExistHealthCheck.cs +++ b/starsky/starsky.feature.health/HealthCheck/PathExistHealthCheck.cs @@ -33,7 +33,7 @@ public Task CheckHealthAsync( $"Not configured")); return Task.FromResult( - resultsList.Any(p => p == FolderOrFileModel.FolderOrFileTypeList.Deleted) ? + resultsList.Exists(p => p == FolderOrFileModel.FolderOrFileTypeList.Deleted) ? new HealthCheckResult(context.Registration.FailureStatus, $"Configured path is not present on system") : HealthCheckResult.Healthy("Configured path is present")); } diff --git a/starsky/starsky.feature.health/UpdateCheck/Models/ReleaseModel.cs b/starsky/starsky.feature.health/UpdateCheck/Models/ReleaseModel.cs index f98d219707..2f3655cd86 100644 --- a/starsky/starsky.feature.health/UpdateCheck/Models/ReleaseModel.cs +++ b/starsky/starsky.feature.health/UpdateCheck/Models/ReleaseModel.cs @@ -29,7 +29,7 @@ public string TagName { set { if ( string.IsNullOrWhiteSpace(value)) return; - if ( !value.StartsWith("v") ) Console.WriteLine($"{_tagName} Should start with v"); + if ( !value.StartsWith('v') ) Console.WriteLine($"{_tagName} Should start with v"); _tagName = value; } } diff --git a/starsky/starsky.feature.health/UpdateCheck/Services/CheckForUpdates.cs b/starsky/starsky.feature.health/UpdateCheck/Services/CheckForUpdates.cs index cfc7ef561e..7b0e6d06b8 100644 --- a/starsky/starsky.feature.health/UpdateCheck/Services/CheckForUpdates.cs +++ b/starsky/starsky.feature.health/UpdateCheck/Services/CheckForUpdates.cs @@ -72,8 +72,11 @@ internal static KeyValuePair Parse(IEnumerable p.TagName); var tagName = orderedReleaseModelList.FirstOrDefault(p => !p.Draft && !p.PreRelease)?.TagName; - if ( string.IsNullOrWhiteSpace(tagName) || !tagName.StartsWith("v") ) + if ( string.IsNullOrWhiteSpace(tagName) || + !tagName.StartsWith('v') ) + { return new KeyValuePair(UpdateStatus.NoReleasesFound,string.Empty); + } try { diff --git a/starsky/starsky.feature.import/Services/Import.cs b/starsky/starsky.feature.import/Services/Import.cs index 0c0c68bce9..23a8c28d83 100644 --- a/starsky/starsky.feature.import/Services/Import.cs +++ b/starsky/starsky.feature.import/Services/Import.cs @@ -142,7 +142,7 @@ public async Task> Preflight(List fullFilePathsLis var parentFolder = Directory.GetParent(itemSourceFullFilePath) ?.FullName; - if ( parentFolders.All(p => p.Item1 != parentFolder) ) + if ( parentFolders.TrueForAll(p => p.Item1 != parentFolder) ) { parentFolders.Add(new Tuple>(parentFolder, new List{itemSourceFullFilePath})); continue; From e91efd7521b3f5315516f0ad57b9d7c1b1047d6e Mon Sep 17 00:00:00 2001 From: Dion Date: Tue, 25 Jul 2023 11:45:24 +0200 Subject: [PATCH 06/10] code smells --- .../starsky.feature.import/Services/Import.cs | 16 +++++++++++----- .../Helpers/AddNotFoundInIndexStatus.cs | 2 +- .../Services/MetaReplaceService.cs | 6 ++++-- .../Services/PackageTelemetry.cs | 2 +- .../ViewModels/SearchViewModel.cs | 13 +++++++++---- .../DatabaseThumbnailGenerationService.cs | 2 +- .../Services/WebHtmlPublishService.cs | 7 ++++--- .../Services/UserManager.cs | 2 +- 8 files changed, 32 insertions(+), 18 deletions(-) diff --git a/starsky/starsky.feature.import/Services/Import.cs b/starsky/starsky.feature.import/Services/Import.cs index 23a8c28d83..8404fc1282 100644 --- a/starsky/starsky.feature.import/Services/Import.cs +++ b/starsky/starsky.feature.import/Services/Import.cs @@ -157,10 +157,16 @@ public async Task> Preflight(List fullFilePathsLis var fileStorageInfo = _filesystemStorage.Info(parentFolder.Item1!); if ( fileStorageInfo.IsFolderOrFile != FolderOrFileModel.FolderOrFileTypeList.Folder || - fileStorageInfo.IsFileSystemReadOnly != true ) continue; + fileStorageInfo.IsFileSystemReadOnly != true ) + { + continue; + } + + var items = parentFolder.Item2.Select(parentItem => + Array.Find(importIndexItemsList.ToArray(), + p => p.SourceFullFilePath == parentItem)).Cast(); - foreach ( var item in parentFolder.Item2.Select(parentItem => importIndexItemsList.FirstOrDefault(p => - p.SourceFullFilePath == parentItem)).Where(item => item != null).Cast() ) + foreach ( var item in items ) { importIndexItemsList[importIndexItemsList.IndexOf(item)] .Status = ImportStatus.ReadOnlyFileSystem; @@ -229,7 +235,7 @@ internal List CheckForDuplicateNaming(List imp var currentDirectoryContent = directoriesContent[importIndexItem.FileIndexItem.ParentDirectory!]; - if ( currentDirectoryContent.Any(p => p == updatedFilePath) ) + if ( currentDirectoryContent.Contains(updatedFilePath) ) { indexer++; continue; @@ -291,7 +297,7 @@ private List> AppendDirectoryFilePaths(List fu internal async Task PreflightPerFile(KeyValuePair inputFileFullPath, ImportSettingsModel importSettings) { - if ( _appSettings.ImportIgnore.Any(p => inputFileFullPath.Key.Contains(p)) ) + if ( _appSettings.ImportIgnore.Exists(p => inputFileFullPath.Key.Contains(p)) ) { ConsoleIfVerbose($"❌ skip due rules: {inputFileFullPath.Key} "); return new ImportIndexItem{ diff --git a/starsky/starsky.feature.metaupdate/Helpers/AddNotFoundInIndexStatus.cs b/starsky/starsky.feature.metaupdate/Helpers/AddNotFoundInIndexStatus.cs index b65dba2c28..65124442d0 100644 --- a/starsky/starsky.feature.metaupdate/Helpers/AddNotFoundInIndexStatus.cs +++ b/starsky/starsky.feature.metaupdate/Helpers/AddNotFoundInIndexStatus.cs @@ -13,7 +13,7 @@ internal static void Update(IEnumerable inputFilePaths, List p.FilePath == subPath) ) + if ( fileIndexResultsList.Exists(p => p.FilePath == subPath) ) { continue; } diff --git a/starsky/starsky.feature.metaupdate/Services/MetaReplaceService.cs b/starsky/starsky.feature.metaupdate/Services/MetaReplaceService.cs index 89575d65a9..2fd6041d57 100644 --- a/starsky/starsky.feature.metaupdate/Services/MetaReplaceService.cs +++ b/starsky/starsky.feature.metaupdate/Services/MetaReplaceService.cs @@ -135,8 +135,10 @@ public static List SearchAndReplace(List fileIndex var propertiesA = new FileIndexItem().GetType().GetProperties( BindingFlags.Public | BindingFlags.Instance); - var property = propertiesA.FirstOrDefault(p => string.Equals( - p.Name, fieldName, StringComparison.InvariantCultureIgnoreCase)); + + var property = Array.Find(propertiesA, p => string.Equals( + p.Name, fieldName, + StringComparison.InvariantCultureIgnoreCase)); if ( property?.PropertyType == typeof(string)) { diff --git a/starsky/starsky.feature.packagetelemetry/Services/PackageTelemetry.cs b/starsky/starsky.feature.packagetelemetry/Services/PackageTelemetry.cs index 113a7b7179..e4675c7a0a 100644 --- a/starsky/starsky.feature.packagetelemetry/Services/PackageTelemetry.cs +++ b/starsky/starsky.feature.packagetelemetry/Services/PackageTelemetry.cs @@ -127,7 +127,7 @@ internal List> AddAppSettingsData( List x is PackageTelemetryAttribute); + var someAttribute = Array.Find(Attribute.GetCustomAttributes(property), x => x is PackageTelemetryAttribute); if ( someAttribute == null ) { continue; diff --git a/starsky/starsky.feature.search/ViewModels/SearchViewModel.cs b/starsky/starsky.feature.search/ViewModels/SearchViewModel.cs index c339b38871..1cda83a4dd 100644 --- a/starsky/starsky.feature.search/ViewModels/SearchViewModel.cs +++ b/starsky/starsky.feature.search/ViewModels/SearchViewModel.cs @@ -503,9 +503,14 @@ public static SearchViewModel NarrowSearch(SearchViewModel model) for ( var i = 0; i < model.SearchIn.Count; i++ ) { - var propertyStringName = FileIndexItem.FileIndexPropList().FirstOrDefault(p => - string.Equals(p, model.SearchIn[i], StringComparison.InvariantCultureIgnoreCase)); - if ( string.IsNullOrEmpty(propertyStringName) ) continue; + var propertyStringName = FileIndexItem.FileIndexPropList().Find( p => + string.Equals(p, model.SearchIn[i], + StringComparison.InvariantCultureIgnoreCase)); + + if ( string.IsNullOrEmpty(propertyStringName) ) + { + continue; + } var property = new FileIndexItem().GetType().GetProperty(propertyStringName)!; @@ -518,7 +523,7 @@ public static SearchViewModel NarrowSearch(SearchViewModel model) } // hide xmp files in default view - if ( model.SearchIn.All(p => !string.Equals(p, nameof(SearchInTypes.imageformat), + if ( model.SearchIn.TrueForAll(p => !string.Equals(p, nameof(SearchInTypes.imageformat), StringComparison.InvariantCultureIgnoreCase))) { model.FileIndexItems = model.FileIndexItems! diff --git a/starsky/starsky.feature.thumbnail/Services/DatabaseThumbnailGenerationService.cs b/starsky/starsky.feature.thumbnail/Services/DatabaseThumbnailGenerationService.cs index 4855fcffb5..32a52bd3ed 100644 --- a/starsky/starsky.feature.thumbnail/Services/DatabaseThumbnailGenerationService.cs +++ b/starsky/starsky.feature.thumbnail/Services/DatabaseThumbnailGenerationService.cs @@ -81,7 +81,7 @@ internal async Task> WorkThumbnailGeneration( foreach ( var item in chuckedItems ) { - var fileIndexItem = fileIndexItems.FirstOrDefault(p => p.FileHash == item.FileHash); + var fileIndexItem = fileIndexItems.Find(p => p.FileHash == item.FileHash); if ( fileIndexItem?.FilePath == null || fileIndexItem.Status != FileIndexItem.ExifStatus.Ok ) { diff --git a/starsky/starsky.feature.webhtmlpublish/Services/WebHtmlPublishService.cs b/starsky/starsky.feature.webhtmlpublish/Services/WebHtmlPublishService.cs index ecb486b9be..a6c431c36a 100644 --- a/starsky/starsky.feature.webhtmlpublish/Services/WebHtmlPublishService.cs +++ b/starsky/starsky.feature.webhtmlpublish/Services/WebHtmlPublishService.cs @@ -97,7 +97,7 @@ internal List AddFileHashIfNotExist(List fileIndex internal bool ShouldSkipExtraLarge(string publishProfileName) { var skipExtraLarge = _publishPreflight?.GetPublishProfileName(publishProfileName)? - .All(p => p.SourceMaxWidth <= 1999); + .TrueForAll(p => p.SourceMaxWidth <= 1999); return skipExtraLarge == true; } @@ -156,9 +156,10 @@ private async Task> Render(List fileIndex // Order alphabetically // Ignore Items with Errors - fileIndexItemsList = fileIndexItemsList.OrderBy(p => p.FileName) + fileIndexItemsList = fileIndexItemsList .Where(p=> p.Status == FileIndexItem.ExifStatus.Ok || - p.Status == FileIndexItem.ExifStatus.ReadOnly).ToList(); + p.Status == FileIndexItem.ExifStatus.ReadOnly) + .OrderBy(p => p.FileName).ToList(); var copyResult = new Dictionary(); diff --git a/starsky/starsky.foundation.accountmanagement/Services/UserManager.cs b/starsky/starsky.foundation.accountmanagement/Services/UserManager.cs index 70be87ba48..96d0318a85 100644 --- a/starsky/starsky.foundation.accountmanagement/Services/UserManager.cs +++ b/starsky/starsky.foundation.accountmanagement/Services/UserManager.cs @@ -164,7 +164,7 @@ internal async Task AddUserToCache(User user) if ( !IsCacheEnabled() ) return; var allUsers = (await AllUsersAsync()).Users; var index = allUsers.Find(p => p.Id == user.Id); - if ( allUsers.Any(p => p.Id == user.Id) && index != null ) + if ( allUsers.Exists(p => p.Id == user.Id) && index != null ) { var indexOf = allUsers.IndexOf(index); allUsers[indexOf] = user; From 60f7bc1db7266fed632af9f8a66a4f97225d1313 Mon Sep 17 00:00:00 2001 From: Dion Date: Tue, 25 Jul 2023 14:51:21 +0200 Subject: [PATCH 07/10] code smells --- .../Services/UserManager.cs | 6 +++--- .../Helpers/FileIndexCompareHelper.cs | 8 ++++---- .../Models/ImportIndexItem.cs | 5 ++++- starsky/starsky.foundation.database/Query/Query.cs | 2 +- .../Query/QueryGetObjectsByFileHashAsync.cs | 2 +- .../Query/QuerySingleItem.cs | 2 +- .../Thumbnails/ThumbnailQuery.cs | 6 +++--- .../ServiceCollectionExtensions.cs | 4 ++-- .../Helpers/AppSettingsCompareHelper.cs | 6 +++--- .../Helpers/DateAssembly.cs | 11 +++++++++-- .../starsky.foundation.platform/Models/AppSettings.cs | 6 +++--- .../starsky.foundation.readmeta/Helpers/GeoParser.cs | 2 +- starsky/starskytest/FakeMocks/FakeIQuery.cs | 2 +- .../Models/AppSettingsTest.cs | 8 ++++---- 14 files changed, 40 insertions(+), 30 deletions(-) diff --git a/starsky/starsky.foundation.accountmanagement/Services/UserManager.cs b/starsky/starsky.foundation.accountmanagement/Services/UserManager.cs index 96d0318a85..24d2bc746d 100644 --- a/starsky/starsky.foundation.accountmanagement/Services/UserManager.cs +++ b/starsky/starsky.foundation.accountmanagement/Services/UserManager.cs @@ -211,7 +211,7 @@ private async Task RemoveUserFromCacheAsync(User user) } var users = (await AllUsersAsync()).Users; - return users.FirstOrDefault(p => p.Id == userTableId); + return users.Find(p => p.Id == userTableId); } /// @@ -284,7 +284,7 @@ public async Task SignUpAsync(string name, } // Add a user role based on a user id - var roleToAdd = roles.FirstOrDefault(p => p.Code == GetRoleAddToUser(identifier,user)); + var roleToAdd = roles.Find(p => p.Code == GetRoleAddToUser(identifier,user)); AddToRole(user, roleToAdd); if (credentialType == null) @@ -555,7 +555,7 @@ public async Task ValidateAsync(string credentialTypeCode, return new ValidateResult(success: false, error: ValidateResultError.SecretNotValid); } - var userData = (await AllUsersAsync()).Users.FirstOrDefault(p => p.Id == credential.UserId); + var userData = (await AllUsersAsync()).Users.Find(p => p.Id == credential.UserId); if ( userData == null ) { return new ValidateResult(success: false, error: ValidateResultError.UserNotFound); diff --git a/starsky/starsky.foundation.database/Helpers/FileIndexCompareHelper.cs b/starsky/starsky.foundation.database/Helpers/FileIndexCompareHelper.cs index dc66dac5ca..c5e53f5554 100644 --- a/starsky/starsky.foundation.database/Helpers/FileIndexCompareHelper.cs +++ b/starsky/starsky.foundation.database/Helpers/FileIndexCompareHelper.cs @@ -102,13 +102,13 @@ public static List Compare(FileIndexItem sourceIndexItem, FileIndexItem? } // Last Edited is not needed - if ( differenceList.Any(p => p == nameof(FileIndexItem.LastEdited).ToLowerInvariant()) ) + if ( differenceList.Exists(p => p == nameof(FileIndexItem.LastEdited).ToLowerInvariant()) ) { differenceList.Remove(nameof(FileIndexItem.LastEdited).ToLowerInvariant()); } // Last Changed is a generated list - if ( differenceList.Any(p => p == nameof(FileIndexItem.LastChanged).ToLowerInvariant()) ) + if ( differenceList.Exists(p => p == nameof(FileIndexItem.LastChanged).ToLowerInvariant()) ) { differenceList.Remove(nameof(FileIndexItem.LastChanged).ToLowerInvariant()); } @@ -134,7 +134,7 @@ public static FileIndexItem Set(FileIndexItem? sourceIndexItem, string fieldName PropertyInfo[] propertiesA = new FileIndexItem().GetType().GetProperties( BindingFlags.Public | BindingFlags.Instance); - var property = propertiesA.FirstOrDefault(p => + var property = Array.Find(propertiesA,p => string.Equals(p.Name, fieldName, StringComparison.InvariantCultureIgnoreCase)); var fieldType = fieldContent.GetType(); @@ -158,7 +158,7 @@ public static FileIndexItem Set(FileIndexItem? sourceIndexItem, string fieldName { PropertyInfo[] propertiesA = new FileIndexItem().GetType() .GetProperties(BindingFlags.Public | BindingFlags.Instance); - return propertiesA.FirstOrDefault(p => + return Array.Find(propertiesA,p => string.Equals(p.Name, fieldName, StringComparison.InvariantCultureIgnoreCase))? .GetValue(sourceIndexItem, null); } diff --git a/starsky/starsky.foundation.database/Models/ImportIndexItem.cs b/starsky/starsky.foundation.database/Models/ImportIndexItem.cs index 9a35249d5c..3fc95dd6ae 100644 --- a/starsky/starsky.foundation.database/Models/ImportIndexItem.cs +++ b/starsky/starsky.foundation.database/Models/ImportIndexItem.cs @@ -118,7 +118,10 @@ public DateTime ParseDateTimeFromFileName() { // Depends on 'AppSettingsProvider.Structure' // depends on SourceFullFilePath - if(string.IsNullOrEmpty(SourceFullFilePath)) {return new DateTime();} + if ( string.IsNullOrEmpty(SourceFullFilePath) ) + { + return new DateTime(0, DateTimeKind.Utc); + } var fileName = Path.GetFileNameWithoutExtension(SourceFullFilePath); diff --git a/starsky/starsky.foundation.database/Query/Query.cs b/starsky/starsky.foundation.database/Query/Query.cs index f21cfab9f1..4da9419b78 100644 --- a/starsky/starsky.foundation.database/Query/Query.cs +++ b/starsky/starsky.foundation.database/Query/Query.cs @@ -477,7 +477,7 @@ public void CacheUpdateItem(List updateStatusContent) // make it a list to avoid enum errors displayFileFolders = displayFileFolders.ToList(); - var obj = displayFileFolders.FirstOrDefault(p => p.FilePath == item.FilePath); + var obj = displayFileFolders.Find(p => p.FilePath == item.FilePath); if ( obj != null ) { // remove add again diff --git a/starsky/starsky.foundation.database/Query/QueryGetObjectsByFileHashAsync.cs b/starsky/starsky.foundation.database/Query/QueryGetObjectsByFileHashAsync.cs index 1c5ced78f6..de086a0fea 100644 --- a/starsky/starsky.foundation.database/Query/QueryGetObjectsByFileHashAsync.cs +++ b/starsky/starsky.foundation.database/Query/QueryGetObjectsByFileHashAsync.cs @@ -27,7 +27,7 @@ async Task> LocalQuery(ApplicationDbContext context) fileHashesList.Contains(p.FileHash!)).ToListAsync(); foreach ( var fileHash in fileHashesList ) { - if ( result.FirstOrDefault(p => p.FileHash == fileHash) == null ) + if ( result.Find(p => p.FileHash == fileHash) == null ) { result.Add(new FileIndexItem(){FileHash = fileHash, Status = FileIndexItem.ExifStatus.NotFoundNotInIndex}); diff --git a/starsky/starsky.foundation.database/Query/QuerySingleItem.cs b/starsky/starsky.foundation.database/Query/QuerySingleItem.cs index c5196df275..71141fa31f 100644 --- a/starsky/starsky.foundation.database/Query/QuerySingleItem.cs +++ b/starsky/starsky.foundation.database/Query/QuerySingleItem.cs @@ -88,7 +88,7 @@ public partial class Query }; } - var currentFileIndexItem = fileIndexItemsList.FirstOrDefault(p => p.FileName == fileName); + var currentFileIndexItem = fileIndexItemsList.Find(p => p.FileName == fileName); // Could be not found or not in directory cache if ( currentFileIndexItem == null ) diff --git a/starsky/starsky.foundation.database/Thumbnails/ThumbnailQuery.cs b/starsky/starsky.foundation.database/Thumbnails/ThumbnailQuery.cs index 6945aded65..add67183b3 100644 --- a/starsky/starsky.foundation.database/Thumbnails/ThumbnailQuery.cs +++ b/starsky/starsky.foundation.database/Thumbnails/ThumbnailQuery.cs @@ -32,7 +32,7 @@ public ThumbnailQuery(ApplicationDbContext context, IServiceScopeFactory? scopeF public Task?> AddThumbnailRangeAsync(List thumbnailItems) { - if ( thumbnailItems.Any(p => string.IsNullOrEmpty(p.FileHash) ) ) + if ( thumbnailItems.Exists(p => string.IsNullOrEmpty(p.FileHash) ) ) { throw new ArgumentNullException(nameof(thumbnailItems), "[AddThumbnailRangeAsync] FileHash is null or empty"); } @@ -208,8 +208,8 @@ private static async Task RenameInternalAsync(ApplicationDbContext dbConte var beforeOrNewItems = await dbContext.Thumbnails.Where(p => p.FileHash == beforeFileHash || p.FileHash == newFileHash).ToListAsync(); - var beforeItem = beforeOrNewItems.FirstOrDefault(p => p.FileHash == beforeFileHash); - var newItem = beforeOrNewItems.FirstOrDefault(p => p.FileHash == newFileHash); + var beforeItem = beforeOrNewItems.Find(p => p.FileHash == beforeFileHash); + var newItem = beforeOrNewItems.Find(p => p.FileHash == newFileHash); if ( beforeItem == null) return false; diff --git a/starsky/starsky.foundation.injection/ServiceCollectionExtensions.cs b/starsky/starsky.foundation.injection/ServiceCollectionExtensions.cs index 1553fb58ab..127abeffb3 100644 --- a/starsky/starsky.foundation.injection/ServiceCollectionExtensions.cs +++ b/starsky/starsky.foundation.injection/ServiceCollectionExtensions.cs @@ -138,7 +138,7 @@ private static List GetEntryAssemblyReferencedAssemblies(List p.FullName == assemblyName.FullName); + var isThere = assemblies.Exists(p => p.FullName == assemblyName.FullName); if (IsWildcardMatch(assemblyName.Name!, assemblyFilter) && !isThere ) { assemblies.Add(AppDomain.CurrentDomain.Load(assemblyName)); @@ -165,7 +165,7 @@ private static Assembly[] GetReferencedAssemblies(List assemblies, IEn foreach ( var referencedAssembly in assembly.GetReferencedAssemblies() ) { if ( IsWildcardMatch(referencedAssembly.Name!, assemblyFilter) - && assemblies.All(p => p.FullName != referencedAssembly.FullName) ) + && assemblies.TrueForAll(p => p.FullName != referencedAssembly.FullName) ) { assemblies.Add(Assembly.Load(referencedAssembly)); } diff --git a/starsky/starsky.foundation.platform/Helpers/AppSettingsCompareHelper.cs b/starsky/starsky.foundation.platform/Helpers/AppSettingsCompareHelper.cs index b11aaa5ad5..e459c40209 100644 --- a/starsky/starsky.foundation.platform/Helpers/AppSettingsCompareHelper.cs +++ b/starsky/starsky.foundation.platform/Helpers/AppSettingsCompareHelper.cs @@ -1,4 +1,5 @@ #nullable enable +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -28,7 +29,7 @@ public static List Compare(AppSettings sourceIndexItem, object? updateOb foreach ( var propertyB in propertiesB ) { // only for when TransferObject is Nullable and AppSettings is bool - var propertyInfoFromA = propertiesA.FirstOrDefault(p => p.Name == propertyB.Name); + var propertyInfoFromA = Array.Find(propertiesA, p => p.Name == propertyB.Name); if ( propertyInfoFromA == null ) continue; if (propertyInfoFromA.PropertyType == typeof(bool?) && propertyB.PropertyType == typeof(bool?)) { @@ -277,8 +278,7 @@ internal static void CompareInt(string propertyName, AppSettings sourceIndexItem /// private static object? GetPropertyValue(object car, string propertyName) { - return car.GetType().GetProperties() - .FirstOrDefault(pi => pi.Name == propertyName)? + return Array.Find(car.GetType().GetProperties(), pi => pi.Name == propertyName)? .GetValue(car, null); } diff --git a/starsky/starsky.foundation.platform/Helpers/DateAssembly.cs b/starsky/starsky.foundation.platform/Helpers/DateAssembly.cs index 4e433f6fe7..ad18d92022 100644 --- a/starsky/starsky.foundation.platform/Helpers/DateAssembly.cs +++ b/starsky/starsky.foundation.platform/Helpers/DateAssembly.cs @@ -20,7 +20,11 @@ public static DateTime GetBuildDate(Assembly assembly) // build$([System.DateTime]::UtcNow.ToString("yyyyMMddHHmmss")) // var attribute = assembly.GetCustomAttribute(); - if ( attribute?.InformationalVersion == null ) return new DateTime(); + if ( attribute?.InformationalVersion == null ) + { + return new DateTime(0, DateTimeKind.Utc); + } + var value = attribute.InformationalVersion; return ParseBuildTime(value); } @@ -29,7 +33,10 @@ internal static DateTime ParseBuildTime(string value) { const string buildVersionMetadataPrefix = "+build"; var index = value.IndexOf(buildVersionMetadataPrefix, StringComparison.Ordinal); - if ( index <= 0 ) return new DateTime(); + if ( index <= 0 ) + { + return new DateTime(0, DateTimeKind.Utc); + } value = value.Substring(index + buildVersionMetadataPrefix.Length); return DateTime.TryParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var result) ? result : new DateTime(); diff --git a/starsky/starsky.foundation.platform/Models/AppSettings.cs b/starsky/starsky.foundation.platform/Models/AppSettings.cs index e4d36ca24e..0691d15a75 100644 --- a/starsky/starsky.foundation.platform/Models/AppSettings.cs +++ b/starsky/starsky.foundation.platform/Models/AppSettings.cs @@ -519,7 +519,7 @@ public bool IsReadOnly(string f) { if (!ReadOnlyFolders.Any() ) return false; - var result = ReadOnlyFolders.FirstOrDefault(f.Contains); + var result = ReadOnlyFolders.Find(f.Contains); return result != null; } @@ -1038,9 +1038,9 @@ public string DatabasePathToFilePath(string databaseFilePath, bool checkIfExist /// /// the input, the env should start with a $ /// the value or the input when nothing is found - internal string ReplaceEnvironmentVariable(string input) + internal static string ReplaceEnvironmentVariable(string input) { - if ( string.IsNullOrEmpty(input) || !input.StartsWith("$") ) return input; + if ( string.IsNullOrEmpty(input) || !input.StartsWith('$') ) return input; var value = Environment.GetEnvironmentVariable(input.Remove(0, 1)); return string.IsNullOrEmpty(value) ? input : value; } diff --git a/starsky/starsky.foundation.readmeta/Helpers/GeoParser.cs b/starsky/starsky.foundation.readmeta/Helpers/GeoParser.cs index a9566e176b..b40a83a0d4 100644 --- a/starsky/starsky.foundation.readmeta/Helpers/GeoParser.cs +++ b/starsky/starsky.foundation.readmeta/Helpers/GeoParser.cs @@ -88,7 +88,7 @@ public static GeoListItem ParseIsoString(string isoStr) // Check for minimum length // Check for trailing slash - if ( isoStr.Length < 18 || !isoStr.EndsWith("/") ) + if ( isoStr.Length < 18 || !isoStr.EndsWith('/') ) { return geoListItem; } diff --git a/starsky/starskytest/FakeMocks/FakeIQuery.cs b/starsky/starskytest/FakeMocks/FakeIQuery.cs index 101a052693..72d7df31f9 100644 --- a/starsky/starskytest/FakeMocks/FakeIQuery.cs +++ b/starsky/starskytest/FakeMocks/FakeIQuery.cs @@ -258,7 +258,7 @@ public Task> GetObjectsByFileHashAsync(List fileHash foreach ( var fileHash in fileHashesList ) { - if ( result.FirstOrDefault(p => p.FileHash == fileHash) == null ) + if ( result.Find(p => p.FileHash == fileHash) == null ) { result.Add(new FileIndexItem(){FileHash = fileHash, Status = FileIndexItem.ExifStatus.NotFoundNotInIndex}); diff --git a/starsky/starskytest/starsky.foundation.platform/Models/AppSettingsTest.cs b/starsky/starskytest/starsky.foundation.platform/Models/AppSettingsTest.cs index 3f93e51676..9872d674bb 100644 --- a/starsky/starskytest/starsky.foundation.platform/Models/AppSettingsTest.cs +++ b/starsky/starskytest/starsky.foundation.platform/Models/AppSettingsTest.cs @@ -63,21 +63,21 @@ public void AppSettingsProviderTest_SqLiteFullPathTest() [TestMethod] public void ReplaceEnvironmentVariable_Nothing() { - var value = _appSettings.ReplaceEnvironmentVariable(string.Empty); + var value = AppSettings.ReplaceEnvironmentVariable(string.Empty); Assert.AreEqual(string.Empty, value); } [TestMethod] public void ReplaceEnvironmentVariable_SomethingThatShouldBeIgnored() { - var value = _appSettings.ReplaceEnvironmentVariable("/test"); + var value = AppSettings.ReplaceEnvironmentVariable("/test"); Assert.AreEqual("/test", value); } [TestMethod] public void ReplaceEnvironmentVariable_Non_Existing_EnvVariable() { - var value = _appSettings.ReplaceEnvironmentVariable("$sdhfdskfbndsfjb38"); + var value = AppSettings.ReplaceEnvironmentVariable("$sdhfdskfbndsfjb38"); Assert.AreEqual("$sdhfdskfbndsfjb38", value); } @@ -86,7 +86,7 @@ public void ReplaceEnvironmentVariable_Existing_EnvVariable() { Environment.SetEnvironmentVariable("test123456789","123456789"); // should start with a dollar sign - var value = _appSettings.ReplaceEnvironmentVariable("$test123456789"); + var value = AppSettings.ReplaceEnvironmentVariable("$test123456789"); Assert.AreEqual("123456789", value); } From 09ea76bcb60c051b5bde5666ff43f38c4b7f79a4 Mon Sep 17 00:00:00 2001 From: Dion Date: Tue, 25 Jul 2023 15:06:08 +0200 Subject: [PATCH 08/10] code smells --- .../ReadMetaHelpers/ReadMetaExif.cs | 8 ++++---- .../ReadMetaHelpers/ReadMetaGpx.cs | 2 +- .../ArchiveFormats/TarBal.cs | 2 +- .../Services/StructureService.cs | 12 +++++++++--- .../Helpers/SizeFileHashIsTheSame.cs | 2 +- starsky/starsky.foundation.sync/Helpers/SyncCli.cs | 2 +- .../Helpers/SyncIgnoreCheck.cs | 2 +- .../SyncServices/SyncFolder.cs | 6 +++--- .../SyncServices/SyncMultiFile.cs | 2 +- .../SyncServices/SyncSingleFile.cs | 6 +++--- .../Services/OffsetDataMetaExifThumbnail.cs | 2 +- starsky/starsky/Controllers/DeleteController.cs | 8 ++++++-- starsky/starsky/Controllers/DiskController.cs | 4 ++-- starsky/starsky/Controllers/ExportController.cs | 2 +- starsky/starsky/Controllers/ImportController.cs | 4 ++-- starsky/starsky/Controllers/MetaInfoController.cs | 10 +++++++--- starsky/starsky/Controllers/MetaUpdateController.cs | 2 +- starsky/starsky/Controllers/PublishController.cs | 2 +- starsky/starsky/Controllers/SearchController.cs | 8 ++++---- starsky/starsky/Controllers/UploadController.cs | 2 +- .../components/atoms/button-styled/button-styled.tsx | 2 +- 21 files changed, 52 insertions(+), 38 deletions(-) diff --git a/starsky/starsky.foundation.readmeta/ReadMetaHelpers/ReadMetaExif.cs b/starsky/starsky.foundation.readmeta/ReadMetaHelpers/ReadMetaExif.cs index 3e451c4bf4..8463cf5043 100644 --- a/starsky/starsky.foundation.readmeta/ReadMetaHelpers/ReadMetaExif.cs +++ b/starsky/starsky.foundation.readmeta/ReadMetaHelpers/ReadMetaExif.cs @@ -284,16 +284,16 @@ private static string GetSonyMakeLensModel(List allExifItems, string private static ExtensionRolesHelper.ImageFormat GetFileSpecificTags(List allExifItems) { - if ( allExifItems.Any(p => p.Name == "JPEG") ) + if ( allExifItems.Exists(p => p.Name == "JPEG") ) return ExtensionRolesHelper.ImageFormat.jpg; - if ( allExifItems.Any(p => p.Name == "PNG-IHDR") ) + if ( allExifItems.Exists(p => p.Name == "PNG-IHDR") ) return ExtensionRolesHelper.ImageFormat.png; - if ( allExifItems.Any(p => p.Name == "BMP Header") ) + if ( allExifItems.Exists(p => p.Name == "BMP Header") ) return ExtensionRolesHelper.ImageFormat.bmp; - if ( allExifItems.Any(p => p.Name == "GIF Header") ) + if ( allExifItems.Exists(p => p.Name == "GIF Header") ) return ExtensionRolesHelper.ImageFormat.gif; return ExtensionRolesHelper.ImageFormat.unknown; diff --git a/starsky/starsky.foundation.readmeta/ReadMetaHelpers/ReadMetaGpx.cs b/starsky/starsky.foundation.readmeta/ReadMetaHelpers/ReadMetaGpx.cs index 4a872950d9..da7807deaa 100644 --- a/starsky/starsky.foundation.readmeta/ReadMetaHelpers/ReadMetaGpx.cs +++ b/starsky/starsky.foundation.readmeta/ReadMetaHelpers/ReadMetaGpx.cs @@ -51,7 +51,7 @@ public FileIndexItem ReadGpxFromFileReturnAfterFirstField(Stream? stream, } var title = readGpxFile.FirstOrDefault()?.Title ?? string.Empty; - var dateTime = readGpxFile.FirstOrDefault()?.DateTime ?? new DateTime(); + var dateTime = readGpxFile.FirstOrDefault()?.DateTime ?? new DateTime(0, DateTimeKind.Utc); var latitude = readGpxFile.FirstOrDefault()?.Latitude ?? 0d; var longitude = readGpxFile.FirstOrDefault()?.Longitude ?? 0d; var altitude = readGpxFile.FirstOrDefault()?.Altitude ?? 0d; diff --git a/starsky/starsky.foundation.storage/ArchiveFormats/TarBal.cs b/starsky/starsky.foundation.storage/ArchiveFormats/TarBal.cs index a59ea0457c..a7dcfce089 100644 --- a/starsky/starsky.foundation.storage/ArchiveFormats/TarBal.cs +++ b/starsky/starsky.foundation.storage/ArchiveFormats/TarBal.cs @@ -110,7 +110,7 @@ private async Task CreateFileOrDirectory(string outputDir, string name, long siz _storage.CreateDirectory(FilenamesHelper.GetParentPath(output)); } - if (!name.EndsWith("/")) //Directories are zero size and don't need anything written + if (!name.EndsWith('/')) // Directories are zero size and don't need anything written { var str = new MemoryStream(); var buf = new byte[size]; diff --git a/starsky/starsky.foundation.storage/Services/StructureService.cs b/starsky/starsky.foundation.storage/Services/StructureService.cs index 5612b88db1..5c96bc4788 100644 --- a/starsky/starsky.foundation.storage/Services/StructureService.cs +++ b/starsky/starsky.foundation.storage/Services/StructureService.cs @@ -141,7 +141,7 @@ private StringBuilder MatchChildDirectories(StringBuilder parentFolderBuilder, S // should return a list of: var childDirectories = _storage.GetDirectories(parentFolderBuilder.ToString()).ToList(); - var matchingFoldersPath= childDirectories.FirstOrDefault(p => + var matchingFoldersPath= childDirectories.Find(p => MatchChildFolderSearch(parentFolderBuilder,currentChildFolderBuilder,p) ); @@ -182,7 +182,13 @@ private static string RemoveAsteriskFromString(StringBuilder input ) /// When not start with / or is /.ext or not end with .ext private void CheckStructureFormat() { - if (!string.IsNullOrEmpty(_structure) && _structure.StartsWith("/") && _structure.EndsWith(".ext") && _structure != "/.ext" ) return; + if ( !string.IsNullOrEmpty(_structure) && + _structure.StartsWith('/') && _structure.EndsWith(".ext") && + _structure != "/.ext" ) + { + return; + } + throw new FieldAccessException("Structure is not right formatted, please read the documentation"); } @@ -252,7 +258,7 @@ private static string OutputStructureRangeItemParser(string pattern, DateTime da foreach ( Match match in matchCollection ) { // Ignore escaped items - if ( !match.Value.StartsWith("\\") && match.Index == 0 && match.Length == pattern.Length ) + if ( !match.Value.StartsWith('\\') && match.Index == 0 && match.Length == pattern.Length ) { return dateTime.ToString(pattern, CultureInfo.InvariantCulture); } diff --git a/starsky/starsky.foundation.sync/Helpers/SizeFileHashIsTheSame.cs b/starsky/starsky.foundation.sync/Helpers/SizeFileHashIsTheSame.cs index 68ff5bfc0c..dbcfd95c96 100644 --- a/starsky/starsky.foundation.sync/Helpers/SizeFileHashIsTheSame.cs +++ b/starsky/starsky.foundation.sync/Helpers/SizeFileHashIsTheSame.cs @@ -26,7 +26,7 @@ public SizeFileHashIsTheSameHelper(IStorage subPathStorage) /// Last Edited is the bool (null is should check further in process), FileHash Same bool (null is not checked) , database item internal async Task> SizeFileHashIsTheSame(List dbItems, string subPath) { - var dbItem = dbItems.FirstOrDefault(p => p.FilePath == subPath); + var dbItem = dbItems.Find(p => p.FilePath == subPath); if ( dbItem == null ) { return new Tuple(false, false, null); diff --git a/starsky/starsky.foundation.sync/Helpers/SyncCli.cs b/starsky/starsky.foundation.sync/Helpers/SyncCli.cs index a64ad758e1..ea2890d175 100644 --- a/starsky/starsky.foundation.sync/Helpers/SyncCli.cs +++ b/starsky/starsky.foundation.sync/Helpers/SyncCli.cs @@ -54,7 +54,7 @@ public async Task Sync(string[] args) var stopWatch = Stopwatch.StartNew(); _console.WriteLine($"Start indexing {subPath}"); var result = await _synchronize.Sync(subPath); - if ( result.All(p => p.FilePath != subPath) ) + if ( result.TrueForAll(p => p.FilePath != subPath) ) { _console.WriteLine($"Not Found: {subPath}"); } diff --git a/starsky/starsky.foundation.sync/Helpers/SyncIgnoreCheck.cs b/starsky/starsky.foundation.sync/Helpers/SyncIgnoreCheck.cs index ba62c4b01d..74712a3278 100644 --- a/starsky/starsky.foundation.sync/Helpers/SyncIgnoreCheck.cs +++ b/starsky/starsky.foundation.sync/Helpers/SyncIgnoreCheck.cs @@ -17,7 +17,7 @@ public SyncIgnoreCheck(AppSettings appSettings, IConsole console) public bool Filter(string subPath) { - var isSynced = _appSettings.SyncIgnore.Any(subPath.StartsWith); + var isSynced = _appSettings.SyncIgnore.Exists(subPath.StartsWith); if ( isSynced && _appSettings.IsVerbose()) _console.WriteLine($"sync ignored for: {subPath}"); return isSynced; } diff --git a/starsky/starsky.foundation.sync/SyncServices/SyncFolder.cs b/starsky/starsky.foundation.sync/SyncServices/SyncFolder.cs index 058f7e6941..1289be1e45 100644 --- a/starsky/starsky.foundation.sync/SyncServices/SyncFolder.cs +++ b/starsky/starsky.foundation.sync/SyncServices/SyncFolder.cs @@ -137,7 +137,7 @@ internal async Task CompareFolderListAndFixMissingFolders(List subPaths, { if ( subPaths.Count == folderList.Count ) return; - foreach ( var path in subPaths.Where(path => folderList.All(p => p.FilePath != path) && + foreach ( var path in subPaths.Where(path => folderList.Exists(p => p.FilePath != path) && _subPathStorage.ExistFolder(path) && !_syncIgnoreCheck.Filter(path) ) ) { await _query.AddItemAsync(new FileIndexItem(path) @@ -155,7 +155,7 @@ internal async Task> AddParentFolder(string subPath, List p.FilePath).ToList(); - if ( allResults.All(p => p.FilePath != subPath)) + if ( allResults.TrueForAll(p => p.FilePath != subPath)) { var subPathStatus = _subPathStorage.IsFolderOrFile(subPath); var exifStatus = subPathStatus == @@ -301,7 +301,7 @@ internal static List PathsToUpdateInDatabase( var resultDatabaseItems = new List(databaseItems); foreach ( var path in pathsOnDisk ) { - var item = databaseItems.FirstOrDefault(p => string.Equals(p.FilePath, path, StringComparison.InvariantCultureIgnoreCase)); + var item = databaseItems.Find(p => string.Equals(p.FilePath, path, StringComparison.InvariantCultureIgnoreCase)); if (item == null ) // when the file should be added to the index { // Status is used by MultiFile diff --git a/starsky/starsky.foundation.sync/SyncServices/SyncMultiFile.cs b/starsky/starsky.foundation.sync/SyncServices/SyncMultiFile.cs index 17e90b38ba..262b2417b6 100644 --- a/starsky/starsky.foundation.sync/SyncServices/SyncMultiFile.cs +++ b/starsky/starsky.foundation.sync/SyncServices/SyncMultiFile.cs @@ -50,7 +50,7 @@ internal async Task> MultiFile(List subPathInFiles, var resultDatabaseItems = new List(); foreach ( var path in subPathInFiles ) { - var item = databaseItems.FirstOrDefault(p => + var item = databaseItems.Find(p => string.Equals(p.FilePath, path, StringComparison.InvariantCultureIgnoreCase)); if (item == null ) // when the file should be added to the index { diff --git a/starsky/starsky.foundation.sync/SyncServices/SyncSingleFile.cs b/starsky/starsky.foundation.sync/SyncServices/SyncSingleFile.cs index a4f8f69ce6..d4acaff790 100644 --- a/starsky/starsky.foundation.sync/SyncServices/SyncSingleFile.cs +++ b/starsky/starsky.foundation.sync/SyncServices/SyncSingleFile.cs @@ -44,7 +44,7 @@ internal async Task> SingleFile(string subPath, ISynchronize.SocketUpdateDelegate? updateDelegate = null) { // when item does not exist in db - if ( dbItems?.FirstOrDefault(p => p.FilePath == subPath) == null ) + if ( dbItems?.Find(p => p.FilePath == subPath) == null ) { return await SingleFile(subPath); } @@ -81,7 +81,7 @@ internal async Task> SingleFile(string subPath, var dbItems = await _query.GetObjectsByFilePathAsync(subPath,true); foreach ( var item in statusItems ) { - var dbItem = dbItems.FirstOrDefault(p => item.FilePath == p.FilePath); + var dbItem = dbItems.Find(p => item.FilePath == p.FilePath); if ( dbItem != null ) { scanItems.Add(dbItem); @@ -91,7 +91,7 @@ internal async Task> SingleFile(string subPath, scanItems.Add(item); } - foreach ( var item in dbItems.Where(item => scanItems.All(p => p.FilePath != item.FilePath)) ) + foreach ( var item in dbItems.Where(item => scanItems.TrueForAll(p => p.FilePath != item.FilePath)) ) { scanItems.Add(item); } diff --git a/starsky/starsky.foundation.thumbnailmeta/Services/OffsetDataMetaExifThumbnail.cs b/starsky/starsky.foundation.thumbnailmeta/Services/OffsetDataMetaExifThumbnail.cs index dee871a22a..a4e484ea97 100644 --- a/starsky/starsky.foundation.thumbnailmeta/Services/OffsetDataMetaExifThumbnail.cs +++ b/starsky/starsky.foundation.thumbnailmeta/Services/OffsetDataMetaExifThumbnail.cs @@ -46,7 +46,7 @@ public OffsetDataMetaExifThumbnail(ISelectorStorage selectorStorage, IWebLogger var allExifItems = ImageMetadataReader.ReadMetadata(stream).ToList(); var exifThumbnailDir = - allExifItems.FirstOrDefault(p => + allExifItems.Find(p => p.Name == "Exif Thumbnail") as ExifThumbnailDirectory; return ( allExifItems, exifThumbnailDir); diff --git a/starsky/starsky/Controllers/DeleteController.cs b/starsky/starsky/Controllers/DeleteController.cs index 0ee33f8a30..91a1df3aa2 100644 --- a/starsky/starsky/Controllers/DeleteController.cs +++ b/starsky/starsky/Controllers/DeleteController.cs @@ -36,8 +36,12 @@ public async Task Delete(string f, bool collections = false) var fileIndexResultsList = await _deleteItem.DeleteAsync(f, collections); // When all items are not found // ok = file is deleted - if (fileIndexResultsList.All(p => p.Status != FileIndexItem.ExifStatus.Ok)) - return NotFound(fileIndexResultsList); + if ( fileIndexResultsList.TrueForAll(p => + p.Status != FileIndexItem.ExifStatus.Ok) ) + { + return NotFound(fileIndexResultsList); + } + return Json(fileIndexResultsList); } diff --git a/starsky/starsky/Controllers/DiskController.cs b/starsky/starsky/Controllers/DiskController.cs index 95e18aeaf9..1c2f63cb42 100644 --- a/starsky/starsky/Controllers/DiskController.cs +++ b/starsky/starsky/Controllers/DiskController.cs @@ -88,7 +88,7 @@ await _query.AddItemAsync(new FileIndexItem(subPath) } // When all items are not found - if (syncResultsList.All(p => p.Status != FileIndexItem.ExifStatus.Ok)) + if (syncResultsList.TrueForAll(p => p.Status != FileIndexItem.ExifStatus.Ok)) Response.StatusCode = 409; // A conflict, Directory already exist await SyncMessageToSocket(syncResultsList, ApiNotificationType.Mkdir); @@ -141,7 +141,7 @@ public async Task Rename(string f, string to, bool collections = var rename = await new RenameService(_query, _iStorage).Rename(f, to, collections); // When all items are not found - if (rename.All(p => p.Status != FileIndexItem.ExifStatus.Ok)) + if (rename.TrueForAll(p => p.Status != FileIndexItem.ExifStatus.Ok)) return NotFound(rename); var webSocketResponse = diff --git a/starsky/starsky/Controllers/ExportController.cs b/starsky/starsky/Controllers/ExportController.cs index fc59d82698..1a147e8bc4 100644 --- a/starsky/starsky/Controllers/ExportController.cs +++ b/starsky/starsky/Controllers/ExportController.cs @@ -49,7 +49,7 @@ public async Task CreateZip(string f, bool collections = true, bo // When all items are not found // allow read only - if (fileIndexResultsList.All(p => p.Status != FileIndexItem.ExifStatus.Ok) ) + if (fileIndexResultsList.TrueForAll(p => p.Status != FileIndexItem.ExifStatus.Ok) ) return NotFound(fileIndexResultsList); // NOT covered: when try to export for example image thumbnails of xml file diff --git a/starsky/starsky/Controllers/ImportController.cs b/starsky/starsky/Controllers/ImportController.cs index b3bb0522d6..d71515f6be 100644 --- a/starsky/starsky/Controllers/ImportController.cs +++ b/starsky/starsky/Controllers/ImportController.cs @@ -88,13 +88,13 @@ await _bgTaskQueue.QueueBackgroundWorkItemAsync(async _ => // When all items are already imported if ( importSettings.IndexMode && - fileIndexResultsList.All(p => p.Status != ImportStatus.Ok) ) + fileIndexResultsList.TrueForAll(p => p.Status != ImportStatus.Ok) ) { Response.StatusCode = 206; } // Wrong input (extension is not allowed) - if ( fileIndexResultsList.All(p => p.Status == ImportStatus.FileError) ) + if ( fileIndexResultsList.TrueForAll(p => p.Status == ImportStatus.FileError) ) { Response.StatusCode = 415; } diff --git a/starsky/starsky/Controllers/MetaInfoController.cs b/starsky/starsky/Controllers/MetaInfoController.cs index 6ac38d2918..aa86dc1ea7 100644 --- a/starsky/starsky/Controllers/MetaInfoController.cs +++ b/starsky/starsky/Controllers/MetaInfoController.cs @@ -40,15 +40,19 @@ public IActionResult Info(string f, bool collections = true) var fileIndexResultsList = _metaInfo.GetInfo(inputFilePaths, collections); // returns read only - if (fileIndexResultsList.All(p => p.Status == FileIndexItem.ExifStatus.ReadOnly)) + if (fileIndexResultsList.TrueForAll(p => p.Status == FileIndexItem.ExifStatus.ReadOnly)) { Response.StatusCode = 203; // is readonly return Json(fileIndexResultsList); } // When all items are not found - if (fileIndexResultsList.All(p => (p.Status != FileIndexItem.ExifStatus.Ok && p.Status != FileIndexItem.ExifStatus.Deleted))) - return NotFound(fileIndexResultsList); + if ( fileIndexResultsList.TrueForAll(p => + ( p.Status != FileIndexItem.ExifStatus.Ok && + p.Status != FileIndexItem.ExifStatus.Deleted )) ) + { + return NotFound(fileIndexResultsList); + } return Json(fileIndexResultsList); } diff --git a/starsky/starsky/Controllers/MetaUpdateController.cs b/starsky/starsky/Controllers/MetaUpdateController.cs index d42a5b3379..375fd55ab5 100644 --- a/starsky/starsky/Controllers/MetaUpdateController.cs +++ b/starsky/starsky/Controllers/MetaUpdateController.cs @@ -98,7 +98,7 @@ await _bgTaskQueue.QueueBackgroundWorkItemAsync(async _ => new StopWatchLogger(_logger).StopUpdateReplaceStopWatch("update", f,collections, stopwatch); // When all items are not found - if ( fileIndexResultsList.All(p => + if ( fileIndexResultsList.TrueForAll(p => p.Status != FileIndexItem.ExifStatus.Ok && p.Status != FileIndexItem.ExifStatus.Deleted) ) { diff --git a/starsky/starsky/Controllers/PublishController.cs b/starsky/starsky/Controllers/PublishController.cs index d89b7fbe64..fc7ca4f19c 100644 --- a/starsky/starsky/Controllers/PublishController.cs +++ b/starsky/starsky/Controllers/PublishController.cs @@ -84,7 +84,7 @@ public async Task PublishCreateAsync(string f, string itemName, _webLogger.LogInformation($"[/api/publish/create] Press publish: {itemName} {f} {DateTime.UtcNow}"); var inputFilePaths = PathHelper.SplitInputFilePaths(f).ToList(); var info = _metaInfo.GetInfo(inputFilePaths, false); - if ( info.All(p => + if ( info.TrueForAll(p => p.Status != FileIndexItem.ExifStatus.Ok && p.Status != FileIndexItem.ExifStatus.ReadOnly) ) { diff --git a/starsky/starsky/Controllers/SearchController.cs b/starsky/starsky/Controllers/SearchController.cs index 70bf023ce8..0c03330417 100644 --- a/starsky/starsky/Controllers/SearchController.cs +++ b/starsky/starsky/Controllers/SearchController.cs @@ -86,10 +86,10 @@ public async Task SearchRelative(string f, string t, int p = 0) /// int as index, fallback == -1 internal static int GetIndexFilePathFromSearch(SearchViewModel searchViewModel, string f) { - var result = searchViewModel.FileIndexItems.FirstOrDefault(p => p.FilePath == f); - var photoIndexOfQuery = searchViewModel.FileIndexItems.IndexOf(result); - if ( result == null ) return -1; - return photoIndexOfQuery; + var result = searchViewModel.FileIndexItems?.Find(p => p.FilePath == f); + var photoIndexOfQuery = searchViewModel.FileIndexItems?.IndexOf(result); + if ( result == null || photoIndexOfQuery == null) return -1; + return photoIndexOfQuery.Value; } /// diff --git a/starsky/starsky/Controllers/UploadController.cs b/starsky/starsky/Controllers/UploadController.cs index f7fdadcd9a..0e8554e55f 100644 --- a/starsky/starsky/Controllers/UploadController.cs +++ b/starsky/starsky/Controllers/UploadController.cs @@ -161,7 +161,7 @@ public async Task UploadToFolder() await _metaUpdateStatusThumbnailService.UpdateStatusThumbnail(metaResultsList); // Wrong input (extension is not allowed) - if ( fileIndexResultsList.All(p => p.Status == ImportStatus.FileError) ) + if ( fileIndexResultsList.TrueForAll(p => p.Status == ImportStatus.FileError) ) { _logger.LogInformation($"Wrong input extension is not allowed" + $" {string.Join(",",fileIndexResultsList.Select(p => p.FilePath))}"); diff --git a/starsky/starsky/clientapp/src/components/atoms/button-styled/button-styled.tsx b/starsky/starsky/clientapp/src/components/atoms/button-styled/button-styled.tsx index 835f440356..c91bc07ae3 100644 --- a/starsky/starsky/clientapp/src/components/atoms/button-styled/button-styled.tsx +++ b/starsky/starsky/clientapp/src/components/atoms/button-styled/button-styled.tsx @@ -14,7 +14,7 @@ export interface IButtonProps { const ButtonStyled: React.FunctionComponent = memo((props) => { return (