Skip to content

Commit

Permalink
minor bug fixes
Browse files Browse the repository at this point in the history
breaking, changed IServiceCollection extension to IHostApplicationBuilder extension
  • Loading branch information
Agash committed Jun 2, 2024
1 parent 2d2d744 commit ff8f741
Show file tree
Hide file tree
Showing 7 changed files with 36 additions and 52 deletions.
2 changes: 0 additions & 2 deletions Common/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,4 @@

internal class Constants
{
public const string YTBaseUrl = "https://www.youtube.com";

}
2 changes: 1 addition & 1 deletion Contracts/Models/ChatItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,5 @@ public class ChatItem
/// <summary>
/// Timestamp of the ChatItem creation
/// </summary>
public DateTime Timestamp { get; set; } = DateTime.Now;
public DateTimeOffset Timestamp { get; set; } = DateTimeOffset.UtcNow;
}
24 changes: 11 additions & 13 deletions Contracts/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using YTLiveChat.Common;
using YTLiveChat.Contracts.Services;
using YTLiveChat.Services;

Expand All @@ -15,21 +14,20 @@ public static class ServiceCollectionExtensions
/// <summary>
/// Adds all relevant services as well as the Service backing IYTLiveChat to the ServiceCollection
/// </summary>
/// <param name="services">IServiceCollection to add the services to</param>
/// <param name="context">HostBuilderContext to get relevant Configuration to configure Options (YTLiveChatOptions)</param>
/// <param name="builder">IHostApplicationBuilder to add the services to</param>
/// <returns>return IServiceCollection after the services have been added</returns>
public static IServiceCollection AddYTLiveChat(this IServiceCollection services, HostBuilderContext context)
public static IHostApplicationBuilder AddYTLiveChat(this IHostApplicationBuilder builder)
{
_ = services.AddSingleton<IYTLiveChat, YTLiveChat.Services.YTLiveChat>();
_ = services.AddHttpClient<YTHttpClient>("YouTubeClient", (serviceProvider, httpClient) =>
_ = builder.Services.Configure<YTLiveChatOptions>(builder.Configuration.GetSection(nameof(YTLiveChatOptions)));

_ = builder.Services.AddSingleton<IYTLiveChat, YTLiveChat.Services.YTLiveChat>();
_ = builder.Services.AddHttpClient<YTHttpClient>("YouTubeClient", (serviceProvider, httpClient) =>
{
var ytChatOptions = serviceProvider.GetRequiredService<IOptions<YTLiveChatOptions>>().Value;
httpClient.BaseAddress = new Uri(ytChatOptions.YoutubeBaseUrl ?? Constants.YTBaseUrl);
YTLiveChatOptions ytChatOptions = serviceProvider.GetRequiredService<IOptions<YTLiveChatOptions>>().Value;
httpClient.BaseAddress = new Uri(ytChatOptions.YoutubeBaseUrl);
});
_ = services.AddSingleton<YTHttpClientFactory>();

_ = services.Configure<YTLiveChatOptions>(context.Configuration.GetSection(nameof(YTLiveChatOptions)));
_ = builder.Services.AddSingleton<YTHttpClientFactory>();

return services;
return builder;
}
}
}
12 changes: 3 additions & 9 deletions Contracts/YTLiveChatOptions.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YTLiveChat.Contracts;
namespace YTLiveChat.Contracts;

/// <summary>
/// Options from appsettings.json loaded in DI
Expand All @@ -15,10 +9,10 @@ public class YTLiveChatOptions
/// Base URL of YouTube
/// </summary>
/// <remarks>If not set, during DI initialization it'll default to: "https://www.youtube.com"</remarks>
public string? YoutubeBaseUrl { get; set; }
public string YoutubeBaseUrl { get; set; } = "https://www.youtube.com";

/// <summary>
/// Frequency of when (in milliseconds) the new batch of chat messages will be requested from YT servers, (i.e. every X milliseconds)
/// </summary>
public required int RequestFrequency { get; set; } = 1000;
public int RequestFrequency { get; set; } = 1000;
}
24 changes: 6 additions & 18 deletions Helpers/MessageRunConverter.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YTLiveChat.Helpers;
using System;
using System.Text.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using YTLiveChat.Models.Response;

namespace YTLiveChat.Helpers;
internal class MessageRunConverter : JsonConverter<MessageRun>
{
public override MessageRun? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
Expand All @@ -20,18 +13,13 @@ internal class MessageRunConverter : JsonConverter<MessageRun>
{
return JsonSerializer.Deserialize<MessageEmoji>(doc.RootElement, options);
}
else if (doc.RootElement.TryGetProperty("text", out _))
{
return JsonSerializer.Deserialize<MessageText>(doc.RootElement, options);
}
else
{
throw new JsonException("Invalid MessageRun format.");
return doc.RootElement.TryGetProperty("text", out _)
? (MessageRun?)JsonSerializer.Deserialize<MessageText>(doc.RootElement, options)
: throw new JsonException("Invalid MessageRun format.");
}
}

public override void Write(Utf8JsonWriter writer, MessageRun value, JsonSerializerOptions options)
{
throw new NotImplementedException(); // Implement if needed
}
public override void Write(Utf8JsonWriter writer, MessageRun value, JsonSerializerOptions options) => throw new NotImplementedException(); // Implement if needed
}
1 change: 0 additions & 1 deletion Services/YTHttpClientFactory.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Microsoft.Extensions.DependencyInjection;

namespace YTLiveChat.Services;

internal class YTHttpClientFactory(IServiceProvider serviceProvider)
Expand Down
23 changes: 15 additions & 8 deletions Services/YTLiveChat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ internal class YTLiveChat(IOptions<YTLiveChatOptions> options, YTHttpClientFacto

public void Start(string? handle = null, string? channelId = null, string? liveId = null, bool overwrite = false)
{
if(_cancellationTokenSource == null || _cancellationTokenSource.IsCancellationRequested)
if (_cancellationTokenSource == null || _cancellationTokenSource.IsCancellationRequested)
{
_cancellationTokenSource = new CancellationTokenSource();
_ = Task.Run(async () => await StartAsync(handle, channelId, liveId, overwrite, _cancellationTokenSource.Token));
Expand All @@ -45,16 +45,23 @@ private async Task StartAsync(string? handle = null, string? channelId = null, s
using PeriodicTimer timer = new(TimeSpan.FromMilliseconds(_options.Value.RequestFrequency));
while (await timer.WaitForNextTickAsync(cancellationToken))
{
Models.Response.GetLiveChatResponse? response = await httpClient.GetLiveChatAsync(options);
if (response != null)
try
{
(List<Contracts.Models.ChatItem> items, string continuation) = Parser.ParseGetLiveChatResponse(response);
foreach (Contracts.Models.ChatItem item in items)
Models.Response.GetLiveChatResponse? response = await httpClient.GetLiveChatAsync(options);
if (response != null)
{
OnChatReceived(new() { ChatItem = item });
}
(List<Contracts.Models.ChatItem> items, string continuation) = Parser.ParseGetLiveChatResponse(response);
foreach (Contracts.Models.ChatItem item in items)
{
OnChatReceived(new() { ChatItem = item });
}

options.Continuation = continuation;
options.Continuation = continuation;
}
}
catch (Exception ex)
{
OnErrorOccurred(new ErrorOccurredEventArgs(ex));
}
}
}
Expand Down

0 comments on commit ff8f741

Please sign in to comment.