/
IntegrationManager.cs
345 lines (295 loc) · 13.8 KB
/
IntegrationManager.cs
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Copyright Bastian Eicher et al.
// Licensed under the GNU Lesser Public License
using System.Text.RegularExpressions;
using NanoByte.Common.Native;
using ZeroInstall.DesktopIntegration.AccessPoints;
using ZeroInstall.Store.Configuration;
namespace ZeroInstall.DesktopIntegration;
/// <summary>
/// Manages an <see cref="AppList"/> and desktop integration via <see cref="AccessPoint"/>s.
/// </summary>
/// <remarks>
/// To prevent race-conditions there may only be one desktop integration class instance active at any given time.
/// This class acquires a mutex upon calling its constructor and releases it upon calling <see cref="IDisposable.Dispose"/>.
/// </remarks>
[MustDisposeResource]
public class IntegrationManager : IntegrationManagerBase
{
#region Constants
/// <summary>
/// The name of the cross-process mutex used to signal that a desktop integration process class is currently active.
/// </summary>
protected override string MutexName => "ZeroInstall.DesktopIntegration";
/// <summary>
/// The window message ID (for use with <see cref="WindowsUtils.BroadcastMessage"/>) that signals integration changes to interested observers.
/// </summary>
public static readonly int ChangedWindowMessageID;
static IntegrationManager()
{
if (WindowsUtils.IsWindows)
ChangedWindowMessageID = WindowsUtils.RegisterWindowMessage("ZeroInstall.DesktopIntegration");
}
#endregion
/// <summary>
/// User settings controlling network behaviour.
/// </summary>
protected readonly Config Config;
/// <summary>
/// Returns a path for a directory that can be used for desktop integration.
/// </summary>
/// <param name="machineWide"><c>true</c> if the directory should be machine-wide and machine-specific instead of roaming with the user profile.</param>
/// <param name="resource">The directory name of the resource to be stored.</param>
/// <returns>A fully qualified directory path. The directory is guaranteed to already exist.</returns>
/// <exception cref="IOException">A problem occurred while creating a directory.</exception>
/// <exception cref="UnauthorizedAccessException">Creating a directory is not permitted.</exception>
/// <remarks>If a new directory is created with <paramref name="machineWide"/> set to <c>true</c> on Windows, ACLs are set to deny write access for non-Administrator users.</remarks>
public static string GetDir(bool machineWide, params string[] resource)
=> machineWide
? Locations.GetSaveSystemConfigPath("0install.net", isFile: false, ["desktop-integration", ..resource])
: Locations.GetSaveConfigPath("0install.net", isFile: false, ["desktop-integration", ..resource]);
/// <summary>
/// The storage location of the <see cref="AppList"/> file.
/// </summary>
protected readonly string AppListPath;
#region Constructor
/// <summary>
/// Creates a new integration manager using the default <see cref="DesktopIntegration.AppList"/> (creating a new one if missing). Performs Mutex-based locking!
/// </summary>
/// <param name="config">User settings controlling network behaviour.</param>
/// <param name="handler">A callback object used when the user is to be informed about the progress of long-running operations such as downloads.</param>
/// <param name="machineWide">Apply operations machine-wide instead of just for the current user.</param>
/// <exception cref="IOException">A problem occurred while accessing the <see cref="AppList"/> file.</exception>
/// <exception cref="UnauthorizedAccessException">Read or write access to the <see cref="AppList"/> file is not permitted or another desktop integration class is currently active.</exception>
/// <exception cref="InvalidDataException">A problem occurred while deserializing an XML file.</exception>
public IntegrationManager(Config config, ITaskHandler handler, bool machineWide = false)
: base(handler, machineWide)
{
Config = config ?? throw new ArgumentNullException(nameof(config));
try
{
AcquireMutex();
}
catch (TimeoutException)
{
throw new UnauthorizedAccessException(Resources.IntegrationMutex);
}
try
{
AppListPath = AppList.GetDefaultPath(machineWide);
if (File.Exists(AppListPath))
{
Log.Debug($"Loading AppList for IntegrationManager from: {AppListPath}");
AppList = XmlStorage.LoadXml<AppList>(AppListPath);
}
else
{
Log.Debug($"Creating new AppList for IntegrationManager: {AppListPath}");
AppList = new AppList();
AppList.SaveXml(AppListPath);
}
}
#region Error handling
catch
{
// Avoid abandoned mutexes
base.Dispose();
throw;
}
#endregion
}
#endregion
//--------------------//
#region Apps
/// <inheritdoc/>
protected override AppEntry AddAppInternal(FeedTarget target)
{
// Prevent double entries
if (AppList.ContainsEntry(target.Uri)) throw new InvalidOperationException(string.Format(Resources.AppAlreadyInList, target.Feed.Name));
// Get basic metadata and copy of capabilities from feed
var appEntry = new AppEntry
{
InterfaceUri = target.Uri,
Name = target.Feed.Name,
Timestamp = DateTime.UtcNow,
CapabilityLists = {target.Feed.CapabilityLists.CloneElements()}
};
AppList.Entries.Add(appEntry);
WriteAppDir(appEntry);
return appEntry;
}
/// <inheritdoc/>
protected override AppEntry AddAppInternal(string petName, Requirements requirements, Feed feed)
{
#region Sanity checks
if (string.IsNullOrEmpty(petName)) throw new ArgumentNullException(nameof(petName));
if (requirements == null) throw new ArgumentNullException(nameof(requirements));
if (feed == null) throw new ArgumentNullException(nameof(feed));
#endregion
throw new NotImplementedException();
/*
// Prevent double entries
if (AppList.ContainsEntry(petName)) throw new InvalidOperationException(string.Format(Resources.AppAlreadyInList, feed.Name));
// Get basic metadata and copy of capabilities from feed
var appEntry = new AppEntry {InterfaceUri = petName, Requirements = requirements, Name = feed.Name, Timestamp = DateTime.UtcNow};
appEntry.CapabilityLists.Add(feed.CapabilityLists.CloneElements());
AppList.Entries.Add(appEntry);
WriteAppDir(appEntry);
return appEntry;
*/
}
/// <inheritdoc/>
protected override void AddAppInternal(AppEntry prototype, Converter<FeedUri, Feed> feedRetriever)
{
#region Sanity checks
if (prototype == null) throw new ArgumentNullException(nameof(prototype));
if (feedRetriever == null) throw new ArgumentNullException(nameof(feedRetriever));
#endregion
var appEntry = prototype.Clone();
AppList.Entries.Add(appEntry);
WriteAppDir(appEntry);
if (appEntry.AccessPoints != null)
AddAccessPointsInternal(appEntry, feedRetriever(appEntry.InterfaceUri), appEntry.AccessPoints.Clone().Entries);
}
/// <inheritdoc/>
protected override void RemoveAppInternal(AppEntry appEntry)
{
#region Sanity checks
if (appEntry == null) throw new ArgumentNullException(nameof(appEntry));
#endregion
DeleteAppDir(appEntry);
if (appEntry.AccessPoints != null)
{
// Unapply any remaining access points
foreach (var accessPoint in appEntry.AccessPoints.Entries)
accessPoint.Unapply(appEntry, MachineWide);
}
AppList.Entries.Remove(appEntry);
}
/// <inheritdoc/>
protected override void UpdateAppInternal(AppEntry appEntry, Feed feed)
{
#region Sanity checks
if (appEntry == null) throw new ArgumentNullException(nameof(appEntry));
if (feed == null) throw new ArgumentNullException(nameof(feed));
#endregion
// Temporarily remove capability-based access points but remember them for later reapplication
var toReapply = new List<AccessPoint>();
if (appEntry.AccessPoints != null)
toReapply.Add(appEntry.AccessPoints.Entries.Where(accessPoint => accessPoint is DefaultAccessPoint or CapabilityRegistration));
RemoveAccessPointsInternal(appEntry, toReapply);
// Update metadata and capabilities
appEntry.Name = feed.Name;
appEntry.CapabilityLists.Clear();
appEntry.CapabilityLists.Add(feed.CapabilityLists.CloneElements());
// Reapply removed access points dumping any that have become incompatible
foreach (var accessPoint in toReapply)
{
try
{
AddAccessPointsInternal(appEntry, feed, [accessPoint]);
}
#region Error handling
catch (KeyNotFoundException)
{
Log.Warn($"Access point '{accessPoint}' no longer compatible with interface '{appEntry.InterfaceUri}'.");
}
#endregion
}
WriteAppDir(appEntry);
appEntry.Timestamp = DateTime.UtcNow;
}
#endregion
#region AccessPoint
/// <inheritdoc/>
protected override void AddAccessPointsInternal(AppEntry appEntry, Feed feed, IReadOnlyCollection<AccessPoint> accessPoints)
{
#region Sanity checks
if (appEntry == null) throw new ArgumentNullException(nameof(appEntry));
if (feed == null) throw new ArgumentNullException(nameof(feed));
if (accessPoints == null) throw new ArgumentNullException(nameof(accessPoints));
if (appEntry.AccessPoints != null && ReferenceEquals(appEntry.AccessPoints.Entries, accessPoints)) throw new ArgumentException("Must not be equal to appEntry.AccessPoints.Entries", nameof(accessPoints));
#endregion
// Skip entries with mismatching hostname
if (appEntry.Hostname != null && !Regex.IsMatch(Environment.MachineName, appEntry.Hostname)) return;
appEntry.AccessPoints ??= new();
AppList.CheckForConflicts(accessPoints, appEntry);
var iconStore = IconStores.DesktopIntegration(Config, Handler, MachineWide);
// Load splash screen into icon store if specified, used by GUI for branding
try
{
_ = feed.SplashScreens.GetIcon(Icon.MimeTypePng)
?.To(iconStore.GetFresh);
}
#region Error handling
catch (InvalidDataException ex)
{
Log.Warn(ex);
}
#endregion
Handler.RunTask(ForEachTask.Create(string.Format(Resources.ApplyingIntegration, appEntry.Name),
accessPoints,
action: accessPoint => accessPoint.Apply(appEntry, feed, iconStore, MachineWide),
rollback: accessPoint =>
{
// Don't perform rollback if the access point was already applied previously and this was only a refresh
if (!appEntry.AccessPoints.Entries.Contains(accessPoint))
accessPoint.Unapply(appEntry, MachineWide);
}));
appEntry.AccessPoints.Entries.Remove(accessPoints); // Replace pre-existing entries
appEntry.AccessPoints.Entries.Add(accessPoints);
appEntry.Timestamp = DateTime.UtcNow;
}
/// <inheritdoc/>
protected override void RemoveAccessPointsInternal(AppEntry appEntry, IEnumerable<AccessPoint> accessPoints)
{
#region Sanity checks
if (appEntry == null) throw new ArgumentNullException(nameof(appEntry));
if (accessPoints == null) throw new ArgumentNullException(nameof(accessPoints));
#endregion
if (appEntry.AccessPoints == null) return;
accessPoints = accessPoints.ToArray();
foreach (var accessPoint in accessPoints)
accessPoint.Unapply(appEntry, MachineWide);
// Remove the access points from the AppList
appEntry.AccessPoints.Entries.Remove(accessPoints);
appEntry.Timestamp = DateTime.UtcNow;
}
/// <inheritdoc/>
protected override void RepairAppInternal(AppEntry appEntry, Feed feed)
{
#region Sanity checks
if (appEntry == null) throw new ArgumentNullException(nameof(appEntry));
if (feed == null) throw new ArgumentNullException(nameof(feed));
#endregion
var toReAdd = appEntry.AccessPoints?.Entries ?? [];
AddAccessPointsInternal(appEntry, feed, toReAdd.ToList());
WriteAppDir(appEntry);
}
#endregion
#region Finish
/// <inheritdoc/>
protected override void Finish()
{
Log.Debug($"Saving AppList to: {AppListPath}");
// Retry to handle race conditions with read-only access to the file
ExceptionUtils.Retry<IOException>(() => AppList.SaveXml(AppListPath));
if (WindowsUtils.IsWindows)
{
WindowsUtils.NotifyAssocChanged(); // Notify Windows Explorer of changes
WindowsUtils.BroadcastMessage(ChangedWindowMessageID); // Notify Zero Install GUIs of changes
}
}
#endregion
#region AppDir
// ReSharper disable once UnusedParameter.Local
private static void WriteAppDir(AppEntry appEntry)
{
// TODO: Implement
}
// ReSharper disable once UnusedParameter.Local
private static void DeleteAppDir(AppEntry appEntry)
{
// TODO: Implement
}
#endregion
}