/// <summary> /// Create a campaign for the given parameters /// </summary> /// <param name="campaignUh">Reddit's campaign creation page modhash</param> /// <param name="camp">Campaign to be created</param> /// <returns>A status object stating whether the creation failed or succeeded</returns> private RedditAdJson CreateCampaign(string campaignUh, Campaign camp) { var result = new RedditAdJson(); string postString = $"link_id36={camp.Advertisement.RedditAdId}&targeting=subreddit&sr=&selected_sr_names={camp.TargetDetail}&country={camp.Location}®ion={camp.Location2}&metro=&mobile_os=&platform={camp.Platform}&undefined={camp.Start.AddDays(3).ToString("MM/dd/yyyy")}&total_budget_dollars={camp.Budget}&impressions={camp.Budget / 200 * 1000 * 100}&startdate={camp.Start.ToString("MM/dd/yyyy")}&enddate={camp.End.ToString("MM/dd/yyyy")}&cost_basis=cpm&bid_dollars={string.Format(CultureInfo.GetCultureInfo("en-US"), "{0: 0.##}", camp.PricingCpm)}&is_new=true&campaign_id36=&campaign_name=&id=%23campaign&uh={campaignUh}&renderstyle=html"; var adUrl = "https://www.reddit.com/api/edit_campaign"; if (camp.BudgetOptionDeliverFast) { postString += "&no_daily_budget=on"; } if (camp.OptionExtend) { postString += "&auto_extend=on"; } var campaignRequest = WebRequest.Create(adUrl) as HttpWebRequest; if (campaignRequest != null) { campaignRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; campaignRequest.Method = "POST"; campaignRequest.CookieContainer = Cookies; campaignRequest.Accept = "application/json, text/javascript, */*; q=0.01"; campaignRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; campaignRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"; campaignRequest.Referer = "https://www.reddit.com/"; var customHeaders = campaignRequest.Headers; customHeaders.Add("accept-language", "en;q=0.4"); customHeaders.Add("origin", "https://www.reddit.com"); customHeaders.Add("x-requested-with", "XMLHttpRequest"); var bytes = Encoding.ASCII.GetBytes(postString); campaignRequest.ContentLength = bytes.Length; using (var os = campaignRequest.GetRequestStream()) { os.Write(bytes, 0, bytes.Length); } var campaignResponse = campaignRequest.GetResponse() as HttpWebResponse; if (campaignResponse != null && campaignResponse.StatusCode == HttpStatusCode.OK) { using (var s = campaignResponse.GetResponseStream()) { using ( // ReSharper disable once AssignNullToNotNullAttribute var sr = new StreamReader(s, Encoding.GetEncoding(campaignResponse.CharacterSet)) ) { var jsonString = sr.ReadToEnd(); result = JsonConvert.DeserializeObject <RedditAdJson>(jsonString); } } } } return(result); }
/// <summary> /// Create an advertisement for the given parameters /// </summary> /// <param name="adUh">Reddit's advertisement creation page modhash</param> /// <param name="ad">Advertisement to be created</param> /// <returns>A status object stating whether the creation failed or succeeded</returns> private RedditAdJson CreateAdvertisement(string adUh, Advertisement ad) { string postString = $"uh={adUh}&id=%23promo-form&title={ad.Title}&kind=link&url={ad.Url}&thing_id=&text=&renderstyle=html"; var adUrl = "https://www.reddit.com/api/create_promo"; var result = new RedditAdJson(); if (ad.SendComments) { postString += "&sendreplies=on"; } if (ad.DisableComments) { postString += "&disable_comments=on"; } var promoRequest = WebRequest.Create(adUrl) as HttpWebRequest; if (promoRequest == null) { throw new ArgumentNullException(nameof(promoRequest)); } promoRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; promoRequest.Method = "POST"; promoRequest.CookieContainer = Cookies; promoRequest.Accept = "application/json, text/javascript, */*; q=0.01"; promoRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; promoRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"; promoRequest.Referer = "https://www.reddit.com/"; promoRequest.Timeout = 15000; var customHeaders = promoRequest.Headers; customHeaders.Add("accept-language", "en;q=0.4"); customHeaders.Add("origin", "https://www.reddit.com"); customHeaders.Add("x-requested-with", "XMLHttpRequest"); var bytes = Encoding.ASCII.GetBytes(postString); promoRequest.ContentLength = bytes.Length; using (var os = promoRequest.GetRequestStream()) { os.Write(bytes, 0, bytes.Length); } var promoResponse = promoRequest.GetResponse() as HttpWebResponse; if (promoResponse != null && promoResponse.StatusCode == HttpStatusCode.OK) { using (var s = promoResponse.GetResponseStream()) { // ReSharper disable once AssignNullToNotNullAttribute using (var sr = new StreamReader(s, Encoding.GetEncoding(promoResponse.CharacterSet))) { result = JsonConvert.DeserializeObject <RedditAdJson>(sr.ReadToEnd()); } } } return(result); }
/// <summary> /// Handle ads and campaigns processes /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void BeginCreationButton_Click(object sender, RoutedEventArgs e) { Log("INFO", "Beggining ad creation"); GeneralProgressBar.Visibility = Visibility.Visible; foreach (var ad in Ads) { var errorMsg = string.Empty; var error = false; var imgPathText = ImagePathTextBox.Text; var result = new RedditAdJson(); try { var task = Task.Factory.StartNew(() => { result = StartAdvertisementProcess(ad, imgPathText); }); await task; } catch (AggregateException ae) { ae.Handle(x => { if (x is FileNotFoundException) { errorMsg = x.Message; error = true; } else { errorMsg = x.Message + " | " + x.StackTrace; error = true; } return(error); }); } catch (Exception ex) { errorMsg = ex.Message + " | " + ex.StackTrace; error = true; } if (error) { Log("ERROR", errorMsg); } else { if (result.Success) { ad.RedditAdId = result.Jquery[16][3].ToString().Split('/')[5].Remove(6); Log("INFO", $"Ad #{ad.AdvertisementNumber} successfully created ({ad.RedditAdId})"); } } await Task.Delay(Convert.ToInt32(DelayPicker.Value)); } Log("INFO", "Finished creating ads!"); // Update Reddit ad ID on campaigns list foreach (var camp in Campaigns) { camp.Advertisement.RedditAdId = Ads.Where(x => x.AdvertisementNumber == camp.Advertisement.AdvertisementNumber) .Select(x => x.RedditAdId) .First(); } Log("INFO", "Beggining campaign creation"); foreach (var camp in Campaigns) { var errorMsg = string.Empty; var error = false; var result = new RedditAdJson(); try { var task = Task.Factory.StartNew(() => { result = StartCampaignProcess(camp); }); await task; } catch (AggregateException ae) { ae.Handle(x => { errorMsg = x.Message + " | " + x.StackTrace; error = true; return(error); }); } if (error) { Log("ERROR", errorMsg); } else { if (result.Success) { Log("INFO", $"Campaign for ad ID {camp.Advertisement.RedditAdId} successfully created"); } else { var msg = result.Jquery[14][3]; Log("ERROR", $"Error creating campaign for ad ID {camp.Advertisement.RedditAdId}:{msg.ToString().Replace(Environment.NewLine, string.Empty).Replace("[", string.Empty).Replace("]", string.Empty).Replace("\"", string.Empty)}"); } } await Task.Delay(Convert.ToInt32(DelayPicker.Value)); } GeneralProgressBar.Visibility = Visibility.Hidden; Log("INFO", "Completed"); }