private static async Task <string> GetJsonDataAsync(string url, MainThreadMarshaller uiMarshaller) { try { Logger.Instance.LogMessageToFile("Searching Reddit for a wallpaper.", LogLevel.Information); using (var wc = HelperMethods.CreateWebClient()) { return(await wc.DownloadStringTaskAsync(url).ConfigureAwait(false)); } } catch (WebException ex) { uiMarshaller.LogFailure(ex.Message, $"Reddit server error: {ex.Message}", LogLevel.Error); throw; } catch (Exception ex) { uiMarshaller.LogFailure("Error downloading search results.", $"Error downloading search results: {ex.Message}", LogLevel.Error); throw; } }
// TODO refactor //====================================================================== // Search for a wallpaper //====================================================================== public async Task <bool> SearchForWallpaperAsync() { Logger.Instance.LogMessageToFile("Looking for a wallpaper.", LogLevel.Information); if (MaxRetriesExceeded()) { return(true); } _uiMarshaller.UpdateStatus("Finding New Wallpaper"); try { var url = GetRedditSearchUrl(_random, _uiMarshaller); var jsonData = await GetJsonDataAsync(url, _uiMarshaller).ConfigureAwait(false); try { if (jsonData.Any()) { var redditResult = GetRedditResult(JToken.Parse(jsonData)); JToken token = null; try { foreach (var toke in redditResult.Reverse()) { token = toke; } if (token == null) { if (redditResult.HasValues) { var randIndex = _random.Next(0, redditResult.Count() - 1); token = redditResult.ElementAt(randIndex); } else { ++_noResultCount; _uiMarshaller.UpdateStatus("No results found, searching again."); Logger.Instance.LogMessageToFile("No search results, trying to change wallpaper again.", LogLevel.Information); return(false); } } if ((WallpaperGrabType)Settings.Default.wallpaperGrabType == WallpaperGrabType.Random) { token = redditResult.ElementAt(_random.Next(0, redditResult.Count() - 1)); } _uiMarshaller.SetCurrentThread($"http://reddit.com{token["data"]["permalink"]}"); if (!await ChangeWallpaperIfValidImageAsync(token).ConfigureAwait(false)) { return(true); } } catch (InvalidOperationException) { _uiMarshaller.LogFailure("Your search query is bringing up no results.", "No results from the search query."); } } else { _uiMarshaller.LogFailure("Subreddit Probably Doesn't Exist", "Subreddit probably does not exist."); _noResultCount++; return(true); } } catch (JsonReaderException ex) { _uiMarshaller.LogFailure($"Unexpected error: {ex.Message}", $"Unexpected error: {ex.Message}", LogLevel.Error); } } catch { } return(true); }