public MemoryManager(BaconManager baconMan) { m_baconMan = baconMan; // Start the thread if we should StartMemoryWatch(); }
public BackgroundManager(BaconManager baconMan) { m_baconMan = baconMan; ImageUpdaterMan = new BackgroundImageUpdater(baconMan); MessageUpdaterMan = new BackgroundMessageUpdater(baconMan); BandMan = new BackgroundBandManager(baconMan); }
/// <summary> /// Gets a reddit user. /// </summary> /// <returns>Returns null if it fails or the user doesn't exist.</returns> public static async Task<User> GetRedditUser(BaconManager baconMan, string userName) { User foundUser = null; try { // Make the call string jsonResponse = await baconMan.NetworkMan.MakeRedditGetRequest($"user/{userName}/about/.json"); // Try to parse out the user int dataPos = jsonResponse.IndexOf("\"data\":"); if (dataPos == -1) return null; int dataStartPos = jsonResponse.IndexOf('{', dataPos + 7); if (dataPos == -1) return null; int dataEndPos = jsonResponse.IndexOf("}", dataStartPos); if (dataPos == -1) return null; string userData = jsonResponse.Substring(dataStartPos, (dataEndPos - dataStartPos + 1)); // Parse the new user foundUser = await Task.Run(() => JsonConvert.DeserializeObject<User>(userData)); } catch (Exception e) { baconMan.TelemetryMan.ReportUnExpectedEvent("MisHelper", "failed to search for user", e); baconMan.MessageMan.DebugDia("failed to search for user", e); } return foundUser; }
public UiSettingManager(BaconManager baconMan) { m_baconMan = baconMan; // If we aren't a background +1 app opened. if(!baconMan.IsBackgroundTask) { AppOpenedCount++; } baconMan.OnResuming += BaconMan_OnResuming; }
/// <summary> /// Called when the user is trying to comment on something. /// </summary> /// <returns>Returns the json returned or a null string if failed.</returns> public static async Task<string> SendRedditComment(BaconManager baconMan, string redditIdCommentingOn, string comment) { string returnString = null; try { // Build the data to send List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>(); postData.Add(new KeyValuePair<string, string>("thing_id", redditIdCommentingOn)); postData.Add(new KeyValuePair<string, string>("text", comment)); // Make the call returnString = await baconMan.NetworkMan.MakeRedditPostRequest("api/comment", postData); } catch (Exception e) { baconMan.TelemetryMan.ReportUnExpectedEvent("MisHelper", "failed to send comment", e); baconMan.MessageMan.DebugDia("failed to send message", e); } return returnString; }
public MessageOfTheDayManager(BaconManager baconMan) { m_baconMan = baconMan; }
/// <summary> /// Submits a new reddit post /// </summary> public static async Task<SubmitNewPostResponse> SubmitNewPost(BaconManager baconMan, string title, string urlOrText, string subredditDisplayName, bool isSelfText, bool sendRepliesToInbox) { if (!baconMan.UserMan.IsUserSignedIn) { baconMan.MessageMan.ShowSigninMessage("submit a new post"); return new SubmitNewPostResponse(){ Success = false }; } try { // Make the data List<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>(); data.Add(new KeyValuePair<string, string>("kind", isSelfText ? "self" : "link")); data.Add(new KeyValuePair<string, string>("sr", subredditDisplayName)); data.Add(new KeyValuePair<string, string>("sendreplies", sendRepliesToInbox ? "true" : "false")); if (isSelfText) { data.Add(new KeyValuePair<string, string>("text", urlOrText)); } else { data.Add(new KeyValuePair<string, string>("url", urlOrText)); } data.Add(new KeyValuePair<string, string>("title", title)); // Make the call string jsonResponse = await baconMan.NetworkMan.MakeRedditPostRequestAsString("/api/submit/", data); // Try to see if we can find the word redirect and if we can find the subreddit url string responseLower = jsonResponse.ToLower(); if (responseLower.Contains("redirect") && responseLower.Contains($"://www.reddit.com/r/{subredditDisplayName}/comments/")) { // Success, try to parse out the new post link int startOfLink = responseLower.IndexOf($"://www.reddit.com/r/{subredditDisplayName}/comments/"); if(startOfLink == -1) { return new SubmitNewPostResponse() { Success = false }; } int endofLink = responseLower.IndexOf('"', startOfLink); if (endofLink == -1) { return new SubmitNewPostResponse() { Success = false }; } // Try to get the link string link = "https" + jsonResponse.Substring(startOfLink, endofLink - startOfLink); // Return return new SubmitNewPostResponse() { Success = true, NewPostLink = link}; } else { // We have a reddit error. Try to figure out what it is. for(int i = 0; i < Enum.GetNames(typeof(SubmitNewPostErrors)).Length; i++) { string enumName = Enum.GetName(typeof(SubmitNewPostErrors), i).ToLower(); ; if (responseLower.Contains(enumName)) { baconMan.TelemetryMan.ReportUnExpectedEvent("MisHelper", "failed to submit post; error: "+ enumName); baconMan.MessageMan.DebugDia("failed to submit post; error: "+ enumName); return new SubmitNewPostResponse() { Success = false, RedditError = (SubmitNewPostErrors)i}; } } baconMan.TelemetryMan.ReportUnExpectedEvent("MisHelper", "failed to submit post; unknown reddit error: "); baconMan.MessageMan.DebugDia("failed to submit post; unknown reddit error"); return new SubmitNewPostResponse() { Success = false, RedditError = SubmitNewPostErrors.UNKNOWN }; } } catch (Exception e) { baconMan.TelemetryMan.ReportUnExpectedEvent("MisHelper", "failed to submit post", e); baconMan.MessageMan.DebugDia("failed to submit post", e); return new SubmitNewPostResponse() { Success = false }; } }
public MemoryManager(BaconManager baconMan) { m_baconMan = baconMan; // Start the watching thread. StartMemoryWatch(); }
public BackgroundBandManager(BaconManager manager) { m_baconMan = manager; }
public ImageManager(BaconManager baconMan) { m_baconMan = baconMan; }
public UserManager(BaconManager baconMan) { m_baconMan = baconMan; m_authMan = new AuthManager(m_baconMan); }
public TelemetryManager(BaconManager baconMan) { _baconMan = baconMan; }
public BackgroundManager(BaconManager baconMan) { m_baconMan = baconMan; ImageUpdaterMan = new BackgroundImageUpdater(baconMan); MessageUpdaterMan = new BackgroundMessageUpdater(baconMan); }
public PostCollector(PostCollectorContext collectorContext, BaconManager baconMan) : base(baconMan, collectorContext.UniqueId) { // Set the vars var user = collectorContext.User; _subreddit = collectorContext.Subreddit; var sortType = collectorContext.SortType; var sortTimeType = collectorContext.SortTimeType; _baconMan = baconMan; // If we are doing a top sort setup the sort time var optionalArgs = string.Empty; if (sortType == SortTypes.Top) { switch (sortTimeType) { case SortTimeTypes.AllTime: optionalArgs = "sort=top&t=all"; break; case SortTimeTypes.Day: optionalArgs = "sort=top&t=day"; break; case SortTimeTypes.Hour: optionalArgs = "sort=top&t=hour"; break; case SortTimeTypes.Month: optionalArgs = "sort=top&t=month"; break; case SortTimeTypes.Week: optionalArgs = "sort=top&t=week"; break; case SortTimeTypes.Year: optionalArgs = "sort=top&t=year"; break; } } var postCollectionUrl = ""; var hasEmptyRoot = false; if (_subreddit != null) { if (_subreddit.DisplayName.ToLower() == "frontpage") { // Special case for the front page postCollectionUrl = $"/{SortTypeToString(sortType)}/.json"; } else if (_subreddit.DisplayName.ToLower() == "saved") { // Special case for the saved posts postCollectionUrl = $"/user/{_baconMan.UserMan.CurrentUser.Name}/saved/.json"; optionalArgs = "type=links"; } else if (!string.IsNullOrWhiteSpace(collectorContext.ForcePostId)) { // We are only going to try to grab one specific post. This is used by search and inbox to // link to a post. Since we are doing so, we need to make the unique id something unique for this post so we don't get // a cache. This should match the unique id we use to look up the subreddit above. SetUniqueId(_subreddit.Id + sortType + collectorContext.ForcePostId); postCollectionUrl = $"/r/{_subreddit.DisplayName}/comments/{collectorContext.ForcePostId}/.json"; hasEmptyRoot = true; } else { postCollectionUrl = $"/r/{_subreddit.DisplayName}/{SortTypeToString(sortType)}/.json"; } } else { // Get posts for a user postCollectionUrl = $"user/{user.Name}/submitted/.json"; switch (sortType) { case SortTypes.Controversial: optionalArgs = "sort=controversial"; break; case SortTypes.Hot: optionalArgs = "sort=hot"; break; case SortTypes.New: optionalArgs = "sort=new"; break; case SortTypes.Top: optionalArgs = "sort=top"; break; case SortTypes.Rising: break; default: throw new ArgumentOutOfRangeException(); } } InitListHelper(postCollectionUrl, hasEmptyRoot, true, optionalArgs); // Listen to user changes so we will update the subreddits _baconMan.UserMan.OnUserUpdated += OnUserUpdated; }
public TileManager(BaconManager baconMan) { m_baconMan = baconMan; }
/// <summary> /// Attempts to parse out a reddit object from a generic reddit response /// json containing a data object. We can't do a generic DataObject here because /// the function handles data blocks that are in various depths in the json. /// </summary> /// <param name="originalJson"></param> /// <returns></returns> public static T ParseOutRedditDataElement <T>(BaconManager baconMan, string originalJson) { // TODO make this async. If I try to Task.Run(()=> the parse the task returns but the // await never resumes... idk why. // Try to parse out the data object int dataPos = originalJson.IndexOf("\"data\":"); if (dataPos == -1) { return(default(T)); } int dataStartPos = originalJson.IndexOf('{', dataPos + 7); if (dataStartPos == -1) { return(default(T)); } // There can be nested { } in the data we want // To do this optimally, we will just look for the close manually. int dataEndPos = dataStartPos + 1; int depth = 0; bool isInText = false; while (dataEndPos < originalJson.Length) { // If we find a " make sure we ignore everything. if (originalJson[dataEndPos] == '"') { if (isInText) { // If we are in a text block look if it is an escape. // If it isn't an escape, end the text block. if (originalJson[dataEndPos - 1] != '\\') { isInText = false; } } else { // We entered text. isInText = true; } } // If not in a text block, look for {} if (!isInText) { // If we find an open +1 to depth if (originalJson[dataEndPos] == '{') { depth++; } // If we find and end.. else if (originalJson[dataEndPos] == '}') { // If we have no depth we are done. if (depth == 0) { break; } // Otherwise take one off. else { depth--; } } } dataEndPos++; } // Make sure we didn't fail. if (depth != 0) { return(default(T)); } // Move past the last } dataEndPos++; string dataBlock = originalJson.Substring(dataStartPos, (dataEndPos - dataStartPos)); return(JsonConvert.DeserializeObject <T>(dataBlock)); }
protected Collector(BaconManager manager, string uniqueId) { m_baconMan = manager; m_uniqueId = uniqueId; }
public NetworkManager(BaconManager baconMan) { m_baconMan = baconMan; }
public CommentCollector(CommentCollectorContext context, BaconManager baconMan) : base(baconMan, context.UniqueId) { // Set the vars m_baconMan = baconMan; m_post = context.post; m_user = context.user; string commentBaseUrl = ""; string optionalParams = null; bool hasEmptyRoot = true; bool takeFirstArray = false; if (m_post != null) { // See if it a force comment if (!String.IsNullOrWhiteSpace(context.forceComment)) { // Set a unique id for this request SetUniqueId(m_post.Id + context.forceComment); // Make the url commentBaseUrl = $"{context.post.Permalink}{context.forceComment}.json"; optionalParams = "context=3"; } else { // Get the post url commentBaseUrl = $"/r/{context.post.Subreddit}/comments/{context.post.Id}.json"; optionalParams = $"sort={ConvertSortToUrl(m_post.CommentSortType)}"; } hasEmptyRoot = true; takeFirstArray = false; } else { commentBaseUrl = $"user/{m_user.Name}/comments/.json"; hasEmptyRoot = false; takeFirstArray = true; switch (context.userSort) { case SortTypes.Controversial: optionalParams = "sort=controversial"; break; case SortTypes.Hot: optionalParams = "sort=hot"; break; case SortTypes.New: optionalParams = "sort=new"; break; case SortTypes.Top: optionalParams = "sort=top"; break; } } // Make the helper, we need to ask it to make a fake root and not to take the // first element, the second element is the comment tree. InitListHelper(commentBaseUrl, hasEmptyRoot, takeFirstArray, optionalParams); }
public CacheManager(BaconManager baconMan) { m_baconMan = baconMan; }
public AuthManager(BaconManager baconMan) { m_baconMan = baconMan; }
/// <summary> /// Submits a new reddit post /// </summary> public static async Task <SubmitNewPostResponse> SubmitNewPost(BaconManager baconMan, string title, string urlOrText, string subredditDisplayName, bool isSelfText, bool sendRepliesToInbox) { if (!baconMan.UserMan.IsUserSignedIn) { baconMan.MessageMan.ShowSigninMessage("submit a new post"); return(new SubmitNewPostResponse() { Success = false }); } try { // Make the data List <KeyValuePair <string, string> > data = new List <KeyValuePair <string, string> >(); data.Add(new KeyValuePair <string, string>("kind", isSelfText ? "self" : "link")); data.Add(new KeyValuePair <string, string>("sr", subredditDisplayName)); data.Add(new KeyValuePair <string, string>("sendreplies", sendRepliesToInbox ? "true" : "false")); if (isSelfText) { data.Add(new KeyValuePair <string, string>("text", urlOrText)); } else { data.Add(new KeyValuePair <string, string>("url", urlOrText)); } data.Add(new KeyValuePair <string, string>("title", title)); // Make the call string jsonResponse = await baconMan.NetworkMan.MakeRedditPostRequestAsString("/api/submit/", data); // Try to see if we can find the word redirect and if we can find the subreddit url string responseLower = jsonResponse.ToLower(); if (responseLower.Contains("redirect") && responseLower.Contains($"://www.reddit.com/r/{subredditDisplayName}/comments/")) { // Success, try to parse out the new post link int startOfLink = responseLower.IndexOf($"://www.reddit.com/r/{subredditDisplayName}/comments/"); if (startOfLink == -1) { return(new SubmitNewPostResponse() { Success = false }); } int endofLink = responseLower.IndexOf('"', startOfLink); if (endofLink == -1) { return(new SubmitNewPostResponse() { Success = false }); } // Try to get the link string link = "https" + jsonResponse.Substring(startOfLink, endofLink - startOfLink); // Return return(new SubmitNewPostResponse() { Success = true, NewPostLink = link }); } else { // We have a reddit error. Try to figure out what it is. for (int i = 0; i < Enum.GetNames(typeof(SubmitNewPostErrors)).Length; i++) { string enumName = Enum.GetName(typeof(SubmitNewPostErrors), i).ToLower();; if (responseLower.Contains(enumName)) { baconMan.TelemetryMan.ReportUnExpectedEvent("MisHelper", "failed to submit post; error: " + enumName); baconMan.MessageMan.DebugDia("failed to submit post; error: " + enumName); return(new SubmitNewPostResponse() { Success = false, RedditError = (SubmitNewPostErrors)i }); } } baconMan.TelemetryMan.ReportUnExpectedEvent("MisHelper", "failed to submit post; unknown reddit error: "); baconMan.MessageMan.DebugDia("failed to submit post; unknown reddit error"); return(new SubmitNewPostResponse() { Success = false, RedditError = SubmitNewPostErrors.UNKNOWN }); } } catch (Exception e) { baconMan.TelemetryMan.ReportUnExpectedEvent("MisHelper", "failed to submit post", e); baconMan.MessageMan.DebugDia("failed to submit post", e); return(new SubmitNewPostResponse() { Success = false }); } }
public MessageOfTheDayManager(BaconManager baconMan) { _mBaconMan = baconMan; }
/// <summary> /// Construct a new trending subreddits helper. /// </summary> /// <param name="baconMan">The reddit connection manager used to get the trending subreddits.</param> public TrendingSubredditsHelper(BaconManager baconMan) { m_baconMan = baconMan; }
public SubredditManager(BaconManager baconMan) { m_baconMan = baconMan; m_baconMan.UserMan.OnUserUpdated += UserMan_OnUserUpdated; }
public DraftManager(BaconManager baconMan) { m_baconMan = baconMan; }
/// <summary> /// Attempts to delete a post. /// </summary> /// <param name="baconMan"></param> /// <param name="postId"></param> /// <returns></returns> public static async Task<bool> DeletePost(BaconManager baconMan, string postId) { string returnString = null; try { // Build the data to send List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>(); postData.Add(new KeyValuePair<string, string>("id", "t3_"+postId)); // Make the call returnString = await baconMan.NetworkMan.MakeRedditPostRequestAsString("api/del", postData); if(returnString.Equals("{}")) { return true; } } catch (Exception e) { baconMan.TelemetryMan.ReportUnexpectedEvent("MisHelper", "failed to delete post", e); baconMan.MessageMan.DebugDia("failed to delete post", e); } return false; }
public MessageManager(BaconManager baconMan) { m_baconMan = baconMan; }
/// <summary> /// Saves, unsaves, hides, or unhides a reddit item. /// </summary> /// <returns>Returns null if it fails or the user doesn't exist.</returns> public static async Task<bool> SaveOrHideRedditItem(BaconManager baconMan, string redditId, bool? save, bool? hide) { if(!baconMan.UserMan.IsUserSignedIn) { baconMan.MessageMan.ShowSigninMessage(save.HasValue ? "save item" : "hide item"); return false; } bool wasSuccess = false; try { // Make the data List<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>(); data.Add(new KeyValuePair<string, string>("id", redditId)); string url; if (save.HasValue) { url = save.Value ? "/api/save" : "/api/unsave"; } else if(hide.HasValue) { url = hide.Value ? "/api/hide" : "/api/unhide"; } else { return false; } // Make the call string jsonResponse = await baconMan.NetworkMan.MakeRedditPostRequestAsString(url, data); if(jsonResponse.Contains("{}")) { wasSuccess = true; } else { baconMan.TelemetryMan.ReportUnExpectedEvent("MisHelper", "failed to save or hide item, unknown response"); baconMan.MessageMan.DebugDia("failed to save or hide item, unknown response"); } } catch (Exception e) { baconMan.TelemetryMan.ReportUnExpectedEvent("MisHelper", "failed to save or hide item", e); baconMan.MessageMan.DebugDia("failed to save or hide item", e); } return wasSuccess; }
/// <summary> /// Uploads a image file to imgur. /// </summary> /// <param name="baconMan"></param> /// <param name="image"></param> /// <returns></returns> public static string UploadImageToImgur(BaconManager baconMan, FileRandomAccessStream imageStream) { //try //{ // // Make the data // List<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>(); // data.Add(new KeyValuePair<string, string>("key", "1a507266cc9ac194b56e2700a67185e4")); // data.Add(new KeyValuePair<string, string>("title", "1a507266cc9ac194b56e2700a67185e4")); // // Read the image from the stream and base64 encode it. // Stream str = imageStream.AsStream(); // byte[] imageData = new byte[str.Length]; // await str.ReadAsync(imageData, 0, (int)str.Length); // data.Add(new KeyValuePair<string, string>("image", WebUtility.UrlEncode(Convert.ToBase64String(imageData)))); // string repsonse = await baconMan.NetworkMan.MakePostRequest("https://api.imgur.com/2/upload.json", data); //} //catch (Exception e) //{ // baconMan.TelemetryMan.ReportUnExpectedEvent("MisHelper", "failed to submit post", e); // baconMan.MessageMan.DebugDia("failed to submit post", e); // return new SubmitNewPostResponse() { Success = false }; //} throw new NotImplementedException("This function isn't complete!"); }
public BackgroundMessageUpdater(BaconManager baconMan) { m_baconMan = baconMan; }
public BackgroundImageUpdater(BaconManager baconMan) { m_baconMan = baconMan; }
/// <summary> /// Returns a collector for the given type. If the collector doesn't exist one will be created. /// </summary> /// <param name="subreddit"></param> /// <returns></returns> protected static Collector <T> GetCollector(Type objectType, string collectorId, object initObject, BaconManager baconMan) { lock (s_collectors) { // See if the collector exists and if it does try to get it. Collector <T> collector = null; if (s_collectors.ContainsKey(collectorId) && s_collectors[collectorId].TryGetTarget(out collector) && collector != null) { return(collector); } else { object[] args = { initObject, baconMan }; collector = (Collector <T>)Activator.CreateInstance(objectType, args); s_collectors[collectorId] = new WeakReference <Collector <T> >(collector); return(collector); } } }