forked from TeamShinkansen/Hakchi2-CE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGameImporterForm.cs
270 lines (237 loc) · 11.7 KB
/
GameImporterForm.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
using ArxOne.Ftp;
using com.clusterrr.clovershell;
using com.clusterrr.hakchi_gui.Properties;
using com.clusterrr.hakchi_gui.Tasks;
using com.clusterrr.util;
using SharpCompress.Archives;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using static com.clusterrr.hakchi_gui.Tasks.Tasker;
namespace com.clusterrr.hakchi_gui
{
public partial class GameImporterForm : Form
{
public bool gameCopied = false;
public IEnumerable<FoundGame> SelectedGames => listViewGames.SelectedItems.Cast<ListViewItem>().Where(item => item.Tag is FoundGame).Select(item => item.Tag as FoundGame);
public static string NoSelection => Resources.NoItemsSelected;
public static string SingleSelection => Resources._0ItemSelected1;
public static string MultiSelection => Resources._0ItemsSelected1;
public class FoundGame
{
public string RemotePath;
public DesktopFile Desktop;
public long Size;
}
public GameImporterForm()
{
InitializeComponent();
labelStatus.Text = NoSelection;
}
public GameImporterForm(List<FoundGame> games): this()
{
foreach (var game in games.OrderBy(e => e.Desktop.Name))
{
var item = new ListViewItem();
listViewGames.Items.Add(new ListViewItem(new ListViewItem.ListViewSubItem[] {
new ListViewItem.ListViewSubItem() { Text = game.Desktop.Name },
new ListViewItem.ListViewSubItem() { Text = game.RemotePath },
new ListViewItem.ListViewSubItem() { Text = Shared.SizeSuffix(game.Size, 2) },
}, 0)
{
Tag = game
});
}
}
public static TaskFunc FindGamesTask(Dictionary<String, FoundGame> foundGames)
{
return (Tasker tasker, Object taskObject) =>
{
tasker.SetStatus(Resources.Scanning);
if (hakchi.Shell.IsOnline)
{
var mountpoint = hakchi.Shell is ClovershellConnection ? "" : hakchi.Shell.ExecuteSimple("hakchi get mountpoint", throwOnNonZero: true);
var rootfs = hakchi.Shell is ClovershellConnection ? "/var/lib/hakchi/rootfs" : hakchi.Shell.ExecuteSimple("hakchi get rootfs", throwOnNonZero: true);
var searchPaths = new string[]
{
$"{rootfs}/usr/share/games",
$"{mountpoint}/var/lib/hakchi/games",
$"{mountpoint}/media/hakchi/games"
};
using (var desktopTarStream = new MemoryStream())
using (var sizeStream = new MemoryStream())
{
var paths = "";
foreach (var path in searchPaths)
{
paths = $"{paths} {Shared.EscapeShellArgument(path)}";
}
hakchi.Shell.Execute($"find {paths} -name \"CLV-*.desktop\" | sort | tar -cf - -T -", null, desktopTarStream);
desktopTarStream.Seek(0, SeekOrigin.Begin);
var sizeRegex = new Regex(@"^(\d+)\s*(/.*)$", RegexOptions.Multiline);
if (desktopTarStream.Length > 0)
{
hakchi.Shell.Execute($"du {paths}", null, sizeStream);
sizeStream.Seek(0, SeekOrigin.Begin);
using (var extractor = ArchiveFactory.Open(desktopTarStream))
using (var reader = extractor.ExtractAllEntries())
{
while (reader.MoveToNextEntry())
{
var entry = reader.Entry;
Trace.WriteLine(entry.Key);
using (var entryStream = reader.OpenEntryStream())
{
var key = Path.GetDirectoryName($"/{entry.Key}").Replace('\\', '/');
var desktop = new DesktopFile(entryStream);
if (desktop.IconPath.EndsWith("/.storage"))
{
// This is a linked game
key = $"{mountpoint}{desktop.IconPath}/{desktop.Code}";
}
desktop.Exec = desktop.Exec.Replace(desktop.IconPath, "/var/games");
desktop.IconPath = "/var/games";
desktop.ProfilePath = "/var/saves";
if (!NesApplication.AllDefaultGames.ContainsKey(desktop.Code) && desktop.Bin != "/bin/chmenu")
{
foundGames.Add(key, new FoundGame()
{
RemotePath = key,
Desktop = desktop,
Size = 0
});
}
}
}
}
using (var sr = new StreamReader(sizeStream))
{
var matches = sizeRegex.Matches(sr.ReadToEnd());
foreach (Match match in matches)
{
var size = long.Parse(match.Groups[1].Value) * 1024;
var path = match.Groups[2].Value;
if (foundGames.ContainsKey(path))
{
foundGames[path].Size = size;
}
}
}
}
}
return Conclusion.Success;
}
return Conclusion.Error;
};
}
private void tableLayoutPanelButtons_Paint(object sender, PaintEventArgs e)
{
var pen = new Pen(SystemColors.ControlLight);
e.Graphics.DrawLine(pen, 0, 0, tableLayoutPanelButtons.Width, 0);
}
private void listViewGames_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
var totalSize = SelectedGames
.Select(game => game.Size)
.Sum();
if (listViewGames.SelectedItems.Count == 0)
{
labelStatus.Text = NoSelection;
}
else
{
labelStatus.Text = string.Format(listViewGames.SelectedItems.Count == 1 ? SingleSelection : MultiSelection, listViewGames.SelectedItems.Count, Shared.SizeSuffix(totalSize));
}
buttonImport.Enabled = listViewGames.SelectedItems.Count > 0;
}
public static TaskFunc GameCopyTask(FoundGame game)
{
return (Tasker tasker, Object sync) =>
{
if (game.Desktop.Code.StartsWith("CLV-"))
{
long dataTransferred = 0;
var destinationPath = Path.Combine(NesApplication.GamesDirectory, game.Desktop.Code);
tasker?.SetStatus($"{game.Desktop.Name}");
if (Directory.Exists(destinationPath))
{
Directory.Delete(destinationPath, true);
}
Directory.CreateDirectory(destinationPath);
foreach (var folder in hakchi.Shell.ExecuteSimple($"cd {Shared.EscapeShellArgument(game.RemotePath)}; find -type d").Split('\n'))
{
Directory.CreateDirectory(Path.Combine(destinationPath, folder));
}
FtpClient ftp = null;
if (hakchi.Shell is INetworkShell)
{
ftp = new FtpClient(new Uri($"ftp://{(hakchi.Shell as INetworkShell).IPAddress}"), new NetworkCredential("root", "root"));
}
foreach (Match match in new Regex(@"^(\d+)\s*\./(.*)$", RegexOptions.Multiline).Matches(hakchi.Shell.ExecuteSimple($"cd {Shared.EscapeShellArgument(game.RemotePath)}; find -type f -exec du {"{}"} \\;")))
{
var size = long.Parse(match.Groups[1].Value) * 1024;
var filename = match.Groups[2].Value;
using (var file = File.Create(Path.Combine(destinationPath, filename)))
using (var tracker = new TrackableStream(file))
{
tracker.OnProgress += (long transferred, long length) =>
{
var totalTransferred = Math.Min(dataTransferred + transferred, game.Size);
tasker?.SetProgress(totalTransferred, game.Size);
tasker?.SetStatus($"{game.Desktop.Name} ({Shared.SizeSuffix(totalTransferred, 2)} / {Shared.SizeSuffix(game.Size, 2)})");
};
if (hakchi.Shell is INetworkShell)
{
using (var ftpStream = ftp.Retr($"{game.RemotePath}/{filename}"))
{
ftpStream.CopyTo(tracker);
}
}
else
{
hakchi.Shell.Execute($"cat {Shared.EscapeShellArgument($"{game.RemotePath}/{filename}")}", null, tracker, throwOnNonZero: true);
}
dataTransferred += size;
}
}
ftp?.Dispose();
ftp = null;
game.Desktop.Save(Path.Combine(destinationPath, $"{game.Desktop.Code}.desktop"));
if (!ConfigIni.Instance.SelectedGames.Contains(game.Desktop.Code))
{
ConfigIni.Instance.SelectedGames.Add(game.Desktop.Code);
}
return Conclusion.Success;
}
return Conclusion.Error;
};
}
private void buttonImport_Click(object sender, EventArgs e)
{
if (listViewGames.SelectedItems.Count > 0)
{
gameCopied = true;
using (var tasker = new Tasks.Tasker(this))
{
tasker.AttachView(new TaskerTaskbar());
tasker.AttachView(new TaskerForm());
tasker.SetTitle(Resources.CopyingGames);
if (hakchi.Shell.IsOnline)
{
foreach (var game in SelectedGames)
{
tasker.AddTask(GameCopyTask(game));
}
}
tasker.Start();
}
}
}
}
}