private static void BackupGame(Game game, string destDirName) { Debug.WriteLine(@"Starting file copy for " + game.Name); var allFiles = Directory.GetFiles(game.Path, "*.*", SearchOption.AllDirectories); foreach (var sourceFile in allFiles) { try { var index = sourceFile.IndexOf(game.RootFolder, StringComparison.CurrentCulture); var substring = sourceFile.Substring(index); var destinationFi = new FileInfo(destDirName + "\\" + substring); var destinationDir = destinationFi.DirectoryName; if (!Directory.Exists(destinationDir)) Directory.CreateDirectory(destinationDir); var file = new FileInfo(sourceFile); file.CopyTo(destinationFi.FullName, true); _progress.FilesComplete++; Messenger.Default.Send(_progress); } catch (IOException ex) { SBTErrorLogger.Log(ex.Message); } catch (NullReferenceException ex) { SBTErrorLogger.Log(ex.Message); } } Debug.WriteLine(@"Finished file copy for " + game.Name); }
//Retrieves GameID if it is the default value 999999 in json file. public async Task GetGameID(Game game) { var fullSearchPath = new Uri(SearchBase + game.Name); var client = new WebClient() { Proxy = null }; var result = await client.DownloadStringTaskAsync(fullSearchPath); var indexOfFirstTag = result.IndexOf("<id>"); var resultExFirstTag = result.Substring(indexOfFirstTag + 4); var indexOfSecondTag = resultExFirstTag.IndexOf("</id>"); game.ID = int.Parse(resultExFirstTag.Remove(indexOfSecondTag)); }
//Gets the GamesDB thumbnail's web URL private async Task GetThumbUrl(Game game) { var thumbQueryUrl = SearchThumbUrlBase + game.ID.ToString(); var client = new WebClient() { Proxy = null }; ; var artResponseString = await client.DownloadStringTaskAsync(thumbQueryUrl); var index = artResponseString.IndexOf("boxart/thumb/original/front/"); var beginningTrimmed = artResponseString.Substring(index); var endIndex = beginningTrimmed.IndexOf("\">"); var endTrimmed = beginningTrimmed.Remove(endIndex); var finalUrl = BannerBase + endTrimmed; game.ThumbnailPath = finalUrl; gameDataChanged = true; }
//Not currently being used //public GiantBombAPI(int game_ID, Game game) { // _game = game; // _newGameId = game_ID; // //CreateThumbnail(_game_ID); //} //public GiantBombAPI(Game game) { // _game = game; //} public static async Task GetThumb(Game game) { //Create path for thumbnails directory and get all files in directory var thumbnailDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Save Backup Tool\\Thumbnails\\"; if (!Directory.Exists(thumbnailDirectory)) Directory.CreateDirectory(thumbnailDirectory); var files = Directory.GetFiles(thumbnailDirectory); thumbnailDirectory += game.Name; //search for thumbnail in directory //if found, set _thumbnailPath to path on HDD for (var i = 0; i < files.Count(); i++) { if (files[i].Contains(thumbnailDirectory)){ //could also check for game.Name game.ThumbnailPath = files[i]; gameDataChanged = true; break; } } //If thumbnailPath is found, leave method. if (!string.IsNullOrWhiteSpace(game.ThumbnailPath) && !game.ThumbnailPath.Contains("Loading")) return; //If thumbnail not found, retrieve gameID and thumbnail. if (game.ID == 999999) { await GetGameID(game); } //if (_thumbnailPath == null && game.ID != 999999) if (game.ThumbnailPath.Contains("Loading") || game.ThumbnailPath.Contains("NoThumb")) await GetThumbUrl(game); if (!string.IsNullOrWhiteSpace(game.ThumbnailPath) && !game.ThumbnailPath.Contains("NoThumb.jpg")) await DownloadThumbnail(game); if (gameDataChanged) await UpdateGameInJson(game); }
public static BackupResultHelper RemoveFromAutobackup(Game game) { if (!_fileWatcherList.Any() && !GamesToBackup.Any()) return new BackupResultHelper(){ Success = true, AutobackupEnabled = false, BackupDateTime = DateTime.Now.ToLocalTime().ToString(),Message = "No games to remove."}; for (var i = 0; i < _fileWatcherList.Count; i++) { if (_fileWatcherList[i].Path.Contains(game.Path)) { //Remove watcher from watcher list _fileWatcherList.RemoveAt(i); } } for (var i = 0; i < GamesToBackup.Count; i++) { if (GamesToBackup[i].Name == game.Name) //Remove game from GamesToBackup GamesToBackup.RemoveAt(i); } //If there is a difference between lists, shut down all operations. if ((!_fileWatcherList.Any() && GamesToBackup.Any()) || (_fileWatcherList.Any() && !GamesToBackup.Any())) { return ShutdownAutobackup(); //If you hit this, there is a problem. } var message = ""; var time = DateTime.Now.ToLocalTime().ToString(); if (_fileWatcherList.Any()) //Games remaining message = string.Format("{0} removed from auto-backup", game.Name); else { return ShutdownAutobackup(); } return new BackupResultHelper() { //Only reachable if games remain in GamesToBackup Success = true, AutobackupEnabled = true, BackupDateTime = time, Message = message }; }
public static async Task AddToJson(Game newGameForJson) { try { var gameJsonList = await JsonConvert.DeserializeObjectAsync<List<Game>>(File.ReadAllText(GameListPath)); gameJsonList.Add(newGameForJson); var listToReturn = new ObservableCollection<Game>(gameJsonList.OrderBy(x => x.Name)); var fileToWrite = await JsonConvert.SerializeObjectAsync(listToReturn); File.WriteAllText(GameListPath, fileToWrite); } catch (Exception ex) { SBTErrorLogger.Log(ex.Message); } }
//If something has been changed in the game parameter, //Update the json private static async Task UpdateGameInJson(Game game) { var listToReturn = new List<Game>(); var gameJsonList = await JsonConvert.DeserializeObjectAsync<List<Game>>(File.ReadAllText(GameListPath)); listToReturn.AddRange(gameJsonList.Select(g => g.Name == game.Name ? game : g)); var fileToWrite = JsonConvert.SerializeObject(listToReturn); File.WriteAllText(GameListPath, fileToWrite); }
//Downloads thumbnail using URL //And sets game.ThumbnailPath to local thumb cache private static async Task DownloadThumbnail(Game game) { var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var extension = Path.GetExtension(game.ThumbnailPath); //new FileInfo(game.ThumbnailPath); //Create path for thumbnail on HDD var thumbLocalPath = documentsPath + "\\Save Backup Tool\\Thumbnails\\" + game.Name + extension; var fi = new FileInfo(thumbLocalPath); //If File doesn't exist, download it. try { if (File.Exists(fi.ToString())) return; var webClient = new WebClient(); await webClient.DownloadFileTaskAsync(new Uri(game.ThumbnailPath), fi.FullName); game.ThumbnailPath = thumbLocalPath; gameDataChanged = true; } catch (Exception ex) { SBTErrorLogger.Log(ex.Message); } }
//Gets the Giant Bomb thumbnail's web URL private static async Task GetThumbUrl(Game game) { var thumbQueryUrl = BuildThumbQueryString(game.ID); var responseString = ""; using (var client = new HttpClient()) responseString = await client.GetStringAsync(thumbQueryUrl); var blob = await JsonConvert.DeserializeObjectAsync<dynamic>(responseString); try { game.ThumbnailPath = blob.results.image.thumb_url; } catch (RuntimeBinderException ex) { SBTErrorLogger.Log(ex.Message); game.ThumbnailPath = @"pack://application:,,,/Assets/NoThumb.jpg"; } }
//Retrieves GameID if it is the default value 999999 in json file. public static async Task GetGameID(Game game) { var searchString = BuildIdQueryString(game.Name); var responseString = ""; using (var client = new HttpClient()) responseString = await client.GetStringAsync(searchString); var blob = await JsonConvert.DeserializeObjectAsync<dynamic>(responseString); try { game.ID = blob.results[0].id; gameDataChanged = true; } catch (ArgumentOutOfRangeException ex) { SBTErrorLogger.Log(ex.Message); } }
public static void InitializeWatchers(Game gameToAdd = null) { if (!_backupEnabled) { _delayTimer = new Timer {Interval = 5000, AutoReset = true}; _delayTimer.Elapsed += _delayTimer_Elapsed; _canBackupTimer = new Timer {Interval = 5000, AutoReset = true}; _canBackupTimer.Elapsed += _canBackupTimer_Elapsed; _lastAutoBackupTime = DateTime.Now; _fileWatcherList = new List<FileSystemWatcher>(); } var watcherNumber = 0; if (gameToAdd != null) { CreateWatcher(gameToAdd, watcherNumber); watcherNumber++; } else { foreach (var game in GamesToBackup.Where(game => Directory.Exists(game.Path))) { Debug.WriteLine(@"Initializing Watchers"); CreateWatcher(game, watcherNumber); watcherNumber++; } } Debug.WriteLine(@"Finished adding {0} Watchers to list", watcherNumber); }
public static BackupResultHelper RemoveFromAutobackup(Game game) { if (game == null) return ErrorResultHelper; var result = BackupAuto.RemoveFromAutobackup(game); return result; }
private static async Task<bool> CopySaves(Game game, IEnumerable<FileInfo> filesToCopy) { var startTime = Watch.Elapsed; var fileCopied = false; _progress.TotalFiles = filesToCopy.Count(); Debug.WriteLine(@"CopySaves starting at {0}", startTime); try { foreach (var sourceFile in filesToCopy) { var index = sourceFile.FullName.IndexOf(game.RootFolder, StringComparison.Ordinal); var substring = sourceFile.FullName.Substring(index); var destPath = _autoBackupDirectoryInfo.FullName + "\\" + substring; var dir = new FileInfo(destPath); if (!Directory.Exists(dir.DirectoryName)) Directory.CreateDirectory(dir.DirectoryName); using ( var inStream = new FileStream(sourceFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var outStream = new FileStream(destPath, FileMode.Create)) { await inStream.CopyToAsync(outStream); Debug.WriteLine(@"SUCCESSFUL COPY: {0} copied to {1}", sourceFile.Name, destPath); fileCopied = true; _numberOfBackups++; _progress.FilesComplete++; Messenger.Default.Send(_progress); Messenger.Default.Send(DateTime.Now.ToLocalTime().ToString()); } } } } catch (ArgumentException ex) { Debug.WriteLine(@"ERROR during CopySaves"); SBTErrorLogger.Log(ex.Message); } catch (IOException ex) { Debug.WriteLine(@"ERROR during CopySaves"); SBTErrorLogger.Log(ex.Message); } catch (Exception ex) { Debug.WriteLine(@"ERROR during CopySaves"); SBTErrorLogger.Log(ex.Message); } var endtime = Watch.Elapsed; Debug.WriteLine(@"CopySaves finished at {0}", endtime); Debug.WriteLine(@"CopySaves finished in {0}.", (endtime - startTime)); Messenger.Default.Send(_numberOfBackups); _progress.FilesComplete = 0; Messenger.Default.Send(_progress); return fileCopied; }
private static void GetTargetFiles(Game game, bool updatingDictionary) { Debug.WriteLine(@"Getting files in target directory for " + game.Name); var targetDirectory = new DirectoryInfo(_autoBackupDirectoryInfo.FullName + "\\" + game.Name); if (!Directory.Exists(targetDirectory.FullName)) Directory.CreateDirectory(targetDirectory.FullName); var targets = targetDirectory.GetFiles("*", SearchOption.AllDirectories).ToList(); if (!updatingDictionary) { //First adding to dictionary GameTargetDictionary.Add(game, targets); return; } if (GameTargetDictionary.ContainsKey(game)) //Updating dictionary. Remove entry for game, then re-add with updated source. GameTargetDictionary.Remove(game); GameTargetDictionary.Add(game, targets); }
/// <summary> /// Returns false if no game files are found /// </summary> /// <param name="game"></param> /// <param name="updatingDictionary"></param> /// <returns></returns> private static bool GetSourceFiles(Game game, bool updatingDictionary) { Debug.WriteLine(@"Getting files in source directory for " + game.Name); var sourceDirectory = new DirectoryInfo(game.Path); if (!Directory.Exists(sourceDirectory.FullName)) return false; var sources = sourceDirectory.GetFiles("*", SearchOption.AllDirectories).ToList(); if (!updatingDictionary) { //First adding to dictionary GameFileDictionary.Add(game, sources); return true; } if (GameFileDictionary.ContainsKey(game)) //Updating dictionary. Remove entry for game, then re-add with updated source. GameFileDictionary.Remove(game); GameFileDictionary.Add(game, sources); return true; }
public static void CreateWatcher(Game game, int watcherNumber = 0) { var filePath = new FileInfo(game.Path + "\\"); _fileWatcherList.Add(new FileSystemWatcher(filePath.FullName)); _fileWatcherList[watcherNumber].Changed += OnChanged; _fileWatcherList[watcherNumber].Created += OnChanged; _fileWatcherList[watcherNumber].Deleted += OnChanged; _fileWatcherList[watcherNumber].Renamed += OnRenamed; _fileWatcherList[watcherNumber].Error += OnError; _fileWatcherList[watcherNumber].NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName; _fileWatcherList[watcherNumber].IncludeSubdirectories = true; _fileWatcherList[watcherNumber].Filter = "*"; _fileWatcherList[watcherNumber].EnableRaisingEvents = true; Debug.WriteLine(@"Watcher added to list for " + game.Name); }
public static Game ModifyGamePaths(Game game) { var editedGame = new Game(); try { if (!game.HasCustomPath && game.Path.Contains("Documents")) editedGame = new Game(game.Name, UserPath + game.Path, game.ID, game.ThumbnailPath, game.HasCustomPath, game.HasThumb, game.RootFolder); else if (!game.HasCustomPath && game.Path.Contains("Program Files")) editedGame = new Game(game.Name, HardDrive + game.Path, game.ID, game.ThumbnailPath, game.HasCustomPath, game.HasThumb, game.RootFolder); else if (!game.HasCustomPath && game.Path.Contains("AppData")) editedGame = new Game(game.Name, UserPath + game.Path, game.ID, game.ThumbnailPath, game.HasCustomPath, game.HasThumb, game.RootFolder); else if (!game.HasCustomPath && game.Path.Contains("Desktop")) editedGame = new Game(game.Name, UserPath + game.Path, game.ID, game.ThumbnailPath, game.HasCustomPath, game.HasThumb, game.RootFolder); else editedGame = game; } catch (Exception ex) { SBTErrorLogger.Log(ex.Message); } return editedGame; }
//Downloads thumbnail using URL //And sets game.ThumbnailPath to local thumb cache private async Task DownloadThumbnail(Game game) { var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); if (string.IsNullOrWhiteSpace(game.ThumbnailPath)) return; var extension = Path.GetExtension(game.ThumbnailPath); //Create path for thumbnail on HDD var thumbLocalPath = String.Format("{0}\\Save Backup Tool\\Thumbnails\\{1}{2}", documentsPath, game.Name, extension); var fi = new FileInfo(thumbLocalPath); if (File.Exists(fi.ToString())) return; //If File doesn't exist, download it. try { var webClient = new WebClient(); var downloadSourceUri = new Uri(game.ThumbnailPath); await webClient.DownloadFileTaskAsync(downloadSourceUri, fi.FullName); game.ThumbnailPath = thumbLocalPath; gameDataChanged = true; } catch (Exception ex) { SBTErrorLogger.Log(ex.Message); } }
public static BackupResultHelper AddToAutobackup(Game game) { if (game == null) return ErrorResultHelper; var editedGame = ModifyGamePaths(game); var result = BackupAuto.AddToAutobackup(editedGame); return result; }
public static BackupResultHelper AddToAutobackup(Game game) { if (!GetSourceFiles(game, false)) { FilesNotFoundHelper.Message = string.Format("No files found for " + game.Name + ". Game not added."); FilesNotFoundHelper.RemoveFromAutobackup = true; FilesNotFoundHelper.AutobackupEnabled = _backupEnabled; return FilesNotFoundHelper; } GetTargetFiles(game, false); InitializeWatchers(game); GamesToBackup.Add(game); return new BackupResultHelper() { AutobackupEnabled = true, Message = string.Format(game.Name + @" added"), Success = true }; }