OptOutFetcher/Program.cs

82 lines
2.8 KiB
C#

using RestSharp;
using System.Text.Json.Nodes;
using System.Text.Json;
using System.Net;
using RestSharp.Authenticators;
/*
Campaign Monitor API reference: https://www.campaignmonitor.com/api/v3-3/getting-started/
Dobbs API key/client ID available from Josh in \\KM202401\c$\Users\joshdeck.KEYMTV\Documents\Misc\OptOutFetcher
*/
internal class Program
{
private static string ListID = "3bb5109cdf3265eac26b3fa34ffae379";
static void Main(string[] args)
{
GetBouncedUsers();
}
private static RestClient InitializeAndGetClient()
{
var cookieJar = new CookieContainer();
var options = new RestClientOptions("https://api.createsend.com")
{
Authenticator = new HttpBasicAuthenticator("7cb8625ed34fbc298521f66b9e491ec3df53859a892c92d3", "x")
};
return new RestClient(options);
}
private static JsonNode? GetOptOuts(string fromDate)
{
// Just outputs, need to revise possibly? who knows?
var client = InitializeAndGetClient();
var request = new RestRequest();
if (fromDate != "")
request = new RestRequest("api/v3.3/lists/3bb5109cdf3265eac26b3fa34ffae379/unsubscribed.json?date=" + fromDate);
else
request = new RestRequest("api/v3.3/lists/3bb5109cdf3265eac26b3fa34ffae379/unsubscribed.json");
var response = client.ExecuteGet(request);
return JsonSerializer.Deserialize<JsonNode>(response.Content!)!;
}
// GET ALL BOUNCED PEOPLE AT ONCE; https://www.campaignmonitor.com/api/v3-3/lists/#bounced-subscribers-2
// Output files are sent to {CurrentWorkingDirectory}\OptOutFetcher\bin\Debug\net8.0\Output
private static void GetBouncedUsers()
{
var client = InitializeAndGetClient();
// Get total number of bounces so we know how many pages (of 10k entries) to export
var request = new RestRequest(string.Format("api/v3.3/lists/{0}/stats.json", ListID));
var response = client.ExecuteGet(request);
var dict = JsonSerializer.Deserialize<Dictionary<string, dynamic>>(response.Content);
JsonElement countJson = dict["TotalBounces"];
var count = -1;
countJson.TryGetInt32(out count);
Console.WriteLine(count);
// Iterate over all bounces and write to file
var pageCount = count / 1000;
for (int pagesLeft = 1 + count / 1000; pagesLeft > 0; pagesLeft--)
{
var currentPageNumber = pageCount - pagesLeft + 1;
request = new RestRequest(string.Format("https://api.createsend.com/api/v3.3/lists/{0}/bounced.json?page={1}&pagesize=1000&orderfield=date&orderdirection=asc", ListID, "" + currentPageNumber));
response = client.ExecuteGet(request);
//string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine("Output", string.Format("BouncedUsersPage_{0}", "" + currentPageNumber))))
{
outputFile.WriteLine(response.Content);
}
}
}
}