Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleaned up code #114

Merged
merged 1 commit into from
Oct 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions HoradotTV.Console/AppSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class AppSettings
public string? LastPath { get; set; }
public string? SdarotUsername { get; set; }
public string? SdarotPassword { get; set; }
public bool ForceDownload { get; set; } = false;
public bool ForceDownload { get; set; }

private static AppSettings LoadSettings()
{
Expand All @@ -27,7 +27,7 @@ private static AppSettings LoadSettings()
public void Save()
{
var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, filePath);
File.WriteAllText(path, JsonSerializer.Serialize(this, options: new JsonSerializerOptions() { WriteIndented = true }));
File.WriteAllText(path, JsonSerializer.Serialize(this, options: new JsonSerializerOptions { WriteIndented = true }));
}

public void SaveCredentials(string username, string password)
Expand Down
15 changes: 3 additions & 12 deletions HoradotTV.Console/ExitHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ internal static class ExitHelper
public static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

public delegate bool EventHandler(CtrlType sig);
public static EventHandler? _handler;
private static EventHandler? _handler;
private static Action? func;

public enum CtrlType
Expand All @@ -21,24 +21,15 @@ public static void Initialize(Action shutDown)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
_handler += new EventHandler(Handler);
_handler += Handler;
_ = SetConsoleCtrlHandler(_handler, true);
func = shutDown;
}
}

public static bool Handler(CtrlType sig)
{
switch (sig)
{
case CtrlType.CTRL_C_EVENT:
case CtrlType.CTRL_LOGOFF_EVENT:
case CtrlType.CTRL_SHUTDOWN_EVENT:
case CtrlType.CTRL_CLOSE_EVENT:
default:
func?.Invoke();
break;
}
func?.Invoke();

return true;
}
Expand Down
1 change: 0 additions & 1 deletion HoradotTV.Console/IOHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ public static int InputInt(string s = "")
catch (FormatException)
{
Print("Please enter a number.");
continue;
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions HoradotTV.Console/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace HoradotTV.Console;

internal class Program
internal static class Program
{
private static SdarotDriver? driver;

Expand Down Expand Up @@ -279,7 +279,7 @@ private static int GetEpisodesAmount()

return failedEpisodes;
}
catch { }
catch { /* Every exception thrown */ }
finally
{
driver.ShutdownWebDriver();
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,13 @@ With some more features like retries on server errors, and division to folders.
The easiest way to use the console app is through the release on GitHub:

1. Go to the [releases](https://github.com/yairp03/HoradotTV/releases) page.

2. Download the latest `zip` file:
- If you have `.NET` installed, you can download the `HoradotTV.Console.zip`.
- If you don't know what `.NET` is, download the `HoradotTV.Console.WithRuntime.zip`.

3. Extract the zip.

4. Run the `HoradotTV.Console.exe` file.

#### Running With Visual Studio
Expand Down
16 changes: 16 additions & 0 deletions SdarotAPI/Extensions/IEnumerableExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace SdarotAPI.Extensions;

public static class IEnumerableExt
{
/// <summary>
/// Wraps this object instance into an IEnumerable&lt;T&gt;
/// consisting of a single item.
/// </summary>
/// <typeparam name="T"> Type of the object. </typeparam>
/// <param name="item"> The instance that will be wrapped. </param>
/// <returns> An IEnumerable&lt;T&gt; consisting of a single item. </returns>
public static IEnumerable<T> Yield<T>(this T item)
{
yield return item;
}
}
19 changes: 12 additions & 7 deletions SdarotAPI/SdarotDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ public class SdarotDriver

public bool IsDriverInitialized => _webDriver is not null;

public SdarotDriver(bool headless = true, bool ignoreChecks = false)
public SdarotDriver() : this(false) { }

public SdarotDriver(bool ignoreChecks) : this(ignoreChecks, true) { }

public SdarotDriver(bool ignoreChecks, bool headless)
{
_headless = headless;

Expand Down Expand Up @@ -167,7 +171,7 @@ public async Task<IEnumerable<SeriesInformation>> SearchSeries(string searchQuer
// In case there is only one result
if (seriesNameElement is not null)
{
var seriesName = seriesNameElement.InnerText.Trim(new char[] { ' ', '/' });
var seriesName = seriesNameElement.InnerText.Trim(new[] { ' ', '/' });

var imageUrlElement = doc.DocumentNode.SelectSingleNode(Constants.XPathSelectors.SeriesPageSeriesImage);
if (imageUrlElement is null)
Expand All @@ -177,7 +181,7 @@ public async Task<IEnumerable<SeriesInformation>> SearchSeries(string searchQuer

var imageUrl = imageUrlElement.GetAttributeValue("src", "");

return new SeriesInformation[] { new(HttpUtility.HtmlDecode(seriesName), imageUrl) };
return new SeriesInformation(HttpUtility.HtmlDecode(seriesName), imageUrl).Yield();
}

var seriesElements = doc.DocumentNode.SelectNodes(Constants.XPathSelectors.SearchPageResult);
Expand Down Expand Up @@ -256,7 +260,7 @@ public async Task<IEnumerable<EpisodeInformation>> GetEpisodesAsync(EpisodeInfor
var seasonBuffer = new Queue<SeasonInformation>((await GetSeasonsAsync(firstEpisode.Season.Series)).ToArray()[(firstEpisode.Season.SeasonIndex + 1)..]);

List<EpisodeInformation> episodes = new();
for (var i = 0; i < maxEpisodeAmount; i++)
while (episodes.Count < maxEpisodeAmount)
{
if (episodesBuffer.Count == 0)
{
Expand All @@ -266,7 +270,6 @@ public async Task<IEnumerable<EpisodeInformation>> GetEpisodesAsync(EpisodeInfor
}

episodesBuffer = new(await GetEpisodesAsync(seasonBuffer.Dequeue()));
i--;
continue;
}

Expand All @@ -289,7 +292,9 @@ public async Task<IEnumerable<EpisodeInformation>> GetEpisodesAsync(SeriesInform
return episodes;
}

public async Task<EpisodeMediaDetails> GetEpisodeMediaDetailsAsync(EpisodeInformation episode, IProgress<float>? progress = null)
public async Task<EpisodeMediaDetails> GetEpisodeMediaDetailsAsync(EpisodeInformation episode) => await GetEpisodeMediaDetailsAsync(episode, null);

public async Task<EpisodeMediaDetails> GetEpisodeMediaDetailsAsync(EpisodeInformation episode, IProgress<float>? progress)
{
if (!IsDriverInitialized)
{
Expand All @@ -309,7 +314,7 @@ public async Task<EpisodeMediaDetails> GetEpisodeMediaDetailsAsync(EpisodeInform
}

var newSeconds = float.Parse(secondsLeft.Text);
if (newSeconds != currSeconds)
if (newSeconds < currSeconds)
{
currSeconds = newSeconds;
progress?.Report(30 - currSeconds);
Expand Down
10 changes: 7 additions & 3 deletions SdarotAPI/SdarotHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,13 @@ public static async Task<string> RetrieveSdarotDomain()

public static async Task<string> GetSdarotTestUrl() => $"https://{await RetrieveSdarotDomain()}/watch/1";

public static async Task DownloadEpisode(EpisodeMediaDetails episode, string downloadLocation, IProgress<long>? progress = null, CancellationToken ct = default)
public static async Task DownloadEpisode(EpisodeMediaDetails episode, string downloadLocation) => await DownloadEpisode(episode, downloadLocation, null);
public static async Task DownloadEpisode(EpisodeMediaDetails episode, string downloadLocation, IProgress<long>? progress) => await DownloadEpisode(episode, downloadLocation, progress, default);


public static async Task DownloadEpisode(EpisodeMediaDetails episode, string downloadLocation, IProgress<long>? progress, CancellationToken ct)
{
using var handler = new HttpClientHandler() { CookieContainer = episode.Cookies };
using var handler = new HttpClientHandler { CookieContainer = episode.Cookies };
using var client = new HttpClient(handler);
client.DefaultRequestHeaders.Add("User-Agent", Constants.UserAgent);
using var file = new FileStream(downloadLocation, FileMode.Create, FileAccess.Write, FileShare.None);
Expand All @@ -21,7 +25,7 @@ public static async Task DownloadEpisode(EpisodeMediaDetails episode, string dow

public static async Task<long?> GetEpisodeSize(EpisodeMediaDetails episode)
{
using var handler = new HttpClientHandler() { CookieContainer = episode.Cookies };
using var handler = new HttpClientHandler { CookieContainer = episode.Cookies };
using var client = new HttpClient(handler);
client.DefaultRequestHeaders.Add("User-Agent", Constants.UserAgent);
// Get the http headers first to examine the content length
Expand Down
2 changes: 1 addition & 1 deletion SdarotAPI/Services/ChromeDriverHelper.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace SdarotAPI.Services;

public class ChromeDriverHelper
public static class ChromeDriverHelper
{
private static readonly HttpClient httpClient = new()
{
Expand Down
10 changes: 4 additions & 6 deletions SdarotAPITest/ApiUnitTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ public async Task DriverInitTest()
Stopwatch sw = new();
sw.Start();

#pragma warning disable IDE0059 // Unnecessary assignment of a value
SdarotDriver driver = new(ignoreChecks: true);
#pragma warning restore IDE0059 // Unnecessary assignment of a value
_ = new SdarotDriver(true);

sw.Stop();

Expand All @@ -24,7 +22,7 @@ public async Task DriverInitTest()
[TestMethod]
public async Task SearchTest()
{
SdarotDriver driver = new(ignoreChecks: true);
SdarotDriver driver = new(true);

Trace.WriteLine($"No results: {(await MeasureSearch(driver, "dsakdjaslkfjsalkjfas")).TotalSeconds} seconds.");
Trace.WriteLine($"15 results: {(await MeasureSearch(driver, "שמש")).TotalSeconds} seconds.");
Expand All @@ -48,7 +46,7 @@ public static async Task<TimeSpan> MeasureSearch(SdarotDriver driver, string que
public async Task SeasonsTest()
{
await Task.Delay(500);
SdarotDriver driver = new(ignoreChecks: true);
SdarotDriver driver = new(true);

SeriesInformation series = new("איש משפחה / Family Guy", "static.sdarot.tw/series/1.jpg");

Expand All @@ -66,7 +64,7 @@ public async Task SeasonsTest()
public async Task EpisodesTest()
{
await Task.Delay(500);
SdarotDriver driver = new(ignoreChecks: true);
SdarotDriver driver = new(true);

SeriesInformation series = new("איש משפחה / Family Guy", "static.sdarot.tw/series/1.jpg");
SeasonInformation season = new(4, 3, "4", series);
Expand Down