forked from Macro-Deck-App/Macro-Deck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PluginManager.cs
568 lines (526 loc) · 23.3 KB
/
PluginManager.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
using Newtonsoft.Json.Linq;
using SuchByte.MacroDeck.ExtensionStore;
using SuchByte.MacroDeck.Logging;
using SuchByte.MacroDeck.Model;
using SuchByte.MacroDeck.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace SuchByte.MacroDeck.Plugins
{
public static class PluginManager
{
public static event EventHandler OnPluginsChange;
public static event EventHandler OnUpdateCheckFinished;
public static Dictionary<string, MacroDeckPlugin> Plugins = new Dictionary<string, MacroDeckPlugin>();
public static List<MacroDeckPlugin> ProtectedPlugins = new List<MacroDeckPlugin>();
public static List<MacroDeckPlugin> UpdatedPlugins = new List<MacroDeckPlugin>();
public static Dictionary<string, MacroDeckPlugin> PluginsNotLoaded = new Dictionary<string, MacroDeckPlugin>();
public static List<MacroDeckPlugin> PluginsUpdateAvailable = new List<MacroDeckPlugin>();
public static Dictionary<MacroDeckPlugin, string> PluginDirectories = new Dictionary<MacroDeckPlugin, string>();
static string _manifestFileName = "ExtensionManifest.json";
static string _manifestFileNameLegacy = "Plugin.xml";
static string _deleteMarkerFileName = ".delete";
static bool _loaded = false;
public static void Load()
{
if (_loaded) return;
MacroDeckLogger.Info(typeof(PluginManager), "Loading plugins...");
_loaded = true;
Plugins.Clear();
PluginsUpdateAvailable.Clear();
PluginsNotLoaded.Clear();
ProtectedPlugins.Clear();
PluginDirectories.Clear();
if (!Directory.Exists(MacroDeck.PluginsDirectoryPath))
{
Directory.CreateDirectory(MacroDeck.PluginsDirectoryPath);
}
// Delete the deprecated .loaded directory if it exists
if (Directory.Exists(MacroDeck.PluginsDirectoryPath + ".loaded"))
{
try
{
Directory.Delete(MacroDeck.PluginsDirectoryPath + ".loaded", true);
} catch { }
}
else
{
// Load updates from the .updates directory
if (Directory.Exists(MacroDeck.UpdatePluginsDirectoryPath))
{
foreach (var directory in Directory.GetDirectories(MacroDeck.UpdatePluginsDirectoryPath))
{
try
{
var destinationDirectory = Path.Combine(MacroDeck.PluginsDirectoryPath, new DirectoryInfo(directory).Name);
DirectoryCopy.Copy(directory, destinationDirectory, true);
Directory.Delete(directory, true);
} catch { }
}
try
{
Directory.Delete(MacroDeck.UpdatePluginsDirectoryPath, true);
} catch { }
}
// Load the plugins
foreach (var directory in Directory.GetDirectories(MacroDeck.PluginsDirectoryPath))
{
// Delete plugin if file ".delete" exists
if (File.Exists(Path.Combine(directory, _deleteMarkerFileName)))
{
try
{
File.Delete(Path.Combine(directory, _deleteMarkerFileName));
Directory.Delete(directory, true);
} catch { }
continue;
}
var manifestFile = Path.Combine(directory, _manifestFileName);
var manifestFileLegacy = Path.Combine(directory, _manifestFileNameLegacy);
if (!File.Exists(manifestFile) && !File.Exists(manifestFileLegacy))
{
continue;
}
if (File.Exists(manifestFile))
{
try
{
ExtensionManifestModel extensionManifest = ExtensionManifestModel.FromManifestFile(manifestFile);
if (extensionManifest == null) continue;
var plugin = LoadPlugin(extensionManifest, directory);
plugin.Author = extensionManifest.Author;
}
catch (Exception ex)
{
MacroDeckLogger.Error(typeof(PluginManager), $"Error while deserializing manifest for {directory}: {ex.Message}");
}
} else if (File.Exists(manifestFileLegacy))
{
try
{
PluginManifest pluginManifest = PluginManifest.FromManifestFile(manifestFileLegacy);
if (pluginManifest == null) continue;
var plugin = LoadLegacyPlugin(pluginManifest, directory);
plugin.Author = pluginManifest.Author;
}
catch (Exception ex)
{
MacroDeckLogger.Error(typeof(PluginManager), $"Error while deserializing legacy manifest for {directory}: {ex.Message}");
}
}
}
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
// Add internal plugins
AddPlugin(new ActionButton.ActionButtonPlugin(), true);
AddPlugin(new Variables.Plugin.VariablesPlugin(), true);
AddPlugin(new Folders.Plugin.FolderPlugin(), true);
}
private static MacroDeckPlugin LoadPlugin(ExtensionManifestModel extensionManifest, string pluginDirectory, bool enable = false)
{
Assembly asm = null;
try
{
asm = Assembly.LoadFrom(Path.Combine(pluginDirectory, extensionManifest.Dll));
MacroDeckLogger.Info("Loading plugin " + asm.GetName().Name);
foreach (var type in asm.GetTypes())
{
try
{
if (type.IsClass && type.IsSubclassOf(typeof(MacroDeckPlugin)))
{
var plugin = Activator.CreateInstance(type) as MacroDeckPlugin;
AddPlugin(plugin);
PluginDirectories[plugin] = pluginDirectory;
Task.Run(() =>
SearchUpdate(plugin)
);
if (File.Exists(Path.Combine(pluginDirectory, "ExtensionIcon.png")))
{
plugin.PluginIcon = (Image)Image.FromFile(Path.Combine(pluginDirectory, "ExtensionIcon.png")).Clone();
}
plugin.Author = extensionManifest.Author;
if (enable) plugin.Enable();
return plugin;
}
}
catch (Exception ex)
{
MacroDeckLogger.Error("Error while loading plugin: " + ex.Message);
}
}
}
catch (Exception ex)
{
MacroDeckLogger.Error("Error while loading plugin: " + ex.Message);
if (asm != null)
{
var disabledPlugin = new DisabledPlugin
{
Name = asm.GetName().Name,
Version = FileVersionInfo.GetVersionInfo(asm.Location).ProductVersion,
Author = extensionManifest.Author,
};
PluginsNotLoaded[disabledPlugin.Name] = disabledPlugin;
PluginDirectories[disabledPlugin] = pluginDirectory;
MacroDeck.SafeMode = true;
using (var msgBox = new GUI.CustomControls.MessageBox())
{
msgBox.ShowDialog(Language.LanguageManager.Strings.ErrorWhileLoadingPlugins, String.Format(Language.LanguageManager.Strings.PluginXCouldNotBeLoaded, disabledPlugin.Name, disabledPlugin.Version), MessageBoxButtons.OK);
}
return disabledPlugin;
}
}
return null;
}
[Obsolete("Will be removed in version 2.11.0")]
private static MacroDeckPlugin LoadLegacyPlugin(PluginManifest pluginManifest, string pluginDirectory, bool enable = false)
{
Assembly asm = null;
try
{
asm = Assembly.LoadFrom(Path.Combine(pluginDirectory, pluginManifest.MainFile));
MacroDeckLogger.Info("Loading legacy plugin " + asm.GetName().Name);
foreach (var type in asm.GetTypes())
{
try
{
if (type.IsClass && type.IsSubclassOf(typeof(MacroDeckPlugin)))
{
var plugin = Activator.CreateInstance(type) as MacroDeckPlugin;
AddPlugin(plugin);
PluginDirectories[plugin] = pluginDirectory;
Task.Run(() =>
SearchUpdate(plugin)
);
plugin.Author = pluginManifest.Author;
if (enable) plugin.Enable();
return plugin;
}
}
catch (Exception ex)
{
MacroDeckLogger.Error("Error while loading legacy plugin: " + ex.Message);
}
}
}
catch (Exception ex)
{
MacroDeckLogger.Error("Error while loading legacy plugin: " + ex.Message);
if (asm != null)
{
var disabledPlugin = new DisabledPlugin
{
Name = asm.GetName().Name,
Version = FileVersionInfo.GetVersionInfo(asm.Location).ProductVersion,
Author = pluginManifest.Author,
};
PluginsNotLoaded[disabledPlugin.Name] = disabledPlugin;
PluginDirectories[disabledPlugin] = pluginDirectory;
MacroDeck.SafeMode = true;
using (var msgBox = new GUI.CustomControls.MessageBox())
{
msgBox.ShowDialog(Language.LanguageManager.Strings.ErrorWhileLoadingPlugins, String.Format(Language.LanguageManager.Strings.PluginXCouldNotBeLoaded, disabledPlugin.Name, disabledPlugin.Version), MessageBoxButtons.OK);
}
return disabledPlugin;
}
}
return null;
}
public static void ScanUpdatesAsync()
{
PluginsUpdateAvailable.Clear();
Task.Run(() =>
{
foreach (MacroDeckPlugin plugin in Plugins.Values)
{
SearchUpdate(plugin);
}
foreach (MacroDeckPlugin plugin in PluginsNotLoaded.Values)
{
SearchUpdate(plugin);
}
if (OnUpdateCheckFinished != null)
{
OnUpdateCheckFinished(null, EventArgs.Empty);
}
});
}
internal static void SearchUpdate(MacroDeckPlugin plugin)
{
if (UpdatedPlugins.Contains(plugin) || ProtectedPlugins.Contains(plugin)) return;
try
{
using (WebClient wc = new WebClient())
{
var jsonString = wc.DownloadString($"https://macrodeck.org/extensionstore/extensionstore.php?action=check-update&package-id={ExtensionStoreHelper.GetPackageId(plugin)}&installed-version={plugin.Version}&target-api={MacroDeck.PluginApiVersion}");
JObject jsonObject = JObject.Parse(jsonString);
bool update = (bool)jsonObject["update-available"];
if (update)
{
MacroDeckLogger.Info("Update available for " + plugin.Name);
PluginsUpdateAvailable.Add(plugin);
}
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
public static bool IsInstalled(string name)
{
return Plugins.ContainsKey(name);
}
public static void DeletePlugin(string name)
{
if (!Plugins.ContainsKey(name)) return;
MacroDeckPlugin plugin = null;
if (Plugins.ContainsKey(name))
{
plugin = Plugins[name];
} else if (PluginsNotLoaded.ContainsKey(name))
{
plugin = PluginsNotLoaded[name];
}
if (plugin == null) return;
if (ProtectedPlugins.Contains(plugin)) return;
if (PluginDirectories.ContainsKey(plugin))
{
try
{
if (UpdatedPlugins.Contains(plugin))
{
UpdatedPlugins.Remove(plugin);
}
if (PluginsNotLoaded.ContainsKey(name))
{
PluginsNotLoaded.Remove(name);
}
if (PluginsUpdateAvailable.Contains(plugin))
{
PluginsUpdateAvailable.Remove(plugin);
}
if (Plugins.ContainsKey(name))
{
Plugins.Remove(name);
}
var deleteMarkerFile = Path.Combine(PluginDirectories[plugin], _deleteMarkerFileName);
File.Create(deleteMarkerFile);
MacroDeckLogger.Info(name + " deleted");
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message.ToString());
}
}
if (OnPluginsChange != null)
{
OnPluginsChange(name, EventArgs.Empty);
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
internal static void InstallPluginFromZip(string zipFilePath)
{
var extensionManifest = ExtensionManifestModel.FromZipFilePath(zipFilePath);
var extractedDirectory = Path.Combine(MacroDeck.TempDirectoryPath, extensionManifest.PackageId);
ZipFile.ExtractToDirectory(Path.Combine(MacroDeck.TempDirectoryPath, zipFilePath), extractedDirectory, true);
InstallPlugin(extractedDirectory, extensionManifest.PackageId);
}
internal static void InstallPlugin(string directory, string packageName)
{
bool update = Directory.Exists(Path.Combine(MacroDeck.PluginsDirectoryPath, packageName));
MacroDeckLogger.Info(typeof(PluginManager), $"{(update ? "Updating" : "Installing")} " + packageName);
Assembly asm = null;
bool error = false;
ExtensionManifestModel extensionManifest = new ExtensionManifestModel();
try
{
var installationDirectory = Path.Combine(MacroDeck.PluginsDirectoryPath, packageName);
if (update)
{
installationDirectory = Path.Combine(MacroDeck.UpdatePluginsDirectoryPath, packageName);
}
DirectoryCopy.Copy(directory, installationDirectory, true);
if (!update)
{
var manifestFile = Path.Combine(installationDirectory, _manifestFileName);
if (!File.Exists(manifestFile))
{
error = true;
}
else
{
try
{
extensionManifest = ExtensionManifestModel.FromManifestFile(manifestFile);
if (extensionManifest == null)
{
error = true;
}
else
{
try
{
using (WebClient wc = new WebClient())
{
wc.DownloadString($"https://macrodeck.org/extensionstore/extensionstore.php?action=count-download&package-id={extensionManifest.PackageId}");
}
} catch { }
var plugin = LoadPlugin(extensionManifest, installationDirectory, true);
if (plugin != null && plugin.CanConfigure)
{
using (var msgBox = new GUI.CustomControls.MessageBox())
{
if (msgBox.ShowDialog(Language.LanguageManager.Strings.PluginNeedsConfiguration, String.Format(Language.LanguageManager.Strings.ConfigureNow, plugin.Name), MessageBoxButtons.YesNo) == DialogResult.Yes)
{
plugin.OpenConfigurator();
}
}
}
}
}
catch
{
error = true;
}
}
}
else
{
UpdatedPlugins.Add(PluginDirectories.FirstOrDefault(x => x.Value == Path.Combine(MacroDeck.PluginsDirectoryPath, packageName)).Key);
}
if (OnPluginsChange != null)
{
OnPluginsChange(null, EventArgs.Empty);
}
} catch
{
error = true;
}
if (error)
{
if (asm != null && extensionManifest != null)
{
var disabledPlugin = new DisabledPlugin
{
Name = asm.GetName().Name,
Version = asm.GetName().Version.ToString(),
Author = extensionManifest.Author,
};
PluginsNotLoaded[asm.GetName().Name] = disabledPlugin;
using (var msgBox = new GUI.CustomControls.MessageBox())
{
msgBox.ShowDialog(Language.LanguageManager.Strings.ErrorWhileInstallingPlugin, String.Format(Language.LanguageManager.Strings.PluginXCouldNotBeInstalled, asm.GetName().Name), MessageBoxButtons.OK);
}
}
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
/// <summary>
/// Adds the plugin to the plugin list
/// </summary>
/// <param name="macroDeckPlugin">Instance of the plugin</param>
/// <param name="protect">true = plugin cannot be uninstalled by the user</param>
internal static void AddPlugin(MacroDeckPlugin macroDeckPlugin, bool protect = false)
{
if (!Plugins.ContainsKey(macroDeckPlugin.Name))
{
Plugins[macroDeckPlugin.Name] = macroDeckPlugin;
if (protect)
{
ProtectedPlugins.Add(macroDeckPlugin);
}
}
if (OnPluginsChange != null)
{
OnPluginsChange(macroDeckPlugin, EventArgs.Empty);
}
}
internal static void EnablePlugins()
{
MacroDeckLogger.Info(typeof(PluginManager), "Enabling plugins...");
foreach (MacroDeckPlugin plugin in Plugins.Values)
{
if (plugin == null) continue;
long enalingStarted = DateTimeOffset.Now.ToUnixTimeMilliseconds();
plugin.Enable();
long enablingTook = DateTimeOffset.Now.ToUnixTimeMilliseconds() - enalingStarted;
MacroDeckLogger.Info($"{plugin.Name} version {plugin.Version} enabled (took {enablingTook}ms)");
}
MacroDeckLogger.Info(typeof(PluginManager), $"Plugins enabled");
}
public static PluginAction GetActionByName(MacroDeckPlugin plugin, string name)
{
PluginAction action = plugin.Actions.Find(plugin => plugin.Name.Equals(name));
if (action == null) return null;
using (var ms = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(action.GetType());
serializer.Serialize(ms, action);
ms.Seek(0, SeekOrigin.Begin);
return (PluginAction)serializer.Deserialize(ms);
}
}
public static PluginAction GetNewActionInstance(PluginAction action)
{
if (action == null) return null;
using (var ms = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(action.GetType());
serializer.Serialize(ms, action);
ms.Seek(0, SeekOrigin.Begin);
return (PluginAction)serializer.Deserialize(ms);
}
}
public static MacroDeckPlugin GetPluginByAction(PluginAction pluginAction)
{
foreach (MacroDeckPlugin macroDeckPlugin in Plugins.Values)
{
if (macroDeckPlugin.Actions.Find(mdp => mdp.GetType().FullName.Equals(pluginAction.GetType().FullName)) != null)
{
return macroDeckPlugin;
}
}
return new DisabledPlugin()
{
Name = "Plugin not available",
};
}
public static MacroDeckPlugin GetPluginByName(string name)
{
foreach (MacroDeckPlugin macroDeckPlugin in Plugins.Values)
{
if (macroDeckPlugin.Name.Equals(name))
{
return macroDeckPlugin;
}
}
return new DisabledPlugin()
{
Name = "Plugin not available",
};
}
}
}