-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathPooledImmichFrameLogic.cs
More file actions
214 lines (167 loc) · 7.76 KB
/
Copy pathPooledImmichFrameLogic.cs
File metadata and controls
214 lines (167 loc) · 7.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
using ImmichFrame.Core.Api;
using ImmichFrame.Core.Exceptions;
using ImmichFrame.Core.Helpers;
using ImmichFrame.Core.Interfaces;
using ImmichFrame.Core.Logic.Pool;
using ImmichFrame.Core.Models;
namespace ImmichFrame.Core.Logic;
public class PooledImmichFrameLogic : IAccountImmichFrameLogic
{
private readonly IGeneralSettings _generalSettings;
private readonly IApiCache _apiCache;
private readonly IAssetPool _pool;
private readonly ImmichApi _immichApi;
private readonly string _downloadLocation = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ImageCache");
public PooledImmichFrameLogic(IAccountSettings accountSettings, IGeneralSettings generalSettings, IHttpClientFactory httpClientFactory)
{
_generalSettings = generalSettings;
var httpClient = httpClientFactory.CreateClient("ImmichApiAccountClient");
AccountSettings = accountSettings;
httpClient.UseApiKey(accountSettings.ApiKey);
_immichApi = new ImmichApi(accountSettings.ImmichServerUrl, httpClient);
_apiCache = new ApiCache(RefreshInterval(generalSettings.RefreshAlbumPeopleInterval));
_pool = BuildPool(accountSettings);
}
private static TimeSpan RefreshInterval(int hours)
=> hours > 0 ? TimeSpan.FromHours(hours) : TimeSpan.FromMilliseconds(1);
public IAccountSettings AccountSettings { get; }
private IAssetPool BuildPool(IAccountSettings accountSettings)
{
return WithExhaustiveShuffle(BuildSourcePool(accountSettings), accountSettings);
}
// Wraps the source pool so each asset is shown once before any repeats (see ShuffleBagAssetPool).
private static IAssetPool WithExhaustiveShuffle(IAssetPool pool, IAccountSettings accountSettings)
=> accountSettings.ExhaustiveShuffle ? new ShuffleBagAssetPool(pool) : pool;
private IAssetPool BuildSourcePool(IAccountSettings accountSettings)
{
var hasAlbums = accountSettings.Albums?.Any() ?? false;
var hasPeople = accountSettings.People?.Any() ?? false;
var hasTags = accountSettings.Tags?.Any() ?? false;
if (!accountSettings.ShowFavorites && !accountSettings.ShowMemories && !hasAlbums && !hasPeople && !hasTags)
{
return new AllAssetsPool(_apiCache, _immichApi, accountSettings);
}
var pools = new List<IAssetPool>();
if (accountSettings.ShowFavorites)
pools.Add(new FavoriteAssetsPool(_apiCache, _immichApi, accountSettings));
if (accountSettings.ShowMemories)
pools.Add(new MemoryAssetsPool(_immichApi, accountSettings));
if (hasAlbums)
pools.Add(new AlbumAssetsPool(_apiCache, _immichApi, accountSettings));
if (hasPeople)
pools.Add(new PersonAssetsPool(_apiCache, _immichApi, accountSettings));
if (hasTags)
pools.Add(new TagAssetsPool(_apiCache, _immichApi, accountSettings));
return new MultiAssetPool(pools);
}
public async Task<AssetResponseDto?> GetNextAsset()
{
return (await _pool.GetAssets(1)).FirstOrDefault();
}
public Task<IEnumerable<AssetResponseDto>> GetAssets()
{
return _pool.GetAssets(25);
}
public Task<AssetResponseDto> GetAssetInfoById(Guid assetId) => _immichApi.GetAssetInfoAsync(assetId, null);
public async Task<IEnumerable<AlbumResponseDto>> GetAlbumInfoById(Guid assetId) => await _immichApi.GetAllAlbumsAsync(assetId, null);
public Task<long> GetTotalAssets() => _pool.GetAssetCount();
public async Task<AssetResponse> GetAsset(Guid id, AssetTypeEnum? assetType = null, string? rangeHeader = null)
{
if (!assetType.HasValue)
{
var assetInfo = await _immichApi.GetAssetInfoAsync(id, null);
if (assetInfo == null)
throw new AssetNotFoundException($"Assetinfo for asset '{id}' was not found!");
assetType = assetInfo.Type;
}
if (assetType == AssetTypeEnum.IMAGE)
{
var (fileName, contentType, fileStream) = await GetImageAsset(id);
return new AssetResponse
{
FileName = fileName,
ContentType = contentType,
FileStream = fileStream,
ContentRange = null,
IsPartial = false,
Owner = null,
ContentLength = null
};
}
if (assetType == AssetTypeEnum.VIDEO)
{
return await GetVideoAsset(id, rangeHeader);
}
throw new AssetNotFoundException($"Asset {id} is not a supported media type ({assetType}).");
}
private async Task<(string fileName, string ContentType, Stream fileStream)> GetImageAsset(Guid id)
{
if (_generalSettings.DownloadImages)
{
if (!Directory.Exists(_downloadLocation))
{
Directory.CreateDirectory(_downloadLocation);
}
var file = Directory.GetFiles(_downloadLocation)
.FirstOrDefault(x => Path.GetFileNameWithoutExtension(x) == id.ToString());
if (!string.IsNullOrWhiteSpace(file))
{
if (_generalSettings.RenewImagesDuration > (DateTime.UtcNow - File.GetCreationTimeUtc(file)).Days)
{
var fs = File.OpenRead(file);
var ex = Path.GetExtension(file).TrimStart('.');
return (Path.GetFileName(file), $"image/{ex}", fs);
}
File.Delete(file);
}
}
var data = await _immichApi.ViewAssetAsync(id, string.Empty, AssetMediaSize.Preview);
if (data == null)
throw new AssetNotFoundException($"Asset {id} was not found!");
var contentType = "";
if (data.Headers.ContainsKey("Content-Type"))
{
contentType = data.Headers["Content-Type"].FirstOrDefault() ?? "";
}
var ext = contentType.ToLower() == "image/webp" ? "webp" : "jpeg";
var fileName = $"{id}.{ext}";
if (_generalSettings.DownloadImages)
{
var stream = data.Stream;
var filePath = Path.Combine(_downloadLocation, fileName);
// save to folder
var fs = File.Create(filePath);
await stream.CopyToAsync(fs);
fs.Position = 0;
return (Path.GetFileName(filePath), contentType, fs);
}
return (fileName, contentType, data.Stream);
}
private async Task<AssetResponse> GetVideoAsset(Guid id, string? rangeHeader = null)
{
var videoResponse = string.IsNullOrEmpty(rangeHeader)
? await _immichApi.PlayAssetVideoAsync(id, string.Empty)
: await _immichApi.PlayAssetVideoWithRangeAsync(id, rangeHeader);
var contentType = videoResponse.Headers.TryGetValue("Content-Type", out var ct)
? ct.FirstOrDefault() ?? "video/mp4"
: "video/mp4";
var contentRange = videoResponse.Headers.TryGetValue("Content-Range", out var cr)
? cr.FirstOrDefault()
: null;
long? contentLength = videoResponse.Headers.TryGetValue("Content-Length", out var cl)
&& long.TryParse(cl.FirstOrDefault(), out var clValue) ? clValue : null;
return new AssetResponse
{
FileName = $"{id}.mp4",
ContentType = contentType,
FileStream = videoResponse.Stream,
ContentRange = contentRange,
IsPartial = videoResponse.StatusCode == 206,
Owner = videoResponse,
ContentLength = contentLength
};
}
public Task SendWebhookNotification(IWebhookNotification notification) =>
WebhookHelper.SendWebhookNotification(notification, _generalSettings.Webhook);
public override string ToString() => $"Account Pool [{_immichApi.BaseUrl}]";
}