Skip to content

Commit

Permalink
-> Mods are downloaded correctly with subfolders
Browse files Browse the repository at this point in the history
• Need to see why FileWatcher isn't updating list
  • Loading branch information
jaywha committed Mar 5, 2020
1 parent 90e474b commit 713c03a
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 35 deletions.
5 changes: 5 additions & 0 deletions MCModGetter/Classes/Mod.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace MCModGetter.Classes
{
Expand All @@ -15,5 +18,7 @@ public class Mod
public string Version { get; set; }
public bool IsClientSide { get; set; }
public bool IsOnLocalMachine { get; set; }

public ImageSource ListViewIcon { get; set; } = new BitmapImage(new Uri("Images/file.png", UriKind.Relative));
}
}
9 changes: 5 additions & 4 deletions MCModGetter/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,8 @@
Width="20"
Height="20"
Stretch="Fill"
Source="Images/file.png"/>
<TextBlock Text="{Binding}" Margin="5,0" />
Source="{Binding ListViewIcon}"/>
<TextBlock Text="{Binding Name}" Margin="5,0" />
</StackPanel>
</DataTemplate>
</Setter.Value>
Expand Down Expand Up @@ -154,8 +154,9 @@
</StackPanel>
<Button x:Name="btnUpdateMods" Content="Update Current Mods" HorizontalAlignment="Left" Margin="10,0,0,10" VerticalAlignment="Bottom" Width="201" Foreground="AntiqueWhite" Click="btnUpdateMods_Click" IsEnabled="True"/>
<StackPanel x:Name="stkProgress" Height="128" HorizontalAlignment="Center" VerticalAlignment="Center" Width="128" Visibility="Hidden">
<ProgressBar x:Name="progbarUpdateMods" Style="{StaticResource MaterialDesignCircularProgressBar}" IsIndeterminate="True" Visibility="Hidden"/>
<TextBlock x:Name="txtProgressStatus" Text="{Binding ElementName=wndMain, Path=FTPDownloadProgress}"/>
<ProgressBar x:Name="progbarUpdateMods" Width="64" Height="64" Style="{StaticResource MaterialDesignCircularProgressBar}" IsIndeterminate="True"/>
<TextBlock x:Name="txtProgressStatus" Text="{Binding ElementName=wndMain, Path=FTPDownloadProgress, StringFormat={}{0:#0}%, FallbackValue={}69%}"
HorizontalAlignment="Center"/>
</StackPanel>
<Image x:Name="imgUserSkin" HorizontalAlignment="Left" Height="128" Margin="10,166,0,0" VerticalAlignment="Top" Width="128"
Visibility="Collapsed"/>
Expand Down
85 changes: 54 additions & 31 deletions MCModGetter/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
using MCModGetter.Classes;
using System.Threading;
using System.Net;
using System.Windows.Media.Imaging;

namespace MCModGetter
{
Expand All @@ -35,9 +36,12 @@ private void OnPropertyChanged([CallerMemberName] string propName = "")

#region Properties
private FileSystemWatcher fileSystemWatcher;
public ObservableCollection<string> CurrentModList { get; private set; } = new ObservableCollection<string>();
public ObservableCollection<Mod> CurrentModList { get; private set; } = new ObservableCollection<Mod>();

private const string BaseURL = "ftp://144.217.65.175/mods/";

private string _modFileLocation = $@"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\.minecraft\mods\";

public string ModFileLocation
{
get => _modFileLocation;
Expand All @@ -60,7 +64,7 @@ public double FTPDownloadProgress

private NetworkCredential VoodooCredential = new NetworkCredential("[email protected]", "pt2T0gy68E");


private StreamWriter CurrentLog;
private string LogDirectory = $@"{Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)}\MCModGetter-Logs\";

private AuthenticateResponse UserAuthCache;
Expand All @@ -75,6 +79,8 @@ public MainWindow()
Hide();
Show();

Directory.CreateDirectory(ModFileLocation); // ensure mod folder exists

fileSystemWatcher = new FileSystemWatcher(ModFileLocation, "*.*")
{
EnableRaisingEvents = true,
Expand All @@ -86,9 +92,14 @@ public MainWindow()
fileSystemWatcher.Renamed += FileSystemWatcher_FileEvent;
fileSystemWatcher.Deleted += FileSystemWatcher_FileEvent;

foreach (string dirName in Directory.EnumerateDirectories(ModFileLocation).Select(d => d.Substring(d.LastIndexOf('\\') + 1)))
{
CurrentModList.Add(new Mod() { Name = dirName, ListViewIcon = new BitmapImage(new Uri("Images/folder-icon.png", UriKind.Relative)) });
}

foreach (string fileName in Directory.EnumerateFiles(ModFileLocation).Select((s) => s.Substring(s.LastIndexOf('\\') + 1)))
{
CurrentModList.Add(fileName);
CurrentModList.Add(new Mod() { Name = fileName });
}

Directory.CreateDirectory(LogDirectory);
Expand Down Expand Up @@ -122,9 +133,13 @@ private void FileSystemWatcher_FileEvent(object sender, FileSystemEventArgs e)
tvMods.Dispatcher.Invoke(() =>
{
CurrentModList.Clear();
foreach (string fileName in Directory.EnumerateFiles(ModFileLocation).Select((s) => s.Substring(s.LastIndexOf('\\') + 1)))
foreach (string dirName in Directory.EnumerateDirectories(ModFileLocation).Select(d => d.Substring(d.LastIndexOf('\\') + 1))) {
CurrentModList.Add(new Mod() { Name = dirName, ListViewIcon = new BitmapImage(new Uri("Images/folder-icon.png", UriKind.Relative)) });
}

foreach (string fileName in Directory.EnumerateFiles(ModFileLocation).Select(s => s.Substring(s.LastIndexOf('\\') + 1)))
{
CurrentModList.Add(fileName);
CurrentModList.Add(new Mod() { Name = fileName });
}
}, System.Windows.Threading.DispatcherPriority.Background);
});
Expand All @@ -137,7 +152,7 @@ private void tvMods_Drop(object sender, DragEventArgs e)
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (var f in files)
{
CurrentModList.Add(f.Substring(f.LastIndexOf('\\') + 1));
CurrentModList.Add(new Mod() { Name = f.Substring(f.LastIndexOf('\\') + 1) });
File.Copy(f, ModFileLocation + f.Substring(f.LastIndexOf('\\') + 1));
}
}
Expand Down Expand Up @@ -205,13 +220,15 @@ private void BtnDeleteMod_Click(object sender, RoutedEventArgs e)
Toast.MessageQueue.Enqueue($"Successfully deleted the following mod: {modName}");
}



private async void btnUpdateMods_Click(object sender, RoutedEventArgs e)
{
btnUpdateMods.IsEnabled = false;
stkProgress.Visibility = Visibility.Visible;
FTPDownloadProgress = 0.0;
Directory.Delete(ModFileLocation.Substring(0, ModFileLocation.Length-1), true);
Directory.CreateDirectory(ModFileLocation);

CurrentLog = File.AppendText(LogDirectory + $"UpdateMods_{DateTime.Now:MM-dd-yyyy hhmmss}");
await Task.Factory.StartNew(() => ProbeFiles());
}

Expand All @@ -232,26 +249,25 @@ private void BtnAddMod_Click(object sender, RoutedEventArgs e)

foreach (string file in ofd.FileNames)
{
CurrentModList.Add(file.Substring(file.LastIndexOf('\\') + 1));
CurrentModList.Add(new Mod() { Name = file.Substring(file.LastIndexOf('\\') + 1) });
File.Copy(file, ModFileLocation + file.Substring(file.LastIndexOf('\\') + 1));
}
}
#endregion

#region Utilitiy Methods

public void ProbeFiles(string startingDir = "")
public void ProbeFiles(string innerPath = "")
{
if (string.IsNullOrWhiteSpace(startingDir))
startingDir = "ftp://144.217.65.175/mods/";
string currentURL = BaseURL + innerPath;

try
{
// Enumerate files and directories to download
List<string> Files = new List<string>();

// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(startingDir);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(currentURL);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

// This example assumes the FTP site uses anonymous logon.
Expand All @@ -278,43 +294,39 @@ public void ProbeFiles(string startingDir = "")
var filesDownloaded = 0;
foreach (var file in Files)
{
string localFilePath = ModFileLocation + file;
string remoteFilePath = startingDir + file;
string localFilePath = ModFileLocation + innerPath + file;
string remoteFilePath = currentURL + file;

if (!CurrentModList.Contains(file))
if (!CurrentModList.Where(mod=>!mod.Name.Equals(file)).Any())
{
if (file.StartsWith("DIR"))
{
try {
ProbeFiles(startingDir+file.Substring(3)+"/");
ProbeFiles(innerPath+file.Substring(3)+"/");
} catch(Exception e) {
// Print error (but continue with other files)
Toast.Dispatcher.Invoke(() =>
Toast.MessageQueue.Enqueue($"Error enumerating folder {file}!"));
CurrentLog.WriteLine($"Error enumerating folder {file}!");
}
}
else
{
Toast.Dispatcher.Invoke(() =>
Toast.MessageQueue.Enqueue($"Downloading file {file}..."));
CurrentLog.WriteLine($"Downloading file {file}...");
// Download file
DownloadMod(remoteFilePath, localFilePath);

// Did the download succeeded?
if (!File.Exists(localFilePath))
{
// Print error (but continue with other files)
Toast.Dispatcher.Invoke(() =>
Toast.MessageQueue.Enqueue($"Error downloading file {file}!"));
CurrentLog.WriteLine($"Error downloading file {file}!");
}
}
}

FTPDownloadProgress = filesDownloaded++ / (double) Files.Count();
FTPDownloadProgress = (filesDownloaded++ / (double) Files.Count()) * 100;
}

Toast.Dispatcher.Invoke(() =>
Toast.MessageQueue.Enqueue("All mods up to date!"));
CurrentLog.WriteLine("All mods up to date!");
}
catch (Exception e)
{
Expand All @@ -323,16 +335,27 @@ public void ProbeFiles(string startingDir = "")
}
finally
{
wndMain.Dispatcher.Invoke(() =>
if (string.IsNullOrWhiteSpace(innerPath))
{
btnUpdateMods.IsEnabled = true;
progbarUpdateMods.Visibility = Visibility.Hidden;
});
wndMain.Dispatcher.Invoke(() =>
{
btnUpdateMods.IsEnabled = true;
stkProgress.Visibility = Visibility.Hidden;
tvMods.InvalidateArrange();
});
}
}
}

private void DownloadMod(string remoteURL, string localFilePath)
{
var trueLocal = localFilePath.Replace('/', '\\');
var dirPath = trueLocal.Substring(0, trueLocal.LastIndexOf('\\')+1);
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}

// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(remoteURL);
request.Method = WebRequestMethods.Ftp.DownloadFile;
Expand All @@ -348,7 +371,7 @@ private void DownloadMod(string remoteURL, string localFilePath)
}
}

private async void DialogHost_DialogClosing(object sender, MaterialDesignThemes.Wpf.DialogClosingEventArgs eventArgs)
private async void DialogHost_DialogClosing(object sender, DialogClosingEventArgs eventArgs)
{
if (eventArgs.Parameter != null && eventArgs.Parameter.ToString().Equals("LOGIN"))
{
Expand Down

0 comments on commit 713c03a

Please sign in to comment.