using System; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using MonoTorrent.Client; using MonoTorrent.Common; using Launcher.Code.Helper; namespace Launcher.Code { public static class BackgroundChecks { private static bool running; public const int BUFFER_SIZE = 4096; public static bool MacAllowed() { string mac = DataProvider.Mac; return DataProvider.LauncherServiceClient.MACAllowed(mac); } public static bool NewerVersionAvailable() { DataProvider.GetMaxVersion(); return DataProvider.Version < DataProvider.MaxVersion; } public static TorrentManager GetDownloadForPatch(string s) { if(!NewerVersionAvailable()) return null; Torrent torrent = Torrent.Load(s); var manager = new TorrentManager(torrent, DataProvider.DataFilesFolder, DataProvider.StandartTorrentSettings); manager.TorrentStateChanged += TorrentStateChanged; manager.PieceManager.BlockReceived += TorrentBlockRecieved; return manager; } private static void TorrentBlockRecieved(object sender, BlockEventArgs e) { DataProvider.MainWindowInstance.SaveSetProgress(((TorrentManager) sender).Progress); } public static void SaveTorrentToFile(Stream stream, long version, long length) { string torrentPath = GetTorrentPath(version); if(File.Exists(torrentPath)) return; int copied = 0; byte[] buffer = new byte[BUFFER_SIZE]; using (var output = File.Create(torrentPath)) { while (copied < length) { int readed = stream.Read(buffer, 0, buffer.Length); output.Write(buffer, 0, readed); copied += readed; } output.Close(); } } private static void TorrentStateChanged(object sender, TorrentStateChangedEventArgs e) { Trace.WriteLine("Changed torrent state from " + e.OldState + " to " + e.NewState); if (e.NewState == TorrentState.Stopped) { DataProvider.ClientEngine.Unregister(sender as TorrentManager); } } public static void Start() { StartCheckingFiles(); } public static void Stop() { } private static void StartCheckingFiles() { Task t = new Task(() => Trace.WriteLine("Starting checking files")); t.ContinueWith(CheckFiles); t.Start(); } private static void CheckFiles(Task t) { Trace.WriteLine("Checking files.."); Thread.Sleep(500); t.ContinueWith(CheckFiles); } private static string GetTorrentPath() { StringBuilder builder = new StringBuilder(); builder.Append("Fiesta") .Append("-") .Append(DataProvider.Version) .Append(".torrent"); return Path.Combine(DataProvider.TorrentFilesFolder, builder.ToString()); } public static string GetTorrentPath(long version) { StringBuilder builder = new StringBuilder(); builder.Append("Fiesta") .Append("-") .Append(version) .Append(".torrent"); return Path.Combine(DataProvider.TorrentFilesFolder, builder.ToString()); } public static long DownloadTorrent(out Stream stream) { string config = "Fiesta"; Stream output; var length = DataProvider.PatcherServiceClient.GetTorrentForVersion(ref DataProvider._v, ref config, out output); stream = output; return length; } } }