private string GetArgumentsForDemo(LocalDemo localDemo) { if (localDemo.Mod == null) { return(string.Format("+seta thereisacow 1337 +seta sv_cheats 1 +devmap {1} +killserver +demo \"{0}\"", localDemo.Name, localDemo.Map)); } return (string.Format( "+seta thereisacow 1337 +seta sv_cheats 1 +set fs_game {3}{0} +devmap {2} +killserver +demo \"{1}\"", localDemo.Mod, localDemo.Name, localDemo.Map, localDemo.Version == GameVersion.CallOfDuty2 ? string.Empty : "mods/")); }
private async Task <RemoteDemo> Upload(LocalDemo demo) { if (demo == null) { throw new ArgumentNullException(nameof(demo)); } ToggleControls(false); statusLabel.Text = $"Uploading demo {demo.Name}..."; try { var newDemo = await Factory.RemoteDemoRepository.Store(demo, p => { statusStrip1.Invoke((MethodInvoker)(() => { if (p < 0) { p = 0; } progressBar.Value = p; })); }); await ReloadRepositories(); remoteRepositoryView.SelectedDemo = newDemo; remoteRepositoryView.Focus(); ResetStatus(); return(newDemo as RemoteDemo); } catch (Exception exception) { LogHelper.Instance.LogException("Failed to upload demo", exception); var deepsetException = exception.GetDeepestException(); MessageBox.Show(this, $"Failed to upload demo.\n{(deepsetException == null ? "An unknown error occured" : deepsetException.Message)}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); ResetStatus(); return(null); } }
public Process Start(LocalDemo localDemo) { if (localDemo == null) { throw new ArgumentNullException(nameof(localDemo)); } var game = localDemo.Version.GetGame(); var info = new ProcessStartInfo(game.GetMultiplayerExecutable(), GetArgumentsForDemo(localDemo)) { WorkingDirectory = game.InstallPath }; return(Process.Start(info)); }
private async Task Play(LocalDemo demo) { if (demo == null) { throw new ArgumentNullException(nameof(demo)); } var game = demo.Version.GetGame(); // Check whether the game is (still) installed. if (game == null) { LogHelper.Instance.LogException("You need to install {0} in order to play this demo.", demo.Version.GetFullName()); // Should never happen as the demo is in the local repository (in the game path). MessageBox.Show(this, $"You need to install {demo.Version.GetFullName()} in order to play this demo.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Check whether the game is already running. if (game.IsRunning) { LogHelper.Instance.LogException( "{0} is already running.\nYou need to close it in order to play this demo.", demo.Version.GetFullName()); MessageBox.Show(this, $"{demo.Version.GetFullName()} is already running.\nYou need to close it in order to play this demo.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Check whether the demo file still exists. if (!demo.IsValid) { LogHelper.Instance.LogException("This demo file is corrupted or no longer exists."); MessageBox.Show(this, "This demo file is corrupted or no longer exists.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); await ReloadRepositories(); return; } // Check for missing files. var missingFiles = game.GetMissingFiles(demo).ToList(); if (missingFiles.Any()) { var fileCount = missingFiles.Count(); if ( MessageBox.Show(this, $"You need to download {fileCount} missing files in order to play this demo:\n{string.Join("\n", missingFiles)}\n\nDo you want to download these now?", "Missing Files", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { ToggleControls(false); var processed = 0; foreach (var missingFile in missingFiles) { var url = missingFile.Item1; var path = missingFile.Item2; statusLabel.Text = $"Downloading {Path.GetFileName(path)}..."; // Create the directory if it doesn't exist already. if (!Directory.Exists(Path.GetDirectoryName(path))) { Directory.CreateDirectory(Path.GetDirectoryName(path) ?? throw new InvalidOperationException()); } try { // Download the file. var processed1 = processed; await RedirectHelper.DownloadFile(url, path, (sender, args) => { progressBar.Value = processed1 * 100 / fileCount + args.ProgressPercentage / fileCount; }); if (game.Version == GameVersion.CallOfDuty2) { var directory = Path.GetDirectoryName(path); var hunkusage = Path.Combine(directory ?? throw new InvalidOperationException(), "hunkusage.dat"); var hunkusageBackup = Path.Combine(directory, "hunkusage.dat.bak"); if (File.Exists(hunkusage)) { if (File.Exists(hunkusageBackup)) { File.Delete(hunkusageBackup); } File.Move(hunkusage, hunkusageBackup); } } } catch (Exception e) { LogHelper.Instance.LogException( $"Failed to download {Path.GetFileName(path)}.\n{e.GetDeepestException().Message}", e); MessageBox.Show(this, $"Failed to download {Path.GetFileName(path)}.\n{e.GetDeepestException().Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Updates the progress bar. processed++; progressBar.Value = processed * 100 / fileCount; } } else { return; } } // Disable the controls in the form and update the status label. ToggleControls(false); statusLabel.Text = $"Waiting for {demo.Version.GetFullName()} to close..."; // Bind the playback keys in the configuration of the demo's game. Factory.ConfigEditor.BindPlaybackKeys(game, demo.Mod); // Play the demo and wait for the game to close again. _isDemoRunning = true; _runningGameVersion = demo.Version; await Task.Run(() => { Factory.DemoPlayback.Start(demo) .WaitForExit(); }); _isDemoRunning = false; // Unbind the playback keys again. Factory.ConfigEditor.UnbindPlaybackKeys(game, demo.Mod); // Enable the controls in the form and reset the status label. ResetStatus(); }
public async Task <ActionResult> ClientUploadDemo(IFormFile file) { if (!Request.Headers.ContainsKey("demo-manager-auth-key")) { return(Content("AuthError: No auth key provided in the request. This should be set in the client.")); } var authKey = Request.Headers["demo-manager-auth-key"].FirstOrDefault(); if (string.IsNullOrWhiteSpace(authKey)) { _logger.LogDebug(EventIds.DemoManager, "ClientUploadDemo - Auth key header supplied was empty"); return(Content("AuthError: The auth key supplied was empty. This should be set in the client.")); } var userId = await _demoAuthRepository.GetUserId(authKey); if (userId == null) { return(Content("AuthError: Your auth key is incorrect, check the portal for the correct one and re-enter it on your client.")); } var user = await _userManager.FindByIdAsync(userId); if (file == null || file.Length == 0) { return(Content("You must provide a file to be uploaded")); } var whitelistedExtensions = new List <string> { ".dm_1", ".dm_6" }; if (!whitelistedExtensions.Any(ext => file.FileName.EndsWith(ext))) { return(Content("Invalid file type - this must be a demo file")); } var gameTypeHeader = Request.Headers["demo-manager-game-type"].ToString(); Enum.TryParse(gameTypeHeader, out GameType gameType); var fileName = $"{Guid.NewGuid().ToString()}.{gameType.DemoExtension()}"; var path = Path.Combine(Path.GetTempPath(), fileName); await using (var fileStream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(fileStream); } var localDemo = new LocalDemo(path, gameType); var frontEndFileName = Path.GetFileNameWithoutExtension(file.FileName); var demoDto = new DemoDto { Game = gameType, Name = frontEndFileName, FileName = fileName, Date = localDemo.Date, Map = localDemo.Map, Mod = localDemo.Mod, GameType = localDemo.GameType, Server = localDemo.Server, Size = localDemo.Size, UserId = user.Id }; await _demosRepository.CreateDemo(demoDto, path); _logger.LogInformation(EventIds.DemoManager, "User {Username} has uploaded a new demo {FileName}", user.UserName, demoDto.FileName); return(Ok()); }