add simple sdk sample

This commit is contained in:
crobibero 2021-04-22 11:11:59 -06:00
parent 17badf2c56
commit 7b55af4b62
3 changed files with 232 additions and 0 deletions

71
samples/Simple/Program.cs Normal file
View File

@ -0,0 +1,71 @@
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using Jellyfin.Sdk;
using Microsoft.Extensions.DependencyInjection;
namespace Simple
{
internal static class Program
{
private static async Task Main()
{
var serviceProvider = ConfigureServices();
// Initialize the sdk client settings. This only needs to happen once on startup.
var sdkClientSettings = serviceProvider.GetRequiredService<SdkClientSettings>();
sdkClientSettings.InitializeClientSettings(
"My-Jellyfin-Client",
"0.0.1",
"Sample Device",
$"this-is-my-device-id-{Guid.NewGuid():N}");
var sampleService = serviceProvider.GetRequiredService<SampleService>();
await sampleService.RunAsync()
.ConfigureAwait(false);
Console.WriteLine("Sample complete");
}
private static ServiceProvider ConfigureServices()
{
var serviceCollection = new ServiceCollection();
// Add Http Client
serviceCollection.AddHttpClient("Default", c =>
{
c.DefaultRequestHeaders.UserAgent.Add(
new ProductInfoHeaderValue(
"My-Jellyfin-Client",
"0.0.1"));
c.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json, 1.0));
c.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("*/*", 0.8));
})
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
AutomaticDecompression = DecompressionMethods.All,
RequestHeaderEncodingSelector = (_, _) => Encoding.UTF8
});
// Add Jellyfin SDK services.
serviceCollection
.AddSingleton<SdkClientSettings>()
.AddScoped<ISystemClient, SystemClient>()
.AddScoped<IUserClient, UserClient>()
.AddScoped<IUserViewsClient, UserViewsClient>()
.AddScoped<IUserLibraryClient, UserLibraryClient>();
// Add sample service
serviceCollection.AddSingleton<SampleService>();
return serviceCollection.BuildServiceProvider();
}
}
}

View File

@ -0,0 +1,136 @@
using System;
using System.Threading.Tasks;
using Jellyfin.Sdk;
using SystemException = Jellyfin.Sdk.SystemException;
namespace Simple
{
/// <summary>
/// Sample Jellyfin service.
/// </summary>
public class SampleService
{
private readonly SdkClientSettings _sdkClientSettings;
private readonly ISystemClient _systemClient;
private readonly IUserClient _userClient;
private readonly IUserViewsClient _userViewsClient;
/// <summary>
/// Initializes a new instance of the <see cref="SampleService"/> class.
/// </summary>
/// <param name="sdkClientSettings">Instance of the <see cref="_sdkClientSettings"/>.</param>
/// <param name="systemClient">Instance of the <see cref="ISystemClient"/> interface.</param>
/// <param name="userClient">Instance of the <see cref="IUserClient"/> interface.</param>
/// <param name="userViewsClient">Instance of the <see cref="IUserViewsClient"/> interface.</param>
public SampleService(
SdkClientSettings sdkClientSettings,
ISystemClient systemClient,
IUserClient userClient,
IUserViewsClient userViewsClient)
{
_sdkClientSettings = sdkClientSettings;
_systemClient = systemClient;
_userClient = userClient;
_userViewsClient = userViewsClient;
}
/// <summary>
/// Run the sample.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task RunAsync()
{
var validServer = false;
do
{
// Prompt for server url.
// Url must be proto://host/path
// ex: https://demo.jellyfin.org/stable
Console.Write("Server Url: ");
var host = Console.ReadLine();
_sdkClientSettings.BaseUrl = host;
try
{
// Get public system info to verify that the url points to a Jellyfin server.
var systemInfo = await _systemClient.GetPublicSystemInfoAsync()
.ConfigureAwait(false);
validServer = true;
Console.WriteLine($"Connected to {host}");
Console.WriteLine($"Server Name: {systemInfo.ServerName}");
Console.WriteLine($"Server Version: {systemInfo.Version}");
}
catch (InvalidOperationException ex)
{
Console.Error.WriteLine("Invalid url");
Console.Error.WriteLine(ex);
}
catch (SystemException ex)
{
Console.Error.WriteLine($"Error connecting to {host}");
Console.Error.WriteLine(ex);
}
}
while (!validServer);
var validUser = false;
UserDto userDto = null!;
do
{
try
{
Console.Write("Username: ");
var username = Console.ReadLine();
Console.Write("Password: ");
var password = Console.ReadLine();
Console.WriteLine($"Logging into {_sdkClientSettings.BaseUrl}");
// Authenticate user.
var authenticationResult = await _userClient.AuthenticateUserByNameAsync(new AuthenticateUserByName
{
Username = username,
Pw = password
})
.ConfigureAwait(false);
_sdkClientSettings.AccessToken = authenticationResult.AccessToken;
userDto = authenticationResult.User;
Console.WriteLine("Authentication success.");
Console.WriteLine($"Welcome to Jellyfin - {userDto.Name}");
validUser = true;
}
catch (UserException ex)
{
Console.Error.WriteLine("Error authenticating.");
Console.Error.WriteLine(ex);
}
}
while (!validUser);
await PrintViews(userDto.Id)
.ConfigureAwait(false);
}
private async Task PrintViews(Guid userId)
{
try
{
var views = await _userViewsClient.GetUserViewsAsync(userId)
.ConfigureAwait(false);
Console.WriteLine("Printing Views:");
foreach (var view in views.Items)
{
Console.WriteLine($"{view.Id} - {view.Name}");
}
}
catch (UserViewsException ex)
{
Console.Error.WriteLine("Error getting user views");
Console.Error.WriteLine(ex);
}
}
}
}

View File

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Nullable>enable</Nullable>
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
<CodeAnalysisRuleSet>..\..\jellyfin.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Jellyfin.Sdk" Version="10.7.2.2" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.1" />
<PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
<PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
</ItemGroup>
</Project>