-
Notifications
You must be signed in to change notification settings - Fork 0
/
StateExporter.cs
96 lines (90 loc) · 2.83 KB
/
StateExporter.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
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace InputMaster
{
public class StateExporter
{
private readonly string _directory;
private readonly StringBuilder _importLog = new StringBuilder();
public StateExporter(string directory)
{
_directory = directory;
}
public async Task ExportAsync()
{
await Env.App.TriggerSaveAsync();
await Task.WhenAll(Env.StateHandlerFactory.GetExportableStateFiles().Select(ExportAsync));
}
public async Task ImportAsync()
{
await Env.App.TriggerSaveAsync();
try
{
await Task.WhenAll(Env.StateHandlerFactory.GetExportableStateFiles().Select(ImportAsync));
}
finally
{
if (0 < _importLog.Length)
await Helper.ShowSelectableTextAsync("Warning", _importLog);
Env.ShouldRestart = true;
Application.Exit();
}
}
private async Task ExportAsync(StateFile stateFile)
{
if (Path.IsPathRooted(stateFile.File))
{
Env.Notifier.Warning($"Cannot export '{stateFile.File}', only relative paths are allowed.");
return;
}
var sourceFile = Path.Combine(Env.Config.DataDir, stateFile.File);
if (!File.Exists(sourceFile))
{
Env.Notifier.Warning($"Cannot export '{sourceFile}', file not found.");
return;
}
string text;
if (stateFile.Flags.HasFlag(StateHandlerFlags.UseCipher))
{
text = await Env.Cipher.TryDecryptFileAsync(sourceFile);
if (text == null)
{
Env.Notifier.Warning($"Cannot export '{sourceFile}', decryption failed.");
return;
}
}
else
{
text = File.ReadAllText(sourceFile);
}
var targetFile = Path.Combine(_directory, stateFile.File);
Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
File.WriteAllText(targetFile, text);
Env.Notifier.Info($"Created file '{targetFile}'.");
}
private async Task ImportAsync(StateFile stateFile)
{
if (Path.IsPathRooted(stateFile.File))
{
_importLog.AppendLine($"Cannot import to '{stateFile.File}', only relative paths are allowed.");
return;
}
var sourceFile = Path.Combine(_directory, stateFile.File);
if (!File.Exists(sourceFile))
{
_importLog.AppendLine($"Cannot import '{sourceFile}', file not found.");
return;
}
var text = File.ReadAllText(sourceFile);
var targetFile = Path.Combine(Env.Config.DataDir, stateFile.File);
Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
if (stateFile.Flags.HasFlag(StateHandlerFlags.UseCipher))
await Env.Cipher.EncryptToFileAsync(targetFile, text);
else
File.WriteAllText(targetFile, text);
}
}
}