Skip to content

Commit

Permalink
clean up code
Browse files Browse the repository at this point in the history
  • Loading branch information
Dyvinia committed Sep 25, 2024
1 parent cda04cd commit 0bea196
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 35 deletions.
8 changes: 4 additions & 4 deletions App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public class Config : SettingsManager<Config> {

public string DiscordClientID { get; set; } = "1100233636491563069";

public string PlexAddress { get; set; } = String.Empty;
public string PlexAddress { get; set; } = string.Empty;
}


Expand All @@ -56,7 +56,7 @@ public partial class App : Application {

public static string? Token { get; set; }
public static PlexAccount? Account { get; set; }
public static Resource[]? PlexResources { get; set; }
public static PlexResource[]? PlexResources { get; set; }

public static LogWriter? Log { get; set; }

Expand Down Expand Up @@ -123,7 +123,7 @@ private static async Task PlexSignIn(bool resignIn = false) {

try {
Account = await AccountClient.GetPlexAccountAsync(Token);
PlexResources = await Resource.GetAccountResources();
PlexResources = await PlexResource.GetAccountResources();
}
catch {
_ = PlexSignIn(true);
Expand All @@ -138,7 +138,7 @@ private static async Task<string> PlexOAuth() {

while (true) {
plexPin = await AccountClient.GetAuthTokenFromOAuthPinAsync(oauthUrl.Id.ToString());
if (!String.IsNullOrEmpty(plexPin.AuthToken)) break;
if (!string.IsNullOrEmpty(plexPin.AuthToken)) break;
await Task.Delay(1000);
}
return plexPin.AuthToken;
Expand Down
46 changes: 24 additions & 22 deletions Resource.cs → PlexResource.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace PlexampRPC {
public class Connection {
public class PlexConnection {
[JsonPropertyName("protocol")]
public string? Protocol { get; set; }

Expand All @@ -31,7 +30,7 @@ public class Connection {
public bool IPv6 { get; set; }
}

public class Resource {
public class PlexResource {
[JsonPropertyName("name")]
public string? Name { get; set; }

Expand Down Expand Up @@ -102,11 +101,11 @@ public class Resource {
public bool NatLoopbackSupported { get; set; }

[JsonPropertyName("connections")]
public IList<Connection>? Connections { get; set; }
public IList<PlexConnection>? Connections { get; set; }
public Uri? LocalUri { get; set; }
public Uri? Uri { get; set; }

public static async Task<Resource[]?> GetAccountResources() {
public static async Task<PlexResource[]?> GetAccountResources() {
try {
HttpRequestMessage requestMessage = new(HttpMethod.Get, $"https://plex.tv/api/v2/resources?includeHttps=1&includeIPv6=1&X-Plex-Token={App.Token}&X-Plex-Client-Identifier=PlexampRPC");
requestMessage.Headers.Add("Accept", "application/json");
Expand All @@ -115,43 +114,44 @@ public class Resource {
sendResponse.EnsureSuccessStatusCode();

JsonDocument responseJson = JsonDocument.Parse(await sendResponse.Content.ReadAsStringAsync());
Resource[]? sourceResources = JsonSerializer.Deserialize<Resource[]>(responseJson.RootElement);
List<Resource>? filteredResources = new();
if (sourceResources == null || sourceResources.Length == 0) {
PlexResource[]? sourceResources = JsonSerializer.Deserialize<PlexResource[]>(responseJson.RootElement);
List<PlexResource>? filteredResources = new();
if (sourceResources is null || sourceResources.Length == 0) {
Console.WriteLine("WARN: No servers found");
return null;
}

int i = 1;
foreach (Resource resource in sourceResources) {
foreach (PlexResource resource in sourceResources) {
if (Config.Settings.OwnedOnly && !resource.Owned)
continue;
MainWindow.UserNameText = $"Testing {i}/{sourceResources.Length}";
Resource? r = await testResource(resource);
if (r != null)
PlexResource? r = await TestResource(resource);
if (r is not null)
filteredResources.Add(r);
i += 1;
i++;
}

return filteredResources.ToArray();
} catch (Exception e) {
}
catch (Exception e) {
Console.WriteLine($"WARN: Unable to get resource: {e.Message} {e.InnerException}");
return null;
}
}

private static async Task<Resource?> testResource(Resource resource) {
private static async Task<PlexResource?> TestResource(PlexResource resource) {
if (!(resource.Provides ?? "").Split(",").Contains("server")) {
Console.WriteLine($"INFO: Skipping {resource.Name}/{resource.Product}, not a server");
return null;
}
foreach (Connection connection in resource.Connections ?? Enumerable.Empty<Connection>()) {
foreach (PlexConnection connection in resource.Connections ?? Enumerable.Empty<PlexConnection>()) {
MainWindow.UserNameText += ".";
Uri Uri;
if (connection.Local)
Uri = new UriBuilder("http", connection.Address, connection.Port).Uri;
else if (!Config.Settings.LocalAddress)
Uri = new UriBuilder(connection.Uri).Uri;
Uri = new UriBuilder(connection.Uri!).Uri;
else
continue;

Expand All @@ -172,21 +172,23 @@ public class Resource {
resource.LocalUri ??= Uri;
else
resource.Uri ??= Uri;
if (resource.LocalUri != null && resource.Uri != null) {
if (resource.LocalUri is not null && resource.Uri is not null) {
break;
}
} catch (TaskCanceledException) {
}
catch (TaskCanceledException) {
Console.WriteLine($"WARN: Timeout {(connection.Local ? 'L' : 'R')} {Uri}status/sessions?X-Plex-Token={resource.AccessToken?[..3]}...");
// Unreachable server, skip for now
} catch (HttpRequestException e) {
}
catch (HttpRequestException e) { // Unreachable server, skip for now
Console.WriteLine($"WARN: Unable to access {Uri}status/sessions?X-Plex-Token={resource.AccessToken?[..3]}: {e.Message}");
Console.WriteLine($"INFO: Adding {Uri} to Skipped list in config.json");
Config.Settings.Skipped.Add($"{Uri}");
} catch (Exception e) {
}
catch (Exception e) {
Console.WriteLine($"WARN: Unable to get resource: {e.Message} {e.InnerException}");
}
}
if (resource.LocalUri == null && resource.Uri == null)
if (resource.LocalUri is null && resource.Uri is null)
return null;
return resource;
}
Expand Down
4 changes: 2 additions & 2 deletions PlexampRPC.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
<UseWPF>true</UseWPF>

<AssemblyName>PlexampRPC</AssemblyName>
<Version>1.4.1</Version>
<Copyright>Copyright © 2023 Dyvinia</Copyright>
<Version>1.5.0</Version>
<Copyright>Copyright © 2024 Dyvinia</Copyright>
<Company>Dyvinia</Company>
<ApplicationIcon>Resources\Icon.ico</ApplicationIcon>
</PropertyGroup>
Expand Down
6 changes: 3 additions & 3 deletions Utils/Dialogs/ExceptionDialog.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace DyviniaUtils.Dialogs {
/// Interaction logic for ExceptionWindow.xaml
/// </summary>
public partial class ExceptionDialog : Window {
public ExceptionDialog(Exception ex, string title, string messagePrefix, bool isCrash) {
public ExceptionDialog(Exception ex, string title, string? messagePrefix, bool isCrash) {
InitializeComponent();

Title = title;
Expand Down Expand Up @@ -39,7 +39,7 @@ public ExceptionDialog(Exception ex, string title, string messagePrefix, bool is
CopyButton.Click += (s, e) => Clipboard.SetDataObject(message);
}

public static void Show(Exception ex, string title, string messagePrefix = null, bool isCrash = false) {
public static void Show(Exception ex, string title, string? messagePrefix = null, bool isCrash = false) {
Application.Current.Dispatcher.Invoke(() => {
ExceptionDialog window = new(ex, title, messagePrefix, isCrash);
window.ShowDialog();
Expand All @@ -49,7 +49,7 @@ public static void Show(Exception ex, string title, string messagePrefix = null,
public static void UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) {
e.Handled = true;
Application.Current.Dispatcher.Invoke(() => {
ExceptionDialog window = new(e.Exception, Assembly.GetEntryAssembly().GetName().Name, null, true);
ExceptionDialog window = new(e.Exception, Assembly.GetEntryAssembly()?.GetName().Name ?? "Exception", null, true);
window.ShowDialog();
});
}
Expand Down
8 changes: 4 additions & 4 deletions Windows/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ public Uri? Address {
return new UriBuilder(Config.Settings.PlexAddress).Uri;
else if (UserServerComboBox.SelectedItem != null) {
if (Config.Settings.LocalAddress)
return ((Resource)UserServerComboBox.SelectedItem).LocalUri;
return ((PlexResource)UserServerComboBox.SelectedItem).LocalUri;
else
return ((Resource)UserServerComboBox.SelectedItem).Uri;
return ((PlexResource)UserServerComboBox.SelectedItem).Uri;
}
return null;
}
Expand All @@ -41,7 +41,7 @@ public Uri? Address {
public string? Token {
get {
if (UserServerComboBox.SelectedItem != null)
return ((Resource)UserServerComboBox.SelectedItem).AccessToken;
return ((PlexResource)UserServerComboBox.SelectedItem).AccessToken;
return null;
}
}
Expand Down Expand Up @@ -234,7 +234,7 @@ private void SetPresence(PresenceData presence) {
LargeImageText = presence.ImageTooltip
},
Buttons = presence.Url != null ? new Button[] {
new Button() { Label = "More...", Url = presence.Url }
new() { Label = "More...", Url = presence.Url }
} : null
});

Expand Down

0 comments on commit 0bea196

Please sign in to comment.