Files
sbt-downloader/Program.cs

77 lines
2.5 KiB
C#

using PowerArgs;
using Newtonsoft.Json.Linq;
using System.Net;
namespace SBT_Downloader
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to the Sound Booth Theater Personal Archiving Tool!");
try
{
var parsed = Args.Parse<MyArgs>(args);
Console.WriteLine("Downloading book now...");
DownloadBook(parsed.Har);
}
catch (ArgException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ArgUsage.GenerateUsageFromTemplate<MyArgs>());
}
}
static void DownloadBook(string fileName)
{
string harContents = LoadHar(fileName);
JObject harObject = JObject.Parse(harContents);
List<string> mp3Urls = ParseUrls(harObject);
_ = DownloadMp3sAsync(mp3Urls);
}
private static async Task DownloadMp3sAsync(List<string> mp3Urls)
{
int fileNumber = 1;
foreach (string url in mp3Urls)
{
using var client = new WebClient();
client.DownloadFile(url, "file" + fileNumber + ".mp3");
Console.WriteLine("Downloading file #" + fileNumber);
fileNumber++;
}
}
static string LoadHar(string harFileName)
{
string harContents;
try
{
using StreamReader streamReader = new(harFileName);
harContents = streamReader.ReadToEnd();
return harContents;
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
Environment.Exit(0);
return string.Empty;
}
}
static List<string> ParseUrls(JObject harObject)
{
List<string> urls = harObject["log"]["entries"]
.Where(x => x.SelectToken("_resourceType").ToString() == "media")
.Select(y => y.SelectToken("request"))
.DistinctBy(z => z.SelectToken("url"))
.Select(x => x.SelectToken("url").ToString()).ToList();
Console.WriteLine(urls.Count + " total requests");
return urls;
}
}
}