build: repack to one dll assembly

This commit is contained in:
cxfksword 2023-07-14 14:15:30 +08:00
parent 41293f00e4
commit 4ee8e53705
267 changed files with 34 additions and 10478 deletions

View File

@ -1,15 +1,6 @@
using System.Reflection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Jellyfin.Plugin.MetaShark.Api; using Jellyfin.Plugin.MetaShark.Api;
using Jellyfin.Plugin.MetaShark.Core; using Jellyfin.Plugin.MetaShark.Core;
using Jellyfin.Plugin.MetaShark.Model;
using Jellyfin.Plugin.MetaShark.Providers;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace Jellyfin.Plugin.MetaShark.Test namespace Jellyfin.Plugin.MetaShark.Test
{ {

View File

@ -1,15 +1,5 @@
using System.Reflection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Jellyfin.Plugin.MetaShark.Api; using Jellyfin.Plugin.MetaShark.Api;
using Jellyfin.Plugin.MetaShark.Core;
using Jellyfin.Plugin.MetaShark.Model;
using Jellyfin.Plugin.MetaShark.Providers;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace Jellyfin.Plugin.MetaShark.Test namespace Jellyfin.Plugin.MetaShark.Test
{ {

View File

@ -8,7 +8,7 @@ using Jellyfin.Plugin.MetaShark.Core;
using Jellyfin.Plugin.MetaShark.Model; using Jellyfin.Plugin.MetaShark.Model;
using Jellyfin.Plugin.MetaShark.Providers; using Jellyfin.Plugin.MetaShark.Providers;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace Jellyfin.Plugin.MetaShark.Test namespace Jellyfin.Plugin.MetaShark.Test
{ {

View File

@ -40,7 +40,7 @@ namespace Jellyfin.Plugin.MetaShark.Api
var apiKey = string.IsNullOrEmpty(config?.TmdbApiKey) ? DEFAULT_API_KEY : config.TmdbApiKey; var apiKey = string.IsNullOrEmpty(config?.TmdbApiKey) ? DEFAULT_API_KEY : config.TmdbApiKey;
var host = string.IsNullOrEmpty(config?.TmdbHost) ? DEFAULT_API_HOST : config.TmdbHost; var host = string.IsNullOrEmpty(config?.TmdbHost) ? DEFAULT_API_HOST : config.TmdbHost;
_tmDbClient = new TMDbClient(apiKey, true, host); _tmDbClient = new TMDbClient(apiKey, true, host);
_tmDbClient.RequestTimeout = TimeSpan.FromSeconds(10); _tmDbClient.Timeout = TimeSpan.FromSeconds(10);
// Not really interested in NotFoundException // Not really interested in NotFoundException
_tmDbClient.ThrowApiExceptions = false; _tmDbClient.ThrowApiExceptions = false;
} }

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="ILRepacker" AfterTargets="Build" Condition="'$(Configuration)'=='Release' or '$(Configuration)'=='Debug'">
<PropertyGroup>
<DoILRepack>false</DoILRepack>
</PropertyGroup>
<ItemGroup>
<InputAssemblies Include="$(OutputPath)$(AssemblyName).dll" />
<InputAssemblies Include="$(OutputPath)publish/RateLimiter.dll" />
<InputAssemblies Include="$(OutputPath)publish/ComposableAsync.Core.dll" />
<InputAssemblies Include="$(OutputPath)publish/TMDbLib.dll" />
<InputAssemblies Include="$(OutputPath)publish/Newtonsoft.Json.dll" />
<InputAssemblies Include="$(OutputPath)publish/AngleSharp.dll" />
</ItemGroup>
<ILRepack
Parallel="false"
Internalize="true"
DebugInfo="true"
InputAssemblies="@(InputAssemblies)"
LibraryPath="$(OutputPath)"
TargetKind="Dll"
OutputFile="$(OutputPath)$(AssemblyName).dll"
/>
</Target>
</Project>

View File

@ -15,9 +15,12 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AngleSharp" Version="1.0.1" /> <PackageReference Include="AngleSharp" Version="1.0.1" />
<PackageReference Include="ILRepack.Lib.MSBuild" Version="2.1.18" />
<PackageReference Include="Jellyfin.Controller" Version="10.8.0" /> <PackageReference Include="Jellyfin.Controller" Version="10.8.0" />
<PackageReference Include="Jellyfin.Model" Version="10.8.0" /> <PackageReference Include="Jellyfin.Model" Version="10.8.0" />
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" /> <PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
<PackageReference Include="RateLimiter" Version="2.2.0" />
<PackageReference Include="TMDbLib" Version="2.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" /> <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />

View File

@ -1,11 +1,8 @@
using MediaBrowser.Model.Entities; using System;
using Newtonsoft.Json;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.Linq; using System.Linq;
using System.Text; using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace Jellyfin.Plugin.MetaShark.Model namespace Jellyfin.Plugin.MetaShark.Model
{ {

View File

@ -1,4 +0,0 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("ComposableAsync.Core.Test")]

View File

@ -1,43 +0,0 @@
using System;
using System.Runtime.CompilerServices;
using System.Security;
namespace ComposableAsync
{
/// <summary>
/// Dispatcher awaiter, making a dispatcher awaitable
/// </summary>
public struct DispatcherAwaiter : INotifyCompletion
{
/// <summary>
/// Dispatcher never is synchronous
/// </summary>
public bool IsCompleted => false;
private readonly IDispatcher _Dispatcher;
/// <summary>
/// Construct a NotifyCompletion fom a dispatcher
/// </summary>
/// <param name="dispatcher"></param>
public DispatcherAwaiter(IDispatcher dispatcher)
{
_Dispatcher = dispatcher;
}
/// <summary>
/// Dispatch on complete
/// </summary>
/// <param name="continuation"></param>
[SecuritySafeCritical]
public void OnCompleted(Action continuation)
{
_Dispatcher.Dispatch(continuation);
}
/// <summary>
/// No Result
/// </summary>
public void GetResult() { }
}
}

View File

@ -1,30 +0,0 @@
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace ComposableAsync
{
/// <summary>
/// A <see cref="DelegatingHandler"/> implementation based on <see cref="IDispatcher"/>
/// </summary>
internal class DispatcherDelegatingHandler : DelegatingHandler
{
private readonly IDispatcher _Dispatcher;
/// <summary>
/// Build an <see cref="DelegatingHandler"/> from a <see cref="IDispatcher"/>
/// </summary>
/// <param name="dispatcher"></param>
public DispatcherDelegatingHandler(IDispatcher dispatcher)
{
_Dispatcher = dispatcher;
InnerHandler = new HttpClientHandler();
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
return _Dispatcher.Enqueue(() => base.SendAsync(request, cancellationToken), cancellationToken);
}
}
}

View File

@ -1,73 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ComposableAsync
{
internal class ComposedDispatcher : IDispatcher, IAsyncDisposable
{
private readonly IDispatcher _First;
private readonly IDispatcher _Second;
public ComposedDispatcher(IDispatcher first, IDispatcher second)
{
_First = first;
_Second = second;
}
public void Dispatch(Action action)
{
_First.Dispatch(() => _Second.Dispatch(action));
}
public async Task Enqueue(Action action)
{
await _First.Enqueue(() => _Second.Enqueue(action));
}
public async Task<T> Enqueue<T>(Func<T> action)
{
return await _First.Enqueue(() => _Second.Enqueue(action));
}
public async Task Enqueue(Func<Task> action)
{
await _First.Enqueue(() => _Second.Enqueue(action));
}
public async Task<T> Enqueue<T>(Func<Task<T>> action)
{
return await _First.Enqueue(() => _Second.Enqueue(action));
}
public async Task Enqueue(Func<Task> action, CancellationToken cancellationToken)
{
await _First.Enqueue(() => _Second.Enqueue(action, cancellationToken), cancellationToken);
}
public async Task<T> Enqueue<T>(Func<Task<T>> action, CancellationToken cancellationToken)
{
return await _First.Enqueue(() => _Second.Enqueue(action, cancellationToken), cancellationToken);
}
public async Task<T> Enqueue<T>(Func<T> action, CancellationToken cancellationToken)
{
return await _First.Enqueue(() => _Second.Enqueue(action, cancellationToken), cancellationToken);
}
public async Task Enqueue(Action action, CancellationToken cancellationToken)
{
await _First.Enqueue(() => _Second.Enqueue(action, cancellationToken), cancellationToken);
}
public IDispatcher Clone() => new ComposedDispatcher(_First, _Second);
public Task DisposeAsync()
{
return Task.WhenAll(DisposeAsync(_First), DisposeAsync(_Second));
}
private static Task DisposeAsync(IDispatcher disposable) => (disposable as IAsyncDisposable)?.DisposeAsync() ?? Task.CompletedTask;
}
}

View File

@ -1,63 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ComposableAsync
{
internal class DispatcherAdapter : IDispatcher
{
private readonly IBasicDispatcher _BasicDispatcher;
public DispatcherAdapter(IBasicDispatcher basicDispatcher)
{
_BasicDispatcher = basicDispatcher;
}
public IDispatcher Clone() => new DispatcherAdapter(_BasicDispatcher.Clone());
public void Dispatch(Action action)
{
_BasicDispatcher.Enqueue(action, CancellationToken.None);
}
public Task Enqueue(Action action)
{
return _BasicDispatcher.Enqueue(action, CancellationToken.None);
}
public Task<T> Enqueue<T>(Func<T> action)
{
return _BasicDispatcher.Enqueue(action, CancellationToken.None);
}
public Task Enqueue(Func<Task> action)
{
return _BasicDispatcher.Enqueue(action, CancellationToken.None);
}
public Task<T> Enqueue<T>(Func<Task<T>> action)
{
return _BasicDispatcher.Enqueue(action, CancellationToken.None);
}
public Task<T> Enqueue<T>(Func<T> action, CancellationToken cancellationToken)
{
return _BasicDispatcher.Enqueue(action, cancellationToken);
}
public Task Enqueue(Action action, CancellationToken cancellationToken)
{
return _BasicDispatcher.Enqueue(action, cancellationToken);
}
public Task Enqueue(Func<Task> action, CancellationToken cancellationToken)
{
return _BasicDispatcher.Enqueue(action, cancellationToken);
}
public Task<T> Enqueue<T>(Func<Task<T>> action, CancellationToken cancellationToken)
{
return _BasicDispatcher.Enqueue(action, cancellationToken);
}
}
}

View File

@ -1,74 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ComposableAsync
{
/// <summary>
/// <see cref="IDispatcher"/> that run actions synchronously
/// </summary>
public sealed class NullDispatcher: IDispatcher
{
private NullDispatcher() { }
/// <summary>
/// Returns a static null dispatcher
/// </summary>
public static IDispatcher Instance { get; } = new NullDispatcher();
/// <inheritdoc />
public void Dispatch(Action action)
{
action();
}
/// <inheritdoc />
public Task Enqueue(Action action)
{
action();
return Task.CompletedTask;
}
/// <inheritdoc />
public Task<T> Enqueue<T>(Func<T> action)
{
return Task.FromResult(action());
}
/// <inheritdoc />
public async Task Enqueue(Func<Task> action)
{
await action();
}
/// <inheritdoc />
public async Task<T> Enqueue<T>(Func<Task<T>> action)
{
return await action();
}
public Task<T> Enqueue<T>(Func<T> action, CancellationToken cancellationToken)
{
return Task.FromResult(action());
}
public Task Enqueue(Action action, CancellationToken cancellationToken)
{
action();
return Task.CompletedTask;
}
public async Task Enqueue(Func<Task> action, CancellationToken cancellationToken)
{
await action();
}
public async Task<T> Enqueue<T>(Func<Task<T>> action, CancellationToken cancellationToken)
{
return await action();
}
/// <inheritdoc />
public IDispatcher Clone() => Instance;
}
}

View File

@ -1,90 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
namespace ComposableAsync
{
/// <summary>
/// <see cref="IDispatcher"/> extension methods provider
/// </summary>
public static class DispatcherExtension
{
/// <summary>
/// Returns awaitable to enter in the dispatcher context
/// This extension method make a dispatcher awaitable
/// </summary>
/// <param name="dispatcher"></param>
/// <returns></returns>
public static DispatcherAwaiter GetAwaiter(this IDispatcher dispatcher)
{
return new DispatcherAwaiter(dispatcher);
}
/// <summary>
/// Returns a composed dispatcher applying the given dispatcher
/// after the first one
/// </summary>
/// <param name="dispatcher"></param>
/// <param name="other"></param>
/// <returns></returns>
public static IDispatcher Then(this IDispatcher dispatcher, IDispatcher other)
{
if (dispatcher == null)
throw new ArgumentNullException(nameof(dispatcher));
if (other == null)
throw new ArgumentNullException(nameof(other));
return new ComposedDispatcher(dispatcher, other);
}
/// <summary>
/// Returns a composed dispatcher applying the given dispatchers sequentially
/// </summary>
/// <param name="dispatcher"></param>
/// <param name="others"></param>
/// <returns></returns>
public static IDispatcher Then(this IDispatcher dispatcher, params IDispatcher[] others)
{
return dispatcher.Then((IEnumerable<IDispatcher>)others);
}
/// <summary>
/// Returns a composed dispatcher applying the given dispatchers sequentially
/// </summary>
/// <param name="dispatcher"></param>
/// <param name="others"></param>
/// <returns></returns>
public static IDispatcher Then(this IDispatcher dispatcher, IEnumerable<IDispatcher> others)
{
if (dispatcher == null)
throw new ArgumentNullException(nameof(dispatcher));
if (others == null)
throw new ArgumentNullException(nameof(others));
return others.Aggregate(dispatcher, (cum, val) => cum.Then(val));
}
/// <summary>
/// Create a <see cref="DelegatingHandler"/> from an <see cref="IDispatcher"/>
/// </summary>
/// <param name="dispatcher"></param>
/// <returns></returns>
public static DelegatingHandler AsDelegatingHandler(this IDispatcher dispatcher)
{
return new DispatcherDelegatingHandler(dispatcher);
}
/// <summary>
/// Create a <see cref="IDispatcher"/> from an <see cref="IBasicDispatcher"/>
/// </summary>
/// <param name="basicDispatcher"></param>
/// <returns></returns>
public static IDispatcher ToFullDispatcher(this IBasicDispatcher @basicDispatcher)
{
return new DispatcherAdapter(@basicDispatcher);
}
}
}

View File

@ -1,19 +0,0 @@
namespace ComposableAsync
{
/// <summary>
/// Dispatcher manager
/// </summary>
public interface IDispatcherManager : IAsyncDisposable
{
/// <summary>
/// true if the Dispatcher should be released
/// </summary>
bool DisposeDispatcher { get; }
/// <summary>
/// Returns a consumable Dispatcher
/// </summary>
/// <returns></returns>
IDispatcher GetDispatcher();
}
}

View File

@ -1,36 +0,0 @@
using System.Threading.Tasks;
namespace ComposableAsync
{
/// <summary>
/// <see cref="IDispatcherManager"/> implementation based on single <see cref="IDispatcher"/>
/// </summary>
public sealed class MonoDispatcherManager : IDispatcherManager
{
/// <inheritdoc cref="IDispatcherManager"/>
public bool DisposeDispatcher { get; }
/// <inheritdoc cref="IDispatcherManager"/>
public IDispatcher GetDispatcher() => _Dispatcher;
private readonly IDispatcher _Dispatcher;
/// <summary>
/// Create
/// </summary>
/// <param name="dispatcher"></param>
/// <param name="shouldDispose"></param>
public MonoDispatcherManager(IDispatcher dispatcher, bool shouldDispose = false)
{
_Dispatcher = dispatcher;
DisposeDispatcher = shouldDispose;
}
/// <inheritdoc cref="IDispatcherManager"/>
public Task DisposeAsync()
{
return DisposeDispatcher && (_Dispatcher is IAsyncDisposable disposable) ?
disposable.DisposeAsync() : Task.CompletedTask;
}
}
}

View File

@ -1,18 +0,0 @@
namespace ComposableAsync
{
/// <summary>
/// <see cref="IDispatcherProvider"/> extension
/// </summary>
public static class DispatcherProviderExtension
{
/// <summary>
/// Returns the underlying <see cref="IDispatcher"/>
/// </summary>
/// <param name="dispatcherProvider"></param>
/// <returns></returns>
public static IDispatcher GetAssociatedDispatcher(this IDispatcherProvider dispatcherProvider)
{
return dispatcherProvider?.Dispatcher ?? NullDispatcher.Instance;
}
}
}

View File

@ -1,48 +0,0 @@
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
namespace ComposableAsync
{
/// <summary>
/// <see cref="IAsyncDisposable"/> implementation aggregating other <see cref="IAsyncDisposable"/>
/// </summary>
public sealed class ComposableAsyncDisposable : IAsyncDisposable
{
private readonly ConcurrentQueue<IAsyncDisposable> _Disposables;
/// <summary>
/// Build an empty ComposableAsyncDisposable
/// </summary>
public ComposableAsyncDisposable()
{
_Disposables = new ConcurrentQueue<IAsyncDisposable>();
}
/// <summary>
/// Add an <see cref="IAsyncDisposable"/> to the ComposableAsyncDisposable
/// and returns it
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="disposable"></param>
/// <returns></returns>
public T Add<T>(T disposable) where T: IAsyncDisposable
{
if (disposable == null)
return default(T);
_Disposables.Enqueue(disposable);
return disposable;
}
/// <summary>
/// Dispose all the resources asynchronously
/// </summary>
/// <returns></returns>
public Task DisposeAsync()
{
var tasks = _Disposables.ToArray().Select(disposable => disposable.DisposeAsync()).ToArray();
return Task.WhenAll(tasks);
}
}
}

View File

@ -1,17 +0,0 @@
using System.Threading.Tasks;
namespace ComposableAsync
{
/// <summary>
/// Asynchronous version of IDisposable
/// For reference see discussion: https://github.com/dotnet/roslyn/issues/114
/// </summary>
public interface IAsyncDisposable
{
/// <summary>
/// Performs asynchronously application-defined tasks associated with freeing,
/// releasing, or resetting unmanaged resources.
/// </summary>
Task DisposeAsync();
}
}

View File

@ -1,57 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ComposableAsync
{
/// <summary>
/// Simplified version of <see cref="IDispatcher"/> that can be converted
/// to a <see cref="IDispatcher"/> using the ToFullDispatcher extension method
/// </summary>
public interface IBasicDispatcher
{
/// <summary>
/// Clone dispatcher
/// </summary>
/// <returns></returns>
IBasicDispatcher Clone();
/// <summary>
/// Enqueue the function and return a task corresponding
/// to the execution of the task
/// /// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="action"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<T> Enqueue<T>(Func<T> action, CancellationToken cancellationToken);
/// <summary>
/// Enqueue the action and return a task corresponding
/// to the execution of the task
/// </summary>
/// <param name="action"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task Enqueue(Action action, CancellationToken cancellationToken);
/// <summary>
/// Enqueue the task and return a task corresponding
/// to the execution of the task
/// </summary>
/// <param name="action"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task Enqueue(Func<Task> action, CancellationToken cancellationToken);
/// <summary>
/// Enqueue the task and return a task corresponding
/// to the execution of the original task
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="action"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<T> Enqueue<T>(Func<Task<T>> action, CancellationToken cancellationToken);
}
}

View File

@ -1,98 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ComposableAsync
{
/// <summary>
/// Dispatcher executes an action or a function
/// on its own context
/// </summary>
public interface IDispatcher
{
/// <summary>
/// Execute action on dispatcher context in a
/// none-blocking way
/// </summary>
/// <param name="action"></param>
void Dispatch(Action action);
/// <summary>
/// Enqueue the action and return a task corresponding to
/// the completion of the action
/// </summary>
/// <param name="action"></param>
/// <returns></returns>
Task Enqueue(Action action);
/// <summary>
/// Enqueue the function and return a task corresponding to
/// the result of the function
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="action"></param>
/// <returns></returns>
Task<T> Enqueue<T>(Func<T> action);
/// <summary>
/// Enqueue the task and return a task corresponding to
/// the completion of the task
/// </summary>
/// <param name="action"></param>
/// <returns></returns>
Task Enqueue(Func<Task> action);
/// <summary>
/// Enqueue the task and return a task corresponding
/// to the execution of the original task
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="action"></param>
/// <returns></returns>
Task<T> Enqueue<T>(Func<Task<T>> action);
/// <summary>
/// Enqueue the function and return a task corresponding
/// to the execution of the task
/// /// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="action"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<T> Enqueue<T>(Func<T> action, CancellationToken cancellationToken);
/// <summary>
/// Enqueue the action and return a task corresponding
/// to the execution of the task
/// </summary>
/// <param name="action"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task Enqueue(Action action, CancellationToken cancellationToken);
/// <summary>
/// Enqueue the task and return a task corresponding
/// to the execution of the task
/// </summary>
/// <param name="action"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task Enqueue(Func<Task> action, CancellationToken cancellationToken);
/// <summary>
/// Enqueue the task and return a task corresponding
/// to the execution of the original task
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="action"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<T> Enqueue<T>(Func<Task<T>> action, CancellationToken cancellationToken);
/// <summary>
/// Clone dispatcher
/// </summary>
/// <returns></returns>
IDispatcher Clone();
}
}

View File

@ -1,13 +0,0 @@
namespace ComposableAsync
{
/// <summary>
/// Returns the fiber associated with an actor
/// </summary>
public interface IDispatcherProvider
{
/// <summary>
/// Returns the corresponding <see cref="IDispatcher"/>
/// </summary>
IDispatcher Dispatcher { get; }
}
}

View File

@ -1,22 +0,0 @@
namespace RateLimiter
{
/// <summary>
/// Provides extension to interface <see cref="IAwaitableConstraint"/>
/// </summary>
public static class AwaitableConstraintExtension
{
/// <summary>
/// Compose two awaitable constraint in a new one
/// </summary>
/// <param name="awaitableConstraint1"></param>
/// <param name="awaitableConstraint2"></param>
/// <returns></returns>
public static IAwaitableConstraint Compose(this IAwaitableConstraint awaitableConstraint1, IAwaitableConstraint awaitableConstraint2)
{
if (awaitableConstraint1 == awaitableConstraint2)
return awaitableConstraint1;
return new ComposedAwaitableConstraint(awaitableConstraint1, awaitableConstraint2);
}
}
}

View File

@ -1,47 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace RateLimiter
{
internal class ComposedAwaitableConstraint : IAwaitableConstraint
{
private readonly IAwaitableConstraint _AwaitableConstraint1;
private readonly IAwaitableConstraint _AwaitableConstraint2;
private readonly SemaphoreSlim _Semaphore = new SemaphoreSlim(1, 1);
internal ComposedAwaitableConstraint(IAwaitableConstraint awaitableConstraint1, IAwaitableConstraint awaitableConstraint2)
{
_AwaitableConstraint1 = awaitableConstraint1;
_AwaitableConstraint2 = awaitableConstraint2;
}
public IAwaitableConstraint Clone()
{
return new ComposedAwaitableConstraint(_AwaitableConstraint1.Clone(), _AwaitableConstraint2.Clone());
}
public async Task<IDisposable> WaitForReadiness(CancellationToken cancellationToken)
{
await _Semaphore.WaitAsync(cancellationToken);
IDisposable[] disposables;
try
{
disposables = await Task.WhenAll(_AwaitableConstraint1.WaitForReadiness(cancellationToken), _AwaitableConstraint2.WaitForReadiness(cancellationToken));
}
catch (Exception)
{
_Semaphore.Release();
throw;
}
return new DisposeAction(() =>
{
foreach (var disposable in disposables)
{
disposable.Dispose();
}
_Semaphore.Release();
});
}
}
}

View File

@ -1,120 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace RateLimiter
{
/// <summary>
/// Provide an awaitable constraint based on number of times per duration
/// </summary>
public class CountByIntervalAwaitableConstraint : IAwaitableConstraint
{
/// <summary>
/// List of the last time stamps
/// </summary>
public IReadOnlyList<DateTime> TimeStamps => _TimeStamps.ToList();
/// <summary>
/// Stack of the last time stamps
/// </summary>
protected LimitedSizeStack<DateTime> _TimeStamps { get; }
private int _Count { get; }
private TimeSpan _TimeSpan { get; }
private SemaphoreSlim _Semaphore { get; } = new SemaphoreSlim(1, 1);
private ITime _Time { get; }
/// <summary>
/// Constructs a new AwaitableConstraint based on number of times per duration
/// </summary>
/// <param name="count"></param>
/// <param name="timeSpan"></param>
public CountByIntervalAwaitableConstraint(int count, TimeSpan timeSpan) : this(count, timeSpan, TimeSystem.StandardTime)
{
}
internal CountByIntervalAwaitableConstraint(int count, TimeSpan timeSpan, ITime time)
{
if (count <= 0)
throw new ArgumentException("count should be strictly positive", nameof(count));
if (timeSpan.TotalMilliseconds <= 0)
throw new ArgumentException("timeSpan should be strictly positive", nameof(timeSpan));
_Count = count;
_TimeSpan = timeSpan;
_TimeStamps = new LimitedSizeStack<DateTime>(_Count);
_Time = time;
}
/// <summary>
/// returns a task that will complete once the constraint is fulfilled
/// </summary>
/// <param name="cancellationToken">
/// Cancel the wait
/// </param>
/// <returns>
/// A disposable that should be disposed upon task completion
/// </returns>
public async Task<IDisposable> WaitForReadiness(CancellationToken cancellationToken)
{
await _Semaphore.WaitAsync(cancellationToken);
var count = 0;
var now = _Time.GetNow();
var target = now - _TimeSpan;
LinkedListNode<DateTime> element = _TimeStamps.First, last = null;
while ((element != null) && (element.Value > target))
{
last = element;
element = element.Next;
count++;
}
if (count < _Count)
return new DisposeAction(OnEnded);
Debug.Assert(element == null);
Debug.Assert(last != null);
var timeToWait = last.Value.Add(_TimeSpan) - now;
try
{
await _Time.GetDelay(timeToWait, cancellationToken);
}
catch (Exception)
{
_Semaphore.Release();
throw;
}
return new DisposeAction(OnEnded);
}
/// <summary>
/// Clone CountByIntervalAwaitableConstraint
/// </summary>
/// <returns></returns>
public IAwaitableConstraint Clone()
{
return new CountByIntervalAwaitableConstraint(_Count, _TimeSpan, _Time);
}
private void OnEnded()
{
var now = _Time.GetNow();
_TimeStamps.Push(now);
OnEnded(now);
_Semaphore.Release();
}
/// <summary>
/// Called when action has been executed
/// </summary>
/// <param name="now"></param>
protected virtual void OnEnded(DateTime now)
{
}
}
}

View File

@ -1,20 +0,0 @@
using System;
namespace RateLimiter
{
internal class DisposeAction : IDisposable
{
private Action _Act;
public DisposeAction(Action act)
{
_Act = act;
}
public void Dispose()
{
_Act?.Invoke();
_Act = null;
}
}
}

View File

@ -1,29 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace RateLimiter
{
/// <summary>
/// Represents a time constraints that can be awaited
/// </summary>
public interface IAwaitableConstraint
{
/// <summary>
/// returns a task that will complete once the constraint is fulfilled
/// </summary>
/// <param name="cancellationToken">
/// Cancel the wait
/// </param>
/// <returns>
/// A disposable that should be disposed upon task completion
/// </returns>
Task<IDisposable> WaitForReadiness(CancellationToken cancellationToken);
/// <summary>
/// Returns a new IAwaitableConstraint with same constraints but unused
/// </summary>
/// <returns></returns>
IAwaitableConstraint Clone();
}
}

View File

@ -1,26 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace RateLimiter
{
/// <summary>
/// Time abstraction
/// </summary>
internal interface ITime
{
/// <summary>
/// Return Now DateTime
/// </summary>
/// <returns></returns>
DateTime GetNow();
/// <summary>
/// Returns a task delay
/// </summary>
/// <param name="timespan"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task GetDelay(TimeSpan timespan, CancellationToken cancellationToken);
}
}

View File

@ -1,35 +0,0 @@
using System.Collections.Generic;
namespace RateLimiter
{
/// <summary>
/// LinkedList with a limited size
/// If the size exceeds the limit older entry are removed
/// </summary>
/// <typeparam name="T"></typeparam>
public class LimitedSizeStack<T>: LinkedList<T>
{
private readonly int _MaxSize;
/// <summary>
/// Construct the LimitedSizeStack with the given limit
/// </summary>
/// <param name="maxSize"></param>
public LimitedSizeStack(int maxSize)
{
_MaxSize = maxSize;
}
/// <summary>
/// Push new entry. If he size exceeds the limit, the oldest entry is removed
/// </summary>
/// <param name="item"></param>
public void Push(T item)
{
AddFirst(item);
if (Count > _MaxSize)
RemoveLast();
}
}
}

View File

@ -1,42 +0,0 @@
using System;
using System.Collections.Generic;
namespace RateLimiter
{
/// <summary>
/// <see cref="CountByIntervalAwaitableConstraint"/> that is able to save own state.
/// </summary>
public sealed class PersistentCountByIntervalAwaitableConstraint : CountByIntervalAwaitableConstraint
{
private readonly Action<DateTime> _SaveStateAction;
/// <summary>
/// Create an instance of <see cref="PersistentCountByIntervalAwaitableConstraint"/>.
/// </summary>
/// <param name="count">Maximum actions allowed per time interval.</param>
/// <param name="timeSpan">Time interval limits are applied for.</param>
/// <param name="saveStateAction">Action is used to save state.</param>
/// <param name="initialTimeStamps">Initial timestamps.</param>
public PersistentCountByIntervalAwaitableConstraint(int count, TimeSpan timeSpan,
Action<DateTime> saveStateAction, IEnumerable<DateTime> initialTimeStamps) : base(count, timeSpan)
{
_SaveStateAction = saveStateAction;
if (initialTimeStamps == null)
return;
foreach (var timeStamp in initialTimeStamps)
{
_TimeStamps.Push(timeStamp);
}
}
/// <summary>
/// Save state
/// </summary>
protected override void OnEnded(DateTime now)
{
_SaveStateAction(now);
}
}
}

View File

@ -1,206 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ComposableAsync;
namespace RateLimiter
{
/// <summary>
/// TimeLimiter implementation
/// </summary>
public class TimeLimiter : IDispatcher
{
private readonly IAwaitableConstraint _AwaitableConstraint;
internal TimeLimiter(IAwaitableConstraint awaitableConstraint)
{
_AwaitableConstraint = awaitableConstraint;
}
/// <summary>
/// Perform the given task respecting the time constraint
/// returning the result of given function
/// </summary>
/// <param name="perform"></param>
/// <returns></returns>
public Task Enqueue(Func<Task> perform)
{
return Enqueue(perform, CancellationToken.None);
}
/// <summary>
/// Perform the given task respecting the time constraint
/// returning the result of given function
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="perform"></param>
/// <returns></returns>
public Task<T> Enqueue<T>(Func<Task<T>> perform)
{
return Enqueue(perform, CancellationToken.None);
}
/// <summary>
/// Perform the given task respecting the time constraint
/// </summary>
/// <param name="perform"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task Enqueue(Func<Task> perform, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
using (await _AwaitableConstraint.WaitForReadiness(cancellationToken))
{
await perform();
}
}
/// <summary>
/// Perform the given task respecting the time constraint
/// returning the result of given function
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="perform"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<T> Enqueue<T>(Func<Task<T>> perform, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
using (await _AwaitableConstraint.WaitForReadiness(cancellationToken))
{
return await perform();
}
}
public IDispatcher Clone() => new TimeLimiter(_AwaitableConstraint.Clone());
private static Func<Task> Transform(Action act)
{
return () => { act(); return Task.FromResult(0); };
}
/// <summary>
/// Perform the given task respecting the time constraint
/// returning the result of given function
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="compute"></param>
/// <returns></returns>
private static Func<Task<T>> Transform<T>(Func<T> compute)
{
return () => Task.FromResult(compute());
}
/// <summary>
/// Perform the given task respecting the time constraint
/// </summary>
/// <param name="perform"></param>
/// <returns></returns>
public Task Enqueue(Action perform)
{
var transformed = Transform(perform);
return Enqueue(transformed);
}
/// <summary>
/// Perform the given task respecting the time constraint
/// </summary>
/// <param name="action"></param>
public void Dispatch(Action action)
{
Enqueue(action);
}
/// <summary>
/// Perform the given task respecting the time constraint
/// returning the result of given function
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="perform"></param>
/// <returns></returns>
public Task<T> Enqueue<T>(Func<T> perform)
{
var transformed = Transform(perform);
return Enqueue(transformed);
}
/// <summary>
/// Perform the given task respecting the time constraint
/// returning the result of given function
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="perform"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Task<T> Enqueue<T>(Func<T> perform, CancellationToken cancellationToken)
{
var transformed = Transform(perform);
return Enqueue(transformed, cancellationToken);
}
/// <summary>
/// Perform the given task respecting the time constraint
/// </summary>
/// <param name="perform"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Task Enqueue(Action perform, CancellationToken cancellationToken)
{
var transformed = Transform(perform);
return Enqueue(transformed, cancellationToken);
}
/// <summary>
/// Returns a TimeLimiter based on a maximum number of times
/// during a given period
/// </summary>
/// <param name="maxCount"></param>
/// <param name="timeSpan"></param>
/// <returns></returns>
public static TimeLimiter GetFromMaxCountByInterval(int maxCount, TimeSpan timeSpan)
{
return new TimeLimiter(new CountByIntervalAwaitableConstraint(maxCount, timeSpan));
}
/// <summary>
/// Create <see cref="TimeLimiter"/> that will save state using action passed through <paramref name="saveStateAction"/> parameter.
/// </summary>
/// <param name="maxCount">Maximum actions allowed per time interval.</param>
/// <param name="timeSpan">Time interval limits are applied for.</param>
/// <param name="saveStateAction">Action is used to save state.</param>
/// <returns><see cref="TimeLimiter"/> instance with <see cref="PersistentCountByIntervalAwaitableConstraint"/>.</returns>
public static TimeLimiter GetPersistentTimeLimiter(int maxCount, TimeSpan timeSpan,
Action<DateTime> saveStateAction)
{
return GetPersistentTimeLimiter(maxCount, timeSpan, saveStateAction, null);
}
/// <summary>
/// Create <see cref="TimeLimiter"/> with initial timestamps that will save state using action passed through <paramref name="saveStateAction"/> parameter.
/// </summary>
/// <param name="maxCount">Maximum actions allowed per time interval.</param>
/// <param name="timeSpan">Time interval limits are applied for.</param>
/// <param name="saveStateAction">Action is used to save state.</param>
/// <param name="initialTimeStamps">Initial timestamps.</param>
/// <returns><see cref="TimeLimiter"/> instance with <see cref="PersistentCountByIntervalAwaitableConstraint"/>.</returns>
public static TimeLimiter GetPersistentTimeLimiter(int maxCount, TimeSpan timeSpan,
Action<DateTime> saveStateAction, IEnumerable<DateTime> initialTimeStamps)
{
return new TimeLimiter(new PersistentCountByIntervalAwaitableConstraint(maxCount, timeSpan, saveStateAction, initialTimeStamps));
}
/// <summary>
/// Compose various IAwaitableConstraint in a TimeLimiter
/// </summary>
/// <param name="constraints"></param>
/// <returns></returns>
public static TimeLimiter Compose(params IAwaitableConstraint[] constraints)
{
var composed = constraints.Aggregate(default(IAwaitableConstraint),
(accumulated, current) => (accumulated == null) ? current : accumulated.Compose(current));
return new TimeLimiter(composed);
}
}
}

View File

@ -1,30 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace RateLimiter
{
internal class TimeSystem : ITime
{
public static ITime StandardTime { get; }
static TimeSystem()
{
StandardTime = new TimeSystem();
}
private TimeSystem()
{
}
DateTime ITime.GetNow()
{
return DateTime.Now;
}
Task ITime.GetDelay(TimeSpan timespan, CancellationToken cancellationToken)
{
return Task.Delay(timespan, cancellationToken);
}
}
}

View File

@ -1,4 +0,0 @@
[*.cs]
# CAC001: ConfigureAwaitChecker
dotnet_diagnostic.CAC001.severity = error

View File

@ -1,291 +0,0 @@
using System;
using TMDbLib.Objects.Account;
using TMDbLib.Objects.Authentication;
using TMDbLib.Objects.General;
using ParameterType = TMDbLib.Rest.ParameterType;
using RestClient = TMDbLib.Rest.RestClient;
using RestRequest = TMDbLib.Rest.RestRequest;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Rest;
using TMDbLib.Utilities.Serializer;
namespace TMDbLib.Client
{
public partial class TMDbClient : IDisposable
{
private const string ApiVersion = "3";
private const string ProductionUrl = "api.themoviedb.org";
private readonly ITMDbSerializer _serializer;
private RestClient _client;
private TMDbConfig _config;
public TMDbClient(string apiKey, bool useSsl = true, string baseUrl = ProductionUrl, ITMDbSerializer serializer = null, IWebProxy proxy = null)
{
DefaultLanguage = null;
DefaultImageLanguage = null;
DefaultCountry = null;
_serializer = serializer ?? TMDbJsonSerializer.Instance;
//Setup proxy to use during requests
//Proxy is optional. If passed, will be used in every request.
WebProxy = proxy;
Initialize(baseUrl, useSsl, apiKey);
}
/// <summary>
/// The account details of the user account associated with the current user session
/// </summary>
/// <remarks>This value is automaticly populated when setting a user session</remarks>
public AccountDetails ActiveAccount { get; private set; }
public string ApiKey { get; private set; }
public TMDbConfig Config
{
get
{
if (!HasConfig)
throw new InvalidOperationException("Call GetConfig() or SetConfig() first");
return _config;
}
private set { _config = value; }
}
/// <summary>
/// ISO 3166-1 code. Ex. US
/// </summary>
public string DefaultCountry { get; set; }
/// <summary>
/// ISO 639-1 code. Ex en
/// </summary>
public string DefaultLanguage { get; set; }
/// <summary>
/// ISO 639-1 code. Ex en
/// </summary>
public string DefaultImageLanguage { get; set; }
public bool HasConfig { get; private set; }
/// <summary>
/// Throw exceptions when TMDbs API returns certain errors, such as Not Found.
/// </summary>
public bool ThrowApiExceptions
{
get => _client.ThrowApiExceptions;
set => _client.ThrowApiExceptions = value;
}
/// <summary>
/// The maximum number of times a call to TMDb will be retried
/// </summary>
/// <remarks>Default is 0</remarks>
public int MaxRetryCount
{
get => _client.MaxRetryCount;
set => _client.MaxRetryCount = value;
}
/// <summary>
/// The request timeout call to TMDb
/// </summary>
public TimeSpan RequestTimeout
{
get => _client.HttpClient.Timeout;
set => _client.HttpClient.Timeout = value;
}
/// <summary>
/// The session id that will be used when TMDb requires authentication
/// </summary>
/// <remarks>Use 'SetSessionInformation' to assign this value</remarks>
public string SessionId { get; private set; }
/// <summary>
/// The type of the session id, this will determine the level of access that is granted on the API
/// </summary>
/// <remarks>Use 'SetSessionInformation' to assign this value</remarks>
public SessionType SessionType { get; private set; }
/// <summary>
/// Gets or sets the Web Proxy to use during requests to TMDb API.
/// </summary>
/// <remarks>
/// The Web Proxy is optional. If set, every request will be sent through it.
/// Use the constructor for setting it.
///
/// For convenience, this library also offers a <see cref="IWebProxy"/> implementation.
/// Check <see cref="Utilities.TMDbAPIProxy"/> for more information.
/// </remarks>
public IWebProxy WebProxy { get; private set; }
/// <summary>
/// Used internally to assign a session id to a request. If no valid session is found, an exception is thrown.
/// </summary>
/// <param name="req">Request</param>
/// <param name="targetType">The target session type to set. If set to Unassigned, the method will take the currently set session.</param>
/// <param name="parameterType">The location of the paramter in the resulting query</param>
private void AddSessionId(RestRequest req, SessionType targetType = SessionType.Unassigned, ParameterType parameterType = ParameterType.QueryString)
{
if ((targetType == SessionType.Unassigned && SessionType == SessionType.GuestSession) ||
(targetType == SessionType.GuestSession))
{
// Either
// - We needed ANY session ID and had a Guest session id
// - We needed a Guest session id and had it
req.AddParameter("guest_session_id", SessionId, parameterType);
return;
}
if ((targetType == SessionType.Unassigned && SessionType == SessionType.UserSession) ||
(targetType == SessionType.UserSession))
{
// Either
// - We needed ANY session ID and had a User session id
// - We needed a User session id and had it
req.AddParameter("session_id", SessionId, parameterType);
return;
}
// We did not have the required session type ready
throw new UserSessionRequiredException();
}
public async Task<TMDbConfig> GetConfigAsync()
{
TMDbConfig config = await _client.Create("configuration").GetOfT<TMDbConfig>(CancellationToken.None).ConfigureAwait(false);
if (config == null)
throw new Exception("Unable to retrieve configuration");
// Store config
Config = config;
HasConfig = true;
return config;
}
public Uri GetImageUrl(string size, string filePath, bool useSsl = false)
{
string baseUrl = useSsl ? Config.Images.SecureBaseUrl : Config.Images.BaseUrl;
return new Uri(baseUrl + size + filePath);
}
[Obsolete("Use " + nameof(GetImageBytesAsync))]
public Task<byte[]> GetImageBytes(string size, string filePath, bool useSsl = false, CancellationToken token = default)
{
return GetImageBytesAsync(size, filePath, useSsl, token);
}
public async Task<byte[]> GetImageBytesAsync(string size, string filePath, bool useSsl = false, CancellationToken token = default)
{
Uri url = GetImageUrl(size, filePath, useSsl);
using HttpResponseMessage response = await _client.HttpClient.GetAsync(url, HttpCompletionOption.ResponseContentRead, token).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("IDisposableAnalyzers.Correctness", "IDISP003:Dispose previous before re-assigning.", Justification = "Only called from ctor")]
private void Initialize(string baseUrl, bool useSsl, string apiKey)
{
if (string.IsNullOrWhiteSpace(baseUrl))
throw new ArgumentException("baseUrl");
if (string.IsNullOrWhiteSpace(apiKey))
throw new ArgumentException("apiKey");
ApiKey = apiKey;
// Cleanup the provided url so that we don't get any issues when we are configuring the client
if (baseUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
baseUrl = baseUrl.Substring("http://".Length);
else if (baseUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
baseUrl = baseUrl.Substring("https://".Length);
string httpScheme = useSsl ? "https" : "http";
_client = new RestClient(new Uri(string.Format("{0}://{1}/{2}/", httpScheme, baseUrl, ApiVersion)), _serializer, WebProxy);
_client.AddDefaultQueryString("api_key", apiKey);
}
/// <summary>
/// Used internally to determine if the current client has the required session set, if not an appropriate exception will be thrown
/// </summary>
/// <param name="sessionType">The type of session that is required by the calling method</param>
/// <exception cref="UserSessionRequiredException">Thrown if the calling method requires a user session and one isn't set on the client object</exception>
/// <exception cref="GuestSessionRequiredException">Thrown if the calling method requires a guest session and no session is set on the client object. (neither user or client type session)</exception>
private void RequireSessionId(SessionType sessionType)
{
if (string.IsNullOrWhiteSpace(SessionId))
{
if (sessionType == SessionType.GuestSession)
throw new UserSessionRequiredException();
else
throw new GuestSessionRequiredException();
}
if (sessionType == SessionType.UserSession && SessionType == SessionType.GuestSession)
throw new UserSessionRequiredException();
}
public void SetConfig(TMDbConfig config)
{
// Store config
Config = config;
HasConfig = true;
}
/// <summary>
/// Use this method to set the current client's authentication information.
/// The session id assigned here will be used by the client when ever TMDb requires it.
/// </summary>
/// <param name="sessionId">The session id to use when making calls that require authentication</param>
/// <param name="sessionType">The type of session id</param>
/// <remarks>
/// - Use the 'AuthenticationGetUserSessionAsync' and 'AuthenticationCreateGuestSessionAsync' methods to optain the respective session ids.
/// - User sessions have access to far for methods than guest sessions, these can currently only be used to rate media.
/// </remarks>
public async Task SetSessionInformationAsync(string sessionId, SessionType sessionType)
{
ActiveAccount = null;
SessionId = sessionId;
if (!string.IsNullOrWhiteSpace(sessionId) && sessionType == SessionType.Unassigned)
{
throw new ArgumentException("When setting the session id it must always be either a guest or user session");
}
SessionType = string.IsNullOrWhiteSpace(sessionId) ? SessionType.Unassigned : sessionType;
// Populate the related account information
if (sessionType == SessionType.UserSession)
{
try
{
ActiveAccount = await AccountGetDetailsAsync().ConfigureAwait(false);
}
catch (Exception)
{
// Unable to complete the full process so reset all values and throw the exception
ActiveAccount = null;
SessionId = null;
SessionType = SessionType.Unassigned;
throw;
}
}
}
public virtual void Dispose()
{
_client?.Dispose();
}
}
}

View File

@ -1,257 +0,0 @@
using TMDbLib.Utilities;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Account;
using TMDbLib.Objects.Authentication;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Lists;
using TMDbLib.Objects.Search;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
private async Task<SearchContainer<T>> GetAccountListInternal<T>(int page, AccountSortBy sortBy, SortOrder sortOrder, string language, AccountListsMethods method, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.UserSession);
RestRequest request = _client.Create("account/{accountId}/" + method.GetDescription());
request.AddUrlSegment("accountId", ActiveAccount.Id.ToString(CultureInfo.InvariantCulture));
AddSessionId(request, SessionType.UserSession);
if (page > 1)
request.AddParameter("page", page.ToString());
if (sortBy != AccountSortBy.Undefined)
request.AddParameter("sort_by", sortBy.GetDescription());
if (sortOrder != SortOrder.Undefined)
request.AddParameter("sort_order", sortOrder.GetDescription());
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
request.AddParameter("language", language);
SearchContainer<T> response = await request.GetOfT<SearchContainer<T>>(cancellationToken).ConfigureAwait(false);
return response;
}
/// <summary>
/// Change the favorite status of a specific movie. Either make the movie a favorite or remove that status depending on the supplied boolean value.
/// </summary>
/// <param name="mediaType">The type of media to influence</param>
/// <param name="mediaId">The id of the movie/tv show to influence</param>
/// <param name="isFavorite">True if you want the specified movie to be marked as favorite, false if not</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>True if the the movie's favorite status was successfully updated, false if not</returns>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<bool> AccountChangeFavoriteStatusAsync(MediaType mediaType, int mediaId, bool isFavorite, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.UserSession);
RestRequest request = _client.Create("account/{accountId}/favorite");
request.AddUrlSegment("accountId", ActiveAccount.Id.ToString(CultureInfo.InvariantCulture));
request.SetBody(new { media_type = mediaType.GetDescription(), media_id = mediaId, favorite = isFavorite });
AddSessionId(request, SessionType.UserSession);
PostReply response = await request.PostOfT<PostReply>(cancellationToken).ConfigureAwait(false);
// status code 1 = "Success" - Returned when adding a movie as favorite for the first time
// status code 13 = "The item/record was deleted successfully" - When removing an item as favorite, no matter if it exists or not
// status code 12 = "The item/record was updated successfully" - Used when an item is already marked as favorite and trying to do so doing again
return response.StatusCode == 1 || response.StatusCode == 12 || response.StatusCode == 13;
}
/// <summary>
/// Change the state of a specific movie on the users watchlist. Either add the movie to the list or remove it, depending on the specified boolean value.
/// </summary>
/// <param name="mediaType">The type of media to influence</param>
/// <param name="mediaId">The id of the movie/tv show to influence</param>
/// <param name="isOnWatchlist">True if you want the specified movie to be part of the watchlist, false if not</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns>True if the the movie's status on the watchlist was successfully updated, false if not</returns>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<bool> AccountChangeWatchlistStatusAsync(MediaType mediaType, int mediaId, bool isOnWatchlist, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.UserSession);
RestRequest request = _client.Create("account/{accountId}/watchlist");
request.AddUrlSegment("accountId", ActiveAccount.Id.ToString(CultureInfo.InvariantCulture));
request.SetBody(new { media_type = mediaType.GetDescription(), media_id = mediaId, watchlist = isOnWatchlist });
AddSessionId(request, SessionType.UserSession);
PostReply response = await request.PostOfT<PostReply>(cancellationToken).ConfigureAwait(false);
// status code 1 = "Success"
// status code 13 = "The item/record was deleted successfully" - When removing an item from the watchlist, no matter if it exists or not
// status code 12 = "The item/record was updated successfully" - Used when an item is already on the watchlist and trying to add it again
return response.StatusCode == 1 || response.StatusCode == 12 || response.StatusCode == 13;
}
/// <summary>
/// Will retrieve the details of the account associated with the current session id
/// </summary>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<AccountDetails> AccountGetDetailsAsync(CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.UserSession);
RestRequest request = _client.Create("account");
AddSessionId(request, SessionType.UserSession);
AccountDetails response = await request.GetOfT<AccountDetails>(cancellationToken).ConfigureAwait(false);
return response;
}
/// <summary>
/// Get a list of all the movies marked as favorite by the current user
/// </summary>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<SearchContainer<SearchMovie>> AccountGetFavoriteMoviesAsync(
int page = 1,
AccountSortBy sortBy = AccountSortBy.Undefined,
SortOrder sortOrder = SortOrder.Undefined,
string language = null, CancellationToken cancellationToken = default)
{
return await GetAccountListInternal<SearchMovie>(page, sortBy, sortOrder, language, AccountListsMethods.FavoriteMovies, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get a list of all the tv shows marked as favorite by the current user
/// </summary>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<SearchContainer<SearchTv>> AccountGetFavoriteTvAsync(
int page = 1,
AccountSortBy sortBy = AccountSortBy.Undefined,
SortOrder sortOrder = SortOrder.Undefined,
string language = null, CancellationToken cancellationToken = default)
{
return await GetAccountListInternal<SearchTv>(page, sortBy, sortOrder, language, AccountListsMethods.FavoriteTv, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Retrieve all lists associated with the provided account id
/// This can be lists that were created by the user or lists marked as favorite
/// </summary>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<SearchContainer<AccountList>> AccountGetListsAsync(int page = 1, string language = null, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.UserSession);
RestRequest request = _client.Create("account/{accountId}/lists");
request.AddUrlSegment("accountId", ActiveAccount.Id.ToString(CultureInfo.InvariantCulture));
AddSessionId(request, SessionType.UserSession);
if (page > 1)
{
request.AddQueryString("page", page.ToString());
}
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
request.AddQueryString("language", language);
SearchContainer<AccountList> response = await request.GetOfT<SearchContainer<AccountList>>(cancellationToken).ConfigureAwait(false);
return response;
}
/// <summary>
/// Get a list of all the movies on the current users match list
/// </summary>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<SearchContainer<SearchMovie>> AccountGetMovieWatchlistAsync(
int page = 1,
AccountSortBy sortBy = AccountSortBy.Undefined,
SortOrder sortOrder = SortOrder.Undefined,
string language = null, CancellationToken cancellationToken = default)
{
return await GetAccountListInternal<SearchMovie>(page, sortBy, sortOrder, language, AccountListsMethods.MovieWatchlist, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get a list of all the movies rated by the current user
/// </summary>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<SearchContainer<SearchMovieWithRating>> AccountGetRatedMoviesAsync(
int page = 1,
AccountSortBy sortBy = AccountSortBy.Undefined,
SortOrder sortOrder = SortOrder.Undefined,
string language = null, CancellationToken cancellationToken = default)
{
return await GetAccountListInternal<SearchMovieWithRating>(page, sortBy, sortOrder, language, AccountListsMethods.RatedMovies, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get a list of all the tv show episodes rated by the current user
/// </summary>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<SearchContainer<AccountSearchTvEpisode>> AccountGetRatedTvShowEpisodesAsync(
int page = 1,
AccountSortBy sortBy = AccountSortBy.Undefined,
SortOrder sortOrder = SortOrder.Undefined,
string language = null, CancellationToken cancellationToken = default)
{
return await GetAccountListInternal<AccountSearchTvEpisode>(page, sortBy, sortOrder, language, AccountListsMethods.RatedTvEpisodes, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get a list of all the tv shows rated by the current user
/// </summary>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<SearchContainer<AccountSearchTv>> AccountGetRatedTvShowsAsync(
int page = 1,
AccountSortBy sortBy = AccountSortBy.Undefined,
SortOrder sortOrder = SortOrder.Undefined,
string language = null, CancellationToken cancellationToken = default)
{
return await GetAccountListInternal<AccountSearchTv>(page, sortBy, sortOrder, language, AccountListsMethods.RatedTv, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get a list of all the tv shows on the current users match list
/// </summary>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<SearchContainer<SearchTv>> AccountGetTvWatchlistAsync(
int page = 1,
AccountSortBy sortBy = AccountSortBy.Undefined,
SortOrder sortOrder = SortOrder.Undefined,
string language = null, CancellationToken cancellationToken = default)
{
return await GetAccountListInternal<SearchTv>(page, sortBy, sortOrder, language, AccountListsMethods.TvWatchlist, cancellationToken).ConfigureAwait(false);
}
private enum AccountListsMethods
{
[EnumValue("favorite/movies")]
FavoriteMovies,
[EnumValue("favorite/tv")]
FavoriteTv,
[EnumValue("rated/movies")]
RatedMovies,
[EnumValue("rated/tv")]
RatedTv,
[EnumValue("rated/tv/episodes")]
RatedTvEpisodes,
[EnumValue("watchlist/movies")]
MovieWatchlist,
[EnumValue("watchlist/tv")]
TvWatchlist,
}
}
}

View File

@ -1,87 +0,0 @@
using System;
using System.Threading.Tasks;
using System.Net;
using System.Threading;
using TMDbLib.Objects.Authentication;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
public async Task<GuestSession> AuthenticationCreateGuestSessionAsync(CancellationToken cancellationToken = default)
{
RestRequest request = _client.Create("authentication/guest_session/new");
//{
// DateFormat = "yyyy-MM-dd HH:mm:ss UTC"
//};
GuestSession response = await request.GetOfT<GuestSession>(cancellationToken).ConfigureAwait(false);
return response;
}
public async Task<UserSession> AuthenticationGetUserSessionAsync(string initialRequestToken, CancellationToken cancellationToken = default)
{
RestRequest request = _client.Create("authentication/session/new");
request.AddParameter("request_token", initialRequestToken);
using RestResponse<UserSession> response = await request.Get<UserSession>(cancellationToken).ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.Unauthorized)
throw new UnauthorizedAccessException();
return await response.GetDataObject().ConfigureAwait(false);
}
/// <summary>
/// Conveniance method combining 'AuthenticationRequestAutenticationTokenAsync', 'AuthenticationValidateUserTokenAsync' and 'AuthenticationGetUserSessionAsync'
/// </summary>
/// <param name="username">A valid TMDb username</param>
/// <param name="password">The passoword for the provided login</param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<UserSession> AuthenticationGetUserSessionAsync(string username, string password, CancellationToken cancellationToken = default)
{
Token token = await AuthenticationRequestAutenticationTokenAsync(cancellationToken).ConfigureAwait(false);
await AuthenticationValidateUserTokenAsync(token.RequestToken, username, password, cancellationToken).ConfigureAwait(false);
return await AuthenticationGetUserSessionAsync(token.RequestToken, cancellationToken).ConfigureAwait(false);
}
public async Task<Token> AuthenticationRequestAutenticationTokenAsync(CancellationToken cancellationToken = default)
{
RestRequest request = _client.Create("authentication/token/new");
using RestResponse<Token> response = await request.Get<Token>(cancellationToken).ConfigureAwait(false);
Token token = await response.GetDataObject().ConfigureAwait(false);
token.AuthenticationCallback = response.GetHeader("Authentication-Callback");
return token;
}
public async Task AuthenticationValidateUserTokenAsync(string initialRequestToken, string username, string password, CancellationToken cancellationToken = default)
{
RestRequest request = _client.Create("authentication/token/validate_with_login");
request.AddParameter("request_token", initialRequestToken);
request.AddParameter("username", username);
request.AddParameter("password", password);
RestResponse response;
try
{
response = await request.Get(cancellationToken).ConfigureAwait(false);
}
catch (AggregateException ex)
{
throw ex.InnerException;
}
using RestResponse _ = response;
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException("Call to TMDb returned unauthorized. Most likely the provided user credentials are invalid.");
}
}
}
}

View File

@ -1,28 +0,0 @@
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Certifications;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
public async Task<CertificationsContainer> GetMovieCertificationsAsync(CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("certification/movie/list");
CertificationsContainer resp = await req.GetOfT<CertificationsContainer>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<CertificationsContainer> GetTvCertificationsAsync(CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("certification/tv/list");
CertificationsContainer resp = await req.GetOfT<CertificationsContainer>(cancellationToken).ConfigureAwait(false);
return resp;
}
}
}

View File

@ -1,109 +0,0 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Changes;
using TMDbLib.Objects.General;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
private async Task<T> GetChangesInternal<T>(string type, int page = 0, int? id = null, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default)
{
string resource;
if (id.HasValue)
resource = "{type}/{id}/changes";
else
resource = "{type}/changes";
RestRequest req = _client.Create(resource);
req.AddUrlSegment("type", type);
if (id.HasValue)
req.AddUrlSegment("id", id.Value.ToString());
if (page >= 1)
req.AddParameter("page", page.ToString());
if (startDate.HasValue)
req.AddParameter("start_date", startDate.Value.ToString("yyyy-MM-dd"));
if (endDate != null)
req.AddParameter("end_date", endDate.Value.ToString("yyyy-MM-dd"));
using RestResponse<T> resp = await req.Get<T>(cancellationToken).ConfigureAwait(false);
T res = await resp.GetDataObject().ConfigureAwait(false);
if (res is SearchContainer<ChangesListItem> asSearch)
{
// https://github.com/LordMike/TMDbLib/issues/296
asSearch.Results.RemoveAll(s => s.Id == 0);
}
return res;
}
/// <summary>
/// Get a list of movie ids that have been edited.
/// By default we show the last 24 hours and only 100 items per page.
/// The maximum number of days that can be returned in a single request is 14.
/// You can then use the movie changes API to get the actual data that has been changed. (.GetMovieChangesAsync)
/// </summary>
/// <remarks>the change log system to support this was changed on October 5, 2012 and will only show movies that have been edited since.</remarks>
public async Task<SearchContainer<ChangesListItem>> GetMoviesChangesAsync(int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default)
{
return await GetChangesInternal<SearchContainer<ChangesListItem>>("movie", page, startDate: startDate, endDate: endDate, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get a list of people ids that have been edited.
/// By default we show the last 24 hours and only 100 items per page.
/// The maximum number of days that can be returned in a single request is 14.
/// You can then use the person changes API to get the actual data that has been changed.(.GetPersonChangesAsync)
/// </summary>
/// <remarks>the change log system to support this was changed on October 5, 2012 and will only show people that have been edited since.</remarks>
public async Task<SearchContainer<ChangesListItem>> GetPeopleChangesAsync(int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default)
{
return await GetChangesInternal<SearchContainer<ChangesListItem>>("person", page, startDate: startDate, endDate: endDate, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get a list of TV show ids that have been edited.
/// By default we show the last 24 hours and only 100 items per page.
/// The maximum number of days that can be returned in a single request is 14.
/// You can then use the TV changes API to get the actual data that has been changed. (.GetTvShowChangesAsync)
/// </summary>
/// <remarks>
/// the change log system to properly support TV was updated on May 13, 2014.
/// You'll likely only find the edits made since then to be useful in the change log system.
/// </remarks>
public async Task<SearchContainer<ChangesListItem>> GetTvChangesAsync(int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default)
{
return await GetChangesInternal<SearchContainer<ChangesListItem>>("tv", page, startDate: startDate, endDate: endDate, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<IList<Change>> GetMovieChangesAsync(int movieId, int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default)
{
ChangesContainer changesContainer = await GetChangesInternal<ChangesContainer>("movie", page, movieId, startDate, endDate, cancellationToken).ConfigureAwait(false);
return changesContainer.Changes;
}
public async Task<IList<Change>> GetPersonChangesAsync(int personId, int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default)
{
ChangesContainer changesContainer = await GetChangesInternal<ChangesContainer>("person", page, personId, startDate, endDate, cancellationToken).ConfigureAwait(false);
return changesContainer.Changes;
}
public async Task<IList<Change>> GetTvSeasonChangesAsync(int seasonId, int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default)
{
ChangesContainer changesContainer = await GetChangesInternal<ChangesContainer>("tv/season", page, seasonId, startDate, endDate, cancellationToken).ConfigureAwait(false);
return changesContainer.Changes;
}
public async Task<IList<Change>> GetTvEpisodeChangesAsync(int episodeId, int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default)
{
ChangesContainer changesContainer = await GetChangesInternal<ChangesContainer>("tv/episode", page, episodeId, startDate, endDate, cancellationToken).ConfigureAwait(false);
return changesContainer.Changes;
}
}
}

View File

@ -1,77 +0,0 @@
using System;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Collections;
using TMDbLib.Objects.General;
using TMDbLib.Rest;
using TMDbLib.Utilities;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
private async Task<T> GetCollectionMethodInternal<T>(int collectionId, CollectionMethods collectionMethod, string language = null, CancellationToken cancellationToken = default) where T : new()
{
RestRequest req = _client.Create("collection/{collectionId}/{method}");
req.AddUrlSegment("collectionId", collectionId.ToString());
req.AddUrlSegment("method", collectionMethod.GetDescription());
if (language != null)
req.AddParameter("language", language);
T resp = await req.GetOfT<T>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<Collection> GetCollectionAsync(int collectionId, CollectionMethods extraMethods = CollectionMethods.Undefined, CancellationToken cancellationToken = default)
{
return await GetCollectionAsync(collectionId, DefaultLanguage, null, extraMethods, cancellationToken).ConfigureAwait(false);
}
public async Task<Collection> GetCollectionAsync(int collectionId, string language, string includeImageLanguages, CollectionMethods extraMethods = CollectionMethods.Undefined, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("collection/{collectionId}");
req.AddUrlSegment("collectionId", collectionId.ToString());
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
includeImageLanguages ??= DefaultImageLanguage;
if (!string.IsNullOrWhiteSpace(includeImageLanguages))
req.AddParameter("include_image_language", includeImageLanguages);
string appends = string.Join(",",
Enum.GetValues(typeof(CollectionMethods))
.OfType<CollectionMethods>()
.Except(new[] { CollectionMethods.Undefined })
.Where(s => extraMethods.HasFlag(s))
.Select(s => s.GetDescription()));
if (appends != string.Empty)
req.AddParameter("append_to_response", appends);
//req.DateFormat = "yyyy-MM-dd";
using RestResponse<Collection> response = await req.Get<Collection>(cancellationToken).ConfigureAwait(false);
if (!response.IsValid)
return null;
Collection item = await response.GetDataObject().ConfigureAwait(false);
if (item != null)
item.Overview = WebUtility.HtmlDecode(item.Overview);
return item;
}
public async Task<ImagesWithId> GetCollectionImagesAsync(int collectionId, string language = null, CancellationToken cancellationToken = default)
{
return await GetCollectionMethodInternal<ImagesWithId>(collectionId, CollectionMethods.Images, language, cancellationToken).ConfigureAwait(false);
}
}
}

View File

@ -1,65 +0,0 @@
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Companies;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Search;
using TMDbLib.Rest;
using TMDbLib.Utilities;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
private async Task<T> GetCompanyMethodInternal<T>(int companyId, CompanyMethods companyMethod, int page = 0, string language = null, CancellationToken cancellationToken = default) where T : new()
{
RestRequest req = _client.Create("company/{companyId}/{method}");
req.AddUrlSegment("companyId", companyId.ToString());
req.AddUrlSegment("method", companyMethod.GetDescription());
if (page >= 1)
req.AddParameter("page", page.ToString());
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
T resp = await req.GetOfT<T>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<Company> GetCompanyAsync(int companyId, CompanyMethods extraMethods = CompanyMethods.Undefined, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("company/{companyId}");
req.AddUrlSegment("companyId", companyId.ToString());
string appends = string.Join(",",
Enum.GetValues(typeof(CompanyMethods))
.OfType<CompanyMethods>()
.Except(new[] { CompanyMethods.Undefined })
.Where(s => extraMethods.HasFlag(s))
.Select(s => s.GetDescription()));
if (appends != string.Empty)
req.AddParameter("append_to_response", appends);
//req.DateFormat = "yyyy-MM-dd";
Company resp = await req.GetOfT<Company>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainerWithId<SearchMovie>> GetCompanyMoviesAsync(int companyId, int page = 0, CancellationToken cancellationToken = default)
{
return await GetCompanyMoviesAsync(companyId, DefaultLanguage, page, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainerWithId<SearchMovie>> GetCompanyMoviesAsync(int companyId, string language, int page = 0, CancellationToken cancellationToken = default)
{
return await GetCompanyMethodInternal<SearchContainerWithId<SearchMovie>>(companyId, CompanyMethods.Movies, page, language, cancellationToken).ConfigureAwait(false);
}
}
}

View File

@ -1,89 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Configuration;
using TMDbLib.Objects.Countries;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Languages;
using TMDbLib.Objects.Timezones;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
public async Task<APIConfiguration> GetAPIConfiguration(CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("configuration");
using RestResponse<APIConfiguration> response = await req.Get<APIConfiguration>(cancellationToken).ConfigureAwait(false);
return (await response.GetDataObject().ConfigureAwait(false));
}
public async Task<List<Country>> GetCountriesAsync(CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("configuration/countries");
using RestResponse<List<Country>> response = await req.Get<List<Country>>(cancellationToken).ConfigureAwait(false);
return await response.GetDataObject().ConfigureAwait(false);
}
public async Task<List<Language>> GetLanguagesAsync(CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("configuration/languages");
using RestResponse<List<Language>> response = await req.Get<List<Language>>(cancellationToken).ConfigureAwait(false);
return (await response.GetDataObject().ConfigureAwait(false));
}
public async Task<List<string>> GetPrimaryTranslationsAsync(CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("configuration/primary_translations");
using RestResponse<List<string>> response = await req.Get<List<string>>(cancellationToken).ConfigureAwait(false);
return (await response.GetDataObject().ConfigureAwait(false));
}
public async Task<Timezones> GetTimezonesAsync(CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("timezones/list");
using RestResponse<List<Dictionary<string, List<string>>>> resp = await req.Get<List<Dictionary<string, List<string>>>>(cancellationToken).ConfigureAwait(false);
List<Dictionary<string, List<string>>> item = await resp.GetDataObject().ConfigureAwait(false);
if (item == null)
return null;
Timezones result = new Timezones();
result.List = new Dictionary<string, List<string>>();
foreach (Dictionary<string, List<string>> dictionary in item)
{
KeyValuePair<string, List<string>> item1 = dictionary.First();
result.List[item1.Key] = item1.Value;
}
return result;
}
/// <summary>
/// Retrieves a list of departments and positions within
/// </summary>
/// <returns>Valid jobs and their departments</returns>
public async Task<List<Job>> GetJobsAsync(CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("configuration/jobs");
using RestResponse<List<Job>> response = await req.Get<List<Job>>(cancellationToken).ConfigureAwait(false);
return (await response.GetDataObject().ConfigureAwait(false));
}
}
}

View File

@ -1,29 +0,0 @@
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Credit;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
public async Task<Credit> GetCreditsAsync(string id, CancellationToken cancellationToken = default)
{
return await GetCreditsAsync(id, DefaultLanguage, cancellationToken).ConfigureAwait(false);
}
public async Task<Credit> GetCreditsAsync(string id, string language, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("credit/{id}");
if (!string.IsNullOrEmpty(language))
req.AddParameter("language", language);
req.AddUrlSegment("id", id);
Credit resp = await req.GetOfT<Credit>(cancellationToken).ConfigureAwait(false);
return resp;
}
}
}

View File

@ -1,46 +0,0 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Discover;
using TMDbLib.Objects.General;
using TMDbLib.Rest;
using TMDbLib.Utilities;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
/// <summary>
/// Can be used to discover movies matching certain criteria
/// </summary>
public DiscoverMovie DiscoverMoviesAsync()
{
return new DiscoverMovie(this);
}
internal async Task<SearchContainer<T>> DiscoverPerformAsync<T>(string endpoint, string language, int page, SimpleNamedValueCollection parameters, CancellationToken cancellationToken = default)
{
RestRequest request = _client.Create(endpoint);
if (page != 1 && page > 1)
request.AddParameter("page", page.ToString());
if (!string.IsNullOrWhiteSpace(language))
request.AddParameter("language", language);
foreach (KeyValuePair<string, string> pair in parameters)
request.AddParameter(pair.Key, pair.Value);
SearchContainer<T> response = await request.GetOfT<SearchContainer<T>>(cancellationToken).ConfigureAwait(false);
return response;
}
/// <summary>
/// Can be used to discover new tv shows matching certain criteria
/// </summary>
public DiscoverTv DiscoverTvShowsAsync()
{
return new DiscoverTv(this);
}
}
}

View File

@ -1,56 +0,0 @@
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Find;
using TMDbLib.Rest;
using TMDbLib.Utilities;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
/// <summary>
/// FindAsync movies, people and tv shows by an external id.
/// The following types can be found based on the specified external id's
/// - Movies: Imdb
/// - People: Imdb, FreeBaseMid, FreeBaseId, TvRage
/// - TV Series: Imdb, FreeBaseMid, FreeBaseId, TvRage, TvDb
/// </summary>
/// <param name="source">The source the specified id belongs to</param>
/// <param name="id">The id of the object you wish to located</param>
/// <returns>A list of all objects in TMDb that matched your id</returns>
/// <param name="cancellationToken">A cancellation token</param>
public Task<FindContainer> FindAsync(FindExternalSource source, string id, CancellationToken cancellationToken = default)
{
return FindAsync(source, id, null, cancellationToken);
}
/// <summary>
/// FindAsync movies, people and tv shows by an external id.
/// The following types can be found based on the specified external id's
/// - Movies: Imdb
/// - People: Imdb, FreeBaseMid, FreeBaseId, TvRage
/// - TV Series: Imdb, FreeBaseMid, FreeBaseId, TvRage, TvDb
/// </summary>
/// <param name="source">The source the specified id belongs to</param>
/// <param name="id">The id of the object you wish to located</param>
/// <returns>A list of all objects in TMDb that matched your id</returns>
/// <param name="language">If specified the api will attempt to return a localized result. ex: en,it,es.</param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<FindContainer> FindAsync(FindExternalSource source, string id, string language, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("find/{id}");
req.AddUrlSegment("id", WebUtility.UrlEncode(id));
req.AddParameter("external_source", source.GetDescription());
language ??= DefaultLanguage;
if (!string.IsNullOrEmpty(language))
req.AddParameter("language", language);
FindContainer resp = await req.GetOfT<FindContainer>(cancellationToken).ConfigureAwait(false);
return resp;
}
}
}

View File

@ -1,76 +0,0 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Genres;
using TMDbLib.Objects.Search;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
[Obsolete("GetGenreMovies is deprecated, use DiscoverMovies instead")]
public async Task<SearchContainerWithId<SearchMovie>> GetGenreMoviesAsync(int genreId, int page = 0, bool? includeAllMovies = null, CancellationToken cancellationToken = default)
{
return await GetGenreMoviesAsync(genreId, DefaultLanguage, page, includeAllMovies, cancellationToken).ConfigureAwait(false);
}
[Obsolete("GetGenreMovies is deprecated, use DiscoverMovies instead")]
public async Task<SearchContainerWithId<SearchMovie>> GetGenreMoviesAsync(int genreId, string language, int page = 0, bool? includeAllMovies = null, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("genre/{genreId}/movies");
req.AddUrlSegment("genreId", genreId.ToString());
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
if (page >= 1)
req.AddParameter("page", page.ToString());
if (includeAllMovies.HasValue)
req.AddParameter("include_all_movies", includeAllMovies.Value ? "true" : "false");
SearchContainerWithId<SearchMovie> resp = await req.GetOfT<SearchContainerWithId<SearchMovie>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<List<Genre>> GetMovieGenresAsync(CancellationToken cancellationToken = default)
{
return await GetMovieGenresAsync(DefaultLanguage, cancellationToken).ConfigureAwait(false);
}
public async Task<List<Genre>> GetMovieGenresAsync(string language, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("genre/movie/list");
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
using RestResponse<GenreContainer> resp = await req.Get<GenreContainer>(cancellationToken).ConfigureAwait(false);
return (await resp.GetDataObject().ConfigureAwait(false)).Genres;
}
public async Task<List<Genre>> GetTvGenresAsync(CancellationToken cancellationToken = default)
{
return await GetTvGenresAsync(DefaultLanguage, cancellationToken).ConfigureAwait(false);
}
public async Task<List<Genre>> GetTvGenresAsync(string language, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("genre/tv/list");
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
using RestResponse<GenreContainer> resp = await req.Get<GenreContainer>(cancellationToken).ConfigureAwait(false);
return (await resp.GetDataObject().ConfigureAwait(false)).Genres;
}
}
}

View File

@ -1,85 +0,0 @@
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Authentication;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Search;
using TMDbLib.Objects.TvShows;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
public async Task<SearchContainer<SearchMovieWithRating>> GetGuestSessionRatedMoviesAsync(int page = 0, CancellationToken cancellationToken = default)
{
return await GetGuestSessionRatedMoviesAsync(DefaultLanguage, page, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchMovieWithRating>> GetGuestSessionRatedMoviesAsync(string language, int page = 0, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.GuestSession);
RestRequest request = _client.Create("guest_session/{guest_session_id}/rated/movies");
if (page > 0)
request.AddParameter("page", page.ToString());
if (!string.IsNullOrEmpty(language))
request.AddParameter("language", language);
AddSessionId(request, SessionType.GuestSession, ParameterType.UrlSegment);
SearchContainer<SearchMovieWithRating> resp = await request.GetOfT<SearchContainer<SearchMovieWithRating>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainer<SearchTvShowWithRating>> GetGuestSessionRatedTvAsync(int page = 0, CancellationToken cancellationToken = default)
{
return await GetGuestSessionRatedTvAsync(DefaultLanguage, page, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchTvShowWithRating>> GetGuestSessionRatedTvAsync(string language, int page = 0, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.GuestSession);
RestRequest request = _client.Create("guest_session/{guest_session_id}/rated/tv");
if (page > 0)
request.AddParameter("page", page.ToString());
if (!string.IsNullOrEmpty(language))
request.AddParameter("language", language);
AddSessionId(request, SessionType.GuestSession, ParameterType.UrlSegment);
SearchContainer<SearchTvShowWithRating> resp = await request.GetOfT<SearchContainer<SearchTvShowWithRating>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainer<TvEpisodeWithRating>> GetGuestSessionRatedTvEpisodesAsync(int page = 0, CancellationToken cancellationToken = default)
{
return await GetGuestSessionRatedTvEpisodesAsync(DefaultLanguage, page, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<TvEpisodeWithRating>> GetGuestSessionRatedTvEpisodesAsync(string language, int page = 0, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.GuestSession);
RestRequest request = _client.Create("guest_session/{guest_session_id}/rated/tv/episodes");
if (page > 0)
request.AddParameter("page", page.ToString());
if (!string.IsNullOrEmpty(language))
request.AddParameter("language", language);
AddSessionId(request, SessionType.GuestSession, ParameterType.UrlSegment);
SearchContainer<TvEpisodeWithRating> resp = await request.GetOfT<SearchContainer<TvEpisodeWithRating>>(cancellationToken).ConfigureAwait(false);
return resp;
}
}
}

View File

@ -1,43 +0,0 @@
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Search;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
public async Task<Keyword> GetKeywordAsync(int keywordId, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("keyword/{keywordId}");
req.AddUrlSegment("keywordId", keywordId.ToString());
Keyword resp = await req.GetOfT<Keyword>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainerWithId<SearchMovie>> GetKeywordMoviesAsync(int keywordId, int page = 0, CancellationToken cancellationToken = default)
{
return await GetKeywordMoviesAsync(keywordId, DefaultLanguage, page, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainerWithId<SearchMovie>> GetKeywordMoviesAsync(int keywordId, string language, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("keyword/{keywordId}/movies");
req.AddUrlSegment("keywordId", keywordId.ToString());
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
if (page >= 1)
req.AddParameter("page", page.ToString());
SearchContainerWithId<SearchMovie> resp = await req.GetOfT<SearchContainerWithId<SearchMovie>>(cancellationToken).ConfigureAwait(false);
return resp;
}
}
}

View File

@ -1,210 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Authentication;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Lists;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
private async Task<bool> GetManipulateMediaListAsyncInternal(string listId, int movieId, string method, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.UserSession);
if (string.IsNullOrWhiteSpace(listId))
throw new ArgumentNullException(nameof(listId));
// Movie Id is expected by the API and can not be null
if (movieId <= 0)
throw new ArgumentOutOfRangeException(nameof(movieId));
RestRequest req = _client.Create("list/{listId}/{method}");
req.AddUrlSegment("listId", listId);
req.AddUrlSegment("method", method);
AddSessionId(req, SessionType.UserSession);
req.SetBody(new { media_id = movieId });
using RestResponse<PostReply> response = await req.Post<PostReply>(cancellationToken).ConfigureAwait(false);
// Status code 12 = "The item/record was updated successfully"
// Status code 13 = "The item/record was deleted successfully"
PostReply item = await response.GetDataObject().ConfigureAwait(false);
// TODO: Previous code checked for item=null
return item.StatusCode == 12 || item.StatusCode == 13;
}
/// <summary>
/// Retrieve a list by it's id
/// </summary>
/// <param name="listId">The id of the list you want to retrieve</param>
/// <param name="language">If specified the api will attempt to return a localized result. ex: en,it,es </param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<GenericList> GetListAsync(string listId, string language = null, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(listId))
throw new ArgumentNullException(nameof(listId));
RestRequest req = _client.Create("list/{listId}");
req.AddUrlSegment("listId", listId);
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
GenericList resp = await req.GetOfT<GenericList>(cancellationToken).ConfigureAwait(false);
return resp;
}
/// <summary>
/// Will check if the provided movie id is present in the specified list
/// </summary>
/// <param name="listId">Id of the list to check in</param>
/// <param name="movieId">Id of the movie to check for in the list</param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<bool> GetListIsMoviePresentAsync(string listId, int movieId, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(listId))
throw new ArgumentNullException(nameof(listId));
if (movieId <= 0)
throw new ArgumentOutOfRangeException(nameof(movieId));
RestRequest req = _client.Create("list/{listId}/item_status");
req.AddUrlSegment("listId", listId);
req.AddParameter("movie_id", movieId.ToString());
using RestResponse<ListStatus> response = await req.Get<ListStatus>(cancellationToken).ConfigureAwait(false);
return (await response.GetDataObject().ConfigureAwait(false)).ItemPresent;
}
/// <summary>
/// Adds a movie to a specified list
/// </summary>
/// <param name="listId">The id of the list to add the movie to</param>
/// <param name="movieId">The id of the movie to add</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns>True if the method was able to add the movie to the list, will retrun false in case of an issue or when the movie was already added to the list</returns>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<bool> ListAddMovieAsync(string listId, int movieId, CancellationToken cancellationToken = default)
{
return await GetManipulateMediaListAsyncInternal(listId, movieId, "add_item", cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Clears a list, without confirmation.
/// </summary>
/// <param name="listId">The id of the list to clear</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns>True if the method was able to remove the movie from the list, will retrun false in case of an issue or when the movie was not present in the list</returns>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<bool> ListClearAsync(string listId, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.UserSession);
if (string.IsNullOrWhiteSpace(listId))
throw new ArgumentNullException(nameof(listId));
RestRequest request = _client.Create("list/{listId}/clear");
request.AddUrlSegment("listId", listId);
request.AddParameter("confirm", "true");
AddSessionId(request, SessionType.UserSession);
using RestResponse<PostReply> response = await request.Post<PostReply>(cancellationToken).ConfigureAwait(false);
// Status code 12 = "The item/record was updated successfully"
PostReply item = await response.GetDataObject().ConfigureAwait(false);
// TODO: Previous code checked for item=null
return item.StatusCode == 12;
}
/// <summary>
/// Creates a new list for the user associated with the current session
/// </summary>
/// <param name="name">The name of the new list</param>
/// <param name="description">Optional description for the list</param>
/// <param name="language">Optional language that might indicate the language of the content in the list</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<string> ListCreateAsync(string name, string description = "", string language = null, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.UserSession);
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
// Description is expected by the API and can not be null
if (string.IsNullOrWhiteSpace(description))
description = "";
RestRequest req = _client.Create("list");
AddSessionId(req, SessionType.UserSession);
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
{
req.SetBody(new { name = name, description = description, language = language });
}
else
{
req.SetBody(new { name = name, description = description });
}
using RestResponse<ListCreateReply> response = await req.Post<ListCreateReply>(cancellationToken).ConfigureAwait(false);
return (await response.GetDataObject().ConfigureAwait(false)).ListId;
}
/// <summary>
/// Deletes the specified list that is owned by the user
/// </summary>
/// <param name="listId">A list id that is owned by the user associated with the current session id</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<bool> ListDeleteAsync(string listId, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.UserSession);
if (string.IsNullOrWhiteSpace(listId))
throw new ArgumentNullException(nameof(listId));
RestRequest req = _client.Create("list/{listId}");
req.AddUrlSegment("listId", listId);
AddSessionId(req, SessionType.UserSession);
using RestResponse<PostReply> response = await req.Delete<PostReply>(cancellationToken).ConfigureAwait(false);
// Status code 13 = success
PostReply item = await response.GetDataObject().ConfigureAwait(false);
// TODO: Previous code checked for item=null
return item.StatusCode == 13;
}
/// <summary>
/// Removes a movie from the specified list
/// </summary>
/// <param name="listId">The id of the list to add the movie to</param>
/// <param name="movieId">The id of the movie to add</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns>True if the method was able to remove the movie from the list, will retrun false in case of an issue or when the movie was not present in the list</returns>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<bool> ListRemoveMovieAsync(string listId, int movieId, CancellationToken cancellationToken = default)
{
return await GetManipulateMediaListAsyncInternal(listId, movieId, "remove_item", cancellationToken).ConfigureAwait(false);
}
}
}

View File

@ -1,392 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Authentication;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Movies;
using TMDbLib.Objects.Reviews;
using TMDbLib.Objects.Search;
using TMDbLib.Rest;
using TMDbLib.Utilities;
using Credits = TMDbLib.Objects.Movies.Credits;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
private async Task<T> GetMovieMethodInternal<T>(int movieId, MovieMethods movieMethod, string dateFormat = null,
string country = null,
string language = null, string includeImageLanguage = null, int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default) where T : new()
{
RestRequest req = _client.Create("movie/{movieId}/{method}");
req.AddUrlSegment("movieId", movieId.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("method", movieMethod.GetDescription());
if (country != null)
req.AddParameter("country", country);
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
if (!string.IsNullOrWhiteSpace(includeImageLanguage))
req.AddParameter("include_image_language", includeImageLanguage);
if (page >= 1)
req.AddParameter("page", page.ToString());
if (startDate.HasValue)
req.AddParameter("start_date", startDate.Value.ToString("yyyy-MM-dd"));
if (endDate != null)
req.AddParameter("end_date", endDate.Value.ToString("yyyy-MM-dd"));
T response = await req.GetOfT<T>(cancellationToken).ConfigureAwait(false);
return response;
}
/// <summary>
/// Retrieves all information for a specific movie in relation to the current user account
/// </summary>
/// <param name="movieId">The id of the movie to get the account states for</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<AccountState> GetMovieAccountStateAsync(int movieId, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.UserSession);
RestRequest req = _client.Create("movie/{movieId}/{method}");
req.AddUrlSegment("movieId", movieId.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("method", MovieMethods.AccountStates.GetDescription());
AddSessionId(req, SessionType.UserSession);
using RestResponse<AccountState> response = await req.Get<AccountState>(cancellationToken).ConfigureAwait(false);
return await response.GetDataObject().ConfigureAwait(false);
}
public async Task<AlternativeTitles> GetMovieAlternativeTitlesAsync(int movieId, CancellationToken cancellationToken = default)
{
return await GetMovieAlternativeTitlesAsync(movieId, DefaultCountry, cancellationToken).ConfigureAwait(false);
}
public async Task<AlternativeTitles> GetMovieAlternativeTitlesAsync(int movieId, string country, CancellationToken cancellationToken = default)
{
return await GetMovieMethodInternal<AlternativeTitles>(movieId, MovieMethods.AlternativeTitles, country: country, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<Movie> GetMovieAsync(int movieId, MovieMethods extraMethods = MovieMethods.Undefined, CancellationToken cancellationToken = default)
{
return await GetMovieAsync(movieId, DefaultLanguage, null, extraMethods, cancellationToken).ConfigureAwait(false);
}
public async Task<Movie> GetMovieAsync(string imdbId, MovieMethods extraMethods = MovieMethods.Undefined, CancellationToken cancellationToken = default)
{
return await GetMovieAsync(imdbId, DefaultLanguage, null, extraMethods, cancellationToken).ConfigureAwait(false);
}
public async Task<Movie> GetMovieAsync(int movieId, string language, string includeImageLanguage = null, MovieMethods extraMethods = MovieMethods.Undefined, CancellationToken cancellationToken = default)
{
return await GetMovieAsync(movieId.ToString(CultureInfo.InvariantCulture), language, includeImageLanguage, extraMethods, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Retrieves a movie by its IMDb Id
/// </summary>
/// <param name="imdbId">The IMDb id of the movie OR the TMDb id as string</param>
/// <param name="language">Language to localize the results in.</param>
/// <param name="includeImageLanguage">If specified the api will attempt to return localized image results eg. en,it,es.</param>
/// <param name="extraMethods">A list of additional methods to execute for this req as enum flags</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns>The reqed movie or null if it could not be found</returns>
/// <remarks>Requires a valid user session when specifying the extra method 'AccountStates' flag</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned, see remarks.</exception>
public async Task<Movie> GetMovieAsync(string imdbId, string language, string includeImageLanguage = null, MovieMethods extraMethods = MovieMethods.Undefined, CancellationToken cancellationToken = default)
{
if (extraMethods.HasFlag(MovieMethods.AccountStates))
RequireSessionId(SessionType.UserSession);
RestRequest req = _client.Create("movie/{movieId}");
req.AddUrlSegment("movieId", imdbId);
if (extraMethods.HasFlag(MovieMethods.AccountStates))
AddSessionId(req, SessionType.UserSession);
if (language != null)
req.AddParameter("language", language);
includeImageLanguage ??= DefaultImageLanguage;
if (includeImageLanguage != null)
req.AddParameter("include_image_language", includeImageLanguage);
string appends = string.Join(",",
Enum.GetValues(typeof(MovieMethods))
.OfType<MovieMethods>()
.Except(new[] { MovieMethods.Undefined })
.Where(s => extraMethods.HasFlag(s))
.Select(s => s.GetDescription()));
if (appends != string.Empty)
req.AddParameter("append_to_response", appends);
using RestResponse<Movie> response = await req.Get<Movie>(cancellationToken).ConfigureAwait(false);
if (!response.IsValid)
return null;
Movie item = await response.GetDataObject().ConfigureAwait(false);
// Patch up data, so that the end user won't notice that we share objects between req-types.
if (item.Videos != null)
item.Videos.Id = item.Id;
if (item.AlternativeTitles != null)
item.AlternativeTitles.Id = item.Id;
if (item.Credits != null)
item.Credits.Id = item.Id;
if (item.Releases != null)
item.Releases.Id = item.Id;
if (item.Keywords != null)
item.Keywords.Id = item.Id;
if (item.Translations != null)
item.Translations.Id = item.Id;
if (item.AccountStates != null)
item.AccountStates.Id = item.Id;
if (item.ExternalIds != null)
item.ExternalIds.Id = item.Id;
// Overview is the only field that is HTML encoded from the source.
item.Overview = WebUtility.HtmlDecode(item.Overview);
return item;
}
public async Task<Credits> GetMovieCreditsAsync(int movieId, CancellationToken cancellationToken = default)
{
return await GetMovieMethodInternal<Credits>(movieId, MovieMethods.Credits, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns an object that contains all known exteral id's for the movie related to the specified TMDB id.
/// </summary>
/// <param name="id">The TMDb id of the target movie.</param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<ExternalIdsMovie> GetMovieExternalIdsAsync(int id, CancellationToken cancellationToken = default)
{
return await GetMovieMethodInternal<ExternalIdsMovie>(id, MovieMethods.ExternalIds, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<ImagesWithId> GetMovieImagesAsync(int movieId, CancellationToken cancellationToken = default)
{
return await GetMovieImagesAsync(movieId, DefaultLanguage, null, cancellationToken).ConfigureAwait(false);
}
public async Task<ImagesWithId> GetMovieImagesAsync(int movieId, string language, string includeImageLanguage = null, CancellationToken cancellationToken = default)
{
return await GetMovieMethodInternal<ImagesWithId>(movieId, MovieMethods.Images, language: language, includeImageLanguage: includeImageLanguage, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<KeywordsContainer> GetMovieKeywordsAsync(int movieId, CancellationToken cancellationToken = default)
{
return await GetMovieMethodInternal<KeywordsContainer>(movieId, MovieMethods.Keywords, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<Movie> GetMovieLatestAsync(CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("movie/latest");
using RestResponse<Movie> resp = await req.Get<Movie>(cancellationToken).ConfigureAwait(false);
Movie item = await resp.GetDataObject().ConfigureAwait(false);
// Overview is the only field that is HTML encoded from the source.
if (item != null)
item.Overview = WebUtility.HtmlDecode(item.Overview);
return item;
}
public async Task<SearchContainerWithId<ListResult>> GetMovieListsAsync(int movieId, int page = 0, CancellationToken cancellationToken = default)
{
return await GetMovieListsAsync(movieId, DefaultLanguage, page, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainerWithId<ListResult>> GetMovieListsAsync(int movieId, string language, int page = 0, CancellationToken cancellationToken = default)
{
return await GetMovieMethodInternal<SearchContainerWithId<ListResult>>(movieId, MovieMethods.Lists, page: page, language: language, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchMovie>> GetMovieRecommendationsAsync(int id, int page = 0, CancellationToken cancellationToken = default)
{
return await GetMovieRecommendationsAsync(id, DefaultLanguage, page, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchMovie>> GetMovieRecommendationsAsync(int id, string language, int page = 0, CancellationToken cancellationToken = default)
{
return await GetMovieMethodInternal<SearchContainer<SearchMovie>>(id, MovieMethods.Recommendations, language: language, page: page, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainerWithDates<SearchMovie>> GetMovieNowPlayingListAsync(string language = null, int page = 0, string region = null, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("movie/now_playing");
if (page >= 1)
req.AddParameter("page", page.ToString());
if (language != null)
req.AddParameter("language", language);
if (region != null)
req.AddParameter("region", region);
SearchContainerWithDates<SearchMovie> resp = await req.GetOfT<SearchContainerWithDates<SearchMovie>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainer<SearchMovie>> GetMoviePopularListAsync(string language = null, int page = 0, string region = null, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("movie/popular");
if (page >= 1)
req.AddParameter("page", page.ToString());
if (language != null)
req.AddParameter("language", language);
if (region != null)
req.AddParameter("region", region);
SearchContainer<SearchMovie> resp = await req.GetOfT<SearchContainer<SearchMovie>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<ResultContainer<ReleaseDatesContainer>> GetMovieReleaseDatesAsync(int movieId, CancellationToken cancellationToken = default)
{
return await GetMovieMethodInternal<ResultContainer<ReleaseDatesContainer>>(movieId, MovieMethods.ReleaseDates, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<Releases> GetMovieReleasesAsync(int movieId, CancellationToken cancellationToken = default)
{
return await GetMovieMethodInternal<Releases>(movieId, MovieMethods.Releases, dateFormat: "yyyy-MM-dd", cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainerWithId<ReviewBase>> GetMovieReviewsAsync(int movieId, int page = 0, CancellationToken cancellationToken = default)
{
return await GetMovieReviewsAsync(movieId, DefaultLanguage, page, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainerWithId<ReviewBase>> GetMovieReviewsAsync(int movieId, string language, int page = 0, CancellationToken cancellationToken = default)
{
return await GetMovieMethodInternal<SearchContainerWithId<ReviewBase>>(movieId, MovieMethods.Reviews, page: page, language: language, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchMovie>> GetMovieSimilarAsync(int movieId, int page = 0, CancellationToken cancellationToken = default)
{
return await GetMovieSimilarAsync(movieId, DefaultLanguage, page, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchMovie>> GetMovieSimilarAsync(int movieId, string language, int page = 0, CancellationToken cancellationToken = default)
{
return await GetMovieMethodInternal<SearchContainer<SearchMovie>>(movieId, MovieMethods.Similar, page: page, language: language, dateFormat: "yyyy-MM-dd", cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchMovie>> GetMovieTopRatedListAsync(string language = null, int page = 0, string region = null, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("movie/top_rated");
if (page >= 1)
req.AddParameter("page", page.ToString());
if (language != null)
req.AddParameter("language", language);
if (region != null)
req.AddParameter("region", region);
SearchContainer<SearchMovie> resp = await req.GetOfT<SearchContainer<SearchMovie>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<TranslationsContainer> GetMovieTranslationsAsync(int movieId, CancellationToken cancellationToken = default)
{
return await GetMovieMethodInternal<TranslationsContainer>(movieId, MovieMethods.Translations, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainerWithDates<SearchMovie>> GetMovieUpcomingListAsync(string language = null, int page = 0, string region = null, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("movie/upcoming");
if (page >= 1)
req.AddParameter("page", page.ToString());
if (language != null)
req.AddParameter("language", language);
if (region != null)
req.AddParameter("region", region);
SearchContainerWithDates<SearchMovie> resp = await req.GetOfT<SearchContainerWithDates<SearchMovie>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<ResultContainer<Video>> GetMovieVideosAsync(int movieId, CancellationToken cancellationToken = default)
{
return await GetMovieMethodInternal<ResultContainer<Video>>(movieId, MovieMethods.Videos, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SingleResultContainer<Dictionary<string, WatchProviders>>> GetMovieWatchProvidersAsync(int movieId, CancellationToken cancellationToken = default)
{
return await GetMovieMethodInternal<SingleResultContainer<Dictionary<string, WatchProviders>>>(movieId, MovieMethods.WatchProviders, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<bool> MovieRemoveRatingAsync(int movieId, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.GuestSession);
RestRequest req = _client.Create("movie/{movieId}/rating");
req.AddUrlSegment("movieId", movieId.ToString(CultureInfo.InvariantCulture));
AddSessionId(req);
using RestResponse<PostReply> response = await req.Delete<PostReply>(cancellationToken).ConfigureAwait(false);
// status code 13 = "The item/record was deleted successfully."
PostReply item = await response.GetDataObject().ConfigureAwait(false);
// TODO: Previous code checked for item=null
return item != null && item.StatusCode == 13;
}
/// <summary>
/// Change the rating of a specified movie.
/// </summary>
/// <param name="movieId">The id of the movie to rate</param>
/// <param name="rating">The rating you wish to assign to the specified movie. Value needs to be between 0.5 and 10 and must use increments of 0.5. Ex. using 7.1 will not work and return false.</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns>True if the the movie's rating was successfully updated, false if not</returns>
/// <remarks>Requires a valid guest or user session</remarks>
/// <exception cref="GuestSessionRequiredException">Thrown when the current client object doens't have a guest or user session assigned.</exception>
public async Task<bool> MovieSetRatingAsync(int movieId, double rating, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.GuestSession);
RestRequest req = _client.Create("movie/{movieId}/rating");
req.AddUrlSegment("movieId", movieId.ToString(CultureInfo.InvariantCulture));
AddSessionId(req);
req.SetBody(new { value = rating });
using RestResponse<PostReply> response = await req.Post<PostReply>(cancellationToken).ConfigureAwait(false);
// status code 1 = "Success"
// status code 12 = "The item/record was updated successfully" - Used when an item was previously rated by the user
PostReply item = await response.GetDataObject().ConfigureAwait(false);
// TODO: Previous code checked for item=null
return item.StatusCode == 1 || item.StatusCode == 12;
}
}
}

View File

@ -1,57 +0,0 @@
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.General;
using TMDbLib.Objects.TvShows;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
/// <summary>
/// Retrieves a network by it's TMDb id. A network is a distributor of media content ex. HBO, AMC
/// </summary>
/// <param name="networkId">The id of the network object to retrieve</param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<Network> GetNetworkAsync(int networkId, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("network/{networkId}");
req.AddUrlSegment("networkId", networkId.ToString(CultureInfo.InvariantCulture));
Network response = await req.GetOfT<Network>(cancellationToken).ConfigureAwait(false);
return response;
}
/// <summary>
/// Gets the logos of a network given a TMDb id
/// </summary>
/// <param name="networkId">The TMDb id of the network</param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<NetworkLogos> GetNetworkImagesAsync(int networkId, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("network/{networkId}/images");
req.AddUrlSegment("networkId", networkId.ToString(CultureInfo.InvariantCulture));
NetworkLogos response = await req.GetOfT<NetworkLogos>(cancellationToken).ConfigureAwait(false);
return response;
}
/// <summary>
/// Gets the alternative names of a network given a TMDb id
/// </summary>
/// <param name="networkId">The TMDb id of the network</param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<AlternativeNames> GetNetworkAlternativeNamesAsync(int networkId, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("network/{networkId}/alternative_names");
req.AddUrlSegment("networkId", networkId.ToString(CultureInfo.InvariantCulture));
AlternativeNames response = await req.GetOfT<AlternativeNames>(cancellationToken).ConfigureAwait(false);
return response;
}
}
}

View File

@ -1,170 +0,0 @@
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.General;
using TMDbLib.Objects.People;
using TMDbLib.Rest;
using TMDbLib.Utilities;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
private async Task<T> GetPersonMethodInternal<T>(int personId, PersonMethods personMethod, string dateFormat = null, string country = null, string language = null,
int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default) where T : new()
{
RestRequest req = _client.Create("person/{personId}/{method}");
req.AddUrlSegment("personId", personId.ToString());
req.AddUrlSegment("method", personMethod.GetDescription());
// TODO: Dateformat?
//if (dateFormat != null)
// req.DateFormat = dateFormat;
if (country != null)
req.AddParameter("country", country);
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
if (page >= 1)
req.AddParameter("page", page.ToString());
if (startDate.HasValue)
req.AddParameter("startDate", startDate.Value.ToString("yyyy-MM-dd"));
if (endDate != null)
req.AddParameter("endDate", endDate.Value.ToString("yyyy-MM-dd"));
T resp = await req.GetOfT<T>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<Person> GetLatestPersonAsync(CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("person/latest");
// TODO: Dateformat?
//req.DateFormat = "yyyy-MM-dd";
Person resp = await req.GetOfT<Person>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<Person> GetPersonAsync(int personId, PersonMethods extraMethods = PersonMethods.Undefined,
CancellationToken cancellationToken = default)
{
return await GetPersonAsync(personId, DefaultLanguage, extraMethods, cancellationToken).ConfigureAwait(false);
}
public async Task<Person> GetPersonAsync(int personId, string language, PersonMethods extraMethods = PersonMethods.Undefined, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("person/{personId}");
req.AddUrlSegment("personId", personId.ToString());
if (language != null)
req.AddParameter("language", language);
string appends = string.Join(",",
Enum.GetValues(typeof(PersonMethods))
.OfType<PersonMethods>()
.Except(new[] { PersonMethods.Undefined })
.Where(s => extraMethods.HasFlag(s))
.Select(s => s.GetDescription()));
if (appends != string.Empty)
req.AddParameter("append_to_response", appends);
// TODO: Dateformat?
//req.DateFormat = "yyyy-MM-dd";
using RestResponse<Person> response = await req.Get<Person>(cancellationToken).ConfigureAwait(false);
if (!response.IsValid)
return null;
Person item = await response.GetDataObject().ConfigureAwait(false);
// Patch up data, so that the end user won't notice that we share objects between request-types.
if (item != null)
{
if (item.Images != null)
item.Images.Id = item.Id;
if (item.TvCredits != null)
item.TvCredits.Id = item.Id;
if (item.MovieCredits != null)
item.MovieCredits.Id = item.Id;
}
return item;
}
public async Task<ExternalIdsPerson> GetPersonExternalIdsAsync(int personId, CancellationToken cancellationToken = default)
{
return await GetPersonMethodInternal<ExternalIdsPerson>(personId, PersonMethods.ExternalIds, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<ProfileImages> GetPersonImagesAsync(int personId, CancellationToken cancellationToken = default)
{
return await GetPersonMethodInternal<ProfileImages>(personId, PersonMethods.Images, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<PersonResult>> GetPersonListAsync(PersonListType type, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req;
switch (type)
{
case PersonListType.Popular:
req = _client.Create("person/popular");
break;
default:
throw new ArgumentOutOfRangeException(nameof(type));
}
if (page >= 1)
req.AddParameter("page", page.ToString());
// TODO: Dateformat?
//req.DateFormat = "yyyy-MM-dd";
SearchContainer<PersonResult> resp = await req.GetOfT<SearchContainer<PersonResult>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<MovieCredits> GetPersonMovieCreditsAsync(int personId, CancellationToken cancellationToken = default)
{
return await GetPersonMovieCreditsAsync(personId, DefaultLanguage, cancellationToken).ConfigureAwait(false);
}
public async Task<MovieCredits> GetPersonMovieCreditsAsync(int personId, string language, CancellationToken cancellationToken = default)
{
return await GetPersonMethodInternal<MovieCredits>(personId, PersonMethods.MovieCredits, language: language, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainerWithId<TaggedImage>> GetPersonTaggedImagesAsync(int personId, int page, CancellationToken cancellationToken = default)
{
return await GetPersonTaggedImagesAsync(personId, DefaultLanguage, page, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainerWithId<TaggedImage>> GetPersonTaggedImagesAsync(int personId, string language, int page, CancellationToken cancellationToken = default)
{
return await GetPersonMethodInternal<SearchContainerWithId<TaggedImage>>(personId, PersonMethods.TaggedImages, language: language, page: page, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<TvCredits> GetPersonTvCreditsAsync(int personId, CancellationToken cancellationToken = default)
{
return await GetPersonTvCreditsAsync(personId, DefaultLanguage, cancellationToken).ConfigureAwait(false);
}
public async Task<TvCredits> GetPersonTvCreditsAsync(int personId, string language, CancellationToken cancellationToken = default)
{
return await GetPersonMethodInternal<TvCredits>(personId, PersonMethods.TvCredits, language: language, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
}

View File

@ -1,23 +0,0 @@
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Reviews;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
public async Task<Review> GetReviewAsync(string reviewId, CancellationToken cancellationToken = default)
{
RestRequest request = _client.Create("review/{reviewId}");
request.AddUrlSegment("reviewId", reviewId);
// TODO: Dateformat?
//request.DateFormat = "yyyy-MM-dd";
Review resp = await request.GetOfT<Review>(cancellationToken).ConfigureAwait(false);
return resp;
}
}
}

View File

@ -1,112 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Search;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
private async Task<T> SearchMethodInternal<T>(string method, string query, int page, string language = null, bool? includeAdult = null, int year = 0, string dateFormat = null, string region = null, int primaryReleaseYear = 0, int firstAirDateYear = 0, CancellationToken cancellationToken = default) where T : new()
{
RestRequest req = _client.Create("search/{method}");
req.AddUrlSegment("method", method);
req.AddParameter("query", query);
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
if (page >= 1)
req.AddParameter("page", page.ToString());
if (year >= 1)
req.AddParameter("year", year.ToString());
if (includeAdult.HasValue)
req.AddParameter("include_adult", includeAdult.Value ? "true" : "false");
// TODO: Dateformat?
//if (dateFormat != null)
// req.DateFormat = dateFormat;
if (!string.IsNullOrWhiteSpace(region))
req.AddParameter("region", region);
if (primaryReleaseYear >= 1)
req.AddParameter("primary_release_year", primaryReleaseYear.ToString());
if (firstAirDateYear >= 1)
req.AddParameter("first_air_date_year", firstAirDateYear.ToString());
T resp = await req.GetOfT<T>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainer<SearchCollection>> SearchCollectionAsync(string query, int page = 0, CancellationToken cancellationToken = default)
{
return await SearchCollectionAsync(query, DefaultLanguage, page, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchCollection>> SearchCollectionAsync(string query, string language, int page = 0, CancellationToken cancellationToken = default)
{
return await SearchMethodInternal<SearchContainer<SearchCollection>>("collection", query, page, language, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchCompany>> SearchCompanyAsync(string query, int page = 0, CancellationToken cancellationToken = default)
{
return await SearchMethodInternal<SearchContainer<SearchCompany>>("company", query, page, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchKeyword>> SearchKeywordAsync(string query, int page = 0, CancellationToken cancellationToken = default)
{
return await SearchMethodInternal<SearchContainer<SearchKeyword>>("keyword", query, page, cancellationToken: cancellationToken).ConfigureAwait(false);
}
[Obsolete("20200701 No longer present in public API")]
public async Task<SearchContainer<SearchList>> SearchListAsync(string query, int page = 0, bool includeAdult = false, CancellationToken cancellationToken = default)
{
return await SearchMethodInternal<SearchContainer<SearchList>>("list", query, page, includeAdult: includeAdult, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchMovie>> SearchMovieAsync(string query, int page = 0, bool includeAdult = false, int year = 0, string region = null, int primaryReleaseYear = 0, CancellationToken cancellationToken = default)
{
return await SearchMovieAsync(query, DefaultLanguage, page, includeAdult, year, region, primaryReleaseYear, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchMovie>> SearchMovieAsync(string query, string language, int page = 0, bool includeAdult = false, int year = 0, string region = null, int primaryReleaseYear = 0, CancellationToken cancellationToken = default)
{
return await SearchMethodInternal<SearchContainer<SearchMovie>>("movie", query, page, language, includeAdult, year, "yyyy-MM-dd", region, primaryReleaseYear, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchBase>> SearchMultiAsync(string query, int page = 0, bool includeAdult = false, int year = 0, string region = null, CancellationToken cancellationToken = default)
{
return await SearchMultiAsync(query, DefaultLanguage, page, includeAdult, year, region, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchBase>> SearchMultiAsync(string query, string language, int page = 0, bool includeAdult = false, int year = 0, string region = null, CancellationToken cancellationToken = default)
{
return await SearchMethodInternal<SearchContainer<SearchBase>>("multi", query, page, language, includeAdult, year, "yyyy-MM-dd", region, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchPerson>> SearchPersonAsync(string query, int page = 0, bool includeAdult = false, string region = null, CancellationToken cancellationToken = default)
{
return await SearchPersonAsync(query, DefaultLanguage, page, includeAdult, region, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchPerson>> SearchPersonAsync(string query, string language, int page = 0, bool includeAdult = false, string region = null, CancellationToken cancellationToken = default)
{
return await SearchMethodInternal<SearchContainer<SearchPerson>>("person", query, page, language, includeAdult, region: region, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchTv>> SearchTvShowAsync(string query, int page = 0, bool includeAdult = false, int firstAirDateYear = 0, CancellationToken cancellationToken = default)
{
return await SearchTvShowAsync(query, DefaultLanguage, page, includeAdult, firstAirDateYear, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchTv>> SearchTvShowAsync(string query, string language, int page = 0, bool includeAdult = false, int firstAirDateYear = 0, CancellationToken cancellationToken = default)
{
return await SearchMethodInternal<SearchContainer<SearchTv>>("tv", query, page, language, includeAdult, firstAirDateYear: firstAirDateYear, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
}

View File

@ -1,52 +0,0 @@
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Search;
using TMDbLib.Objects.Trending;
using TMDbLib.Rest;
using TMDbLib.Utilities;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
public async Task<SearchContainer<SearchMovie>> GetTrendingMoviesAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("trending/movie/{time_window}");
req.AddUrlSegment("time_window", timeWindow.GetDescription());
if (page >= 1)
req.AddQueryString("page", page.ToString());
SearchContainer<SearchMovie> resp = await req.GetOfT<SearchContainer<SearchMovie>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainer<SearchTv>> GetTrendingTvAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("trending/tv/{time_window}");
req.AddUrlSegment("time_window", timeWindow.GetDescription());
if (page >= 1)
req.AddQueryString("page", page.ToString());
SearchContainer<SearchTv> resp = await req.GetOfT<SearchContainer<SearchTv>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainer<SearchPerson>> GetTrendingPeopleAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("trending/person/{time_window}");
req.AddUrlSegment("time_window", timeWindow.GetDescription());
if (page >= 1)
req.AddQueryString("page", page.ToString());
SearchContainer<SearchPerson> resp = await req.GetOfT<SearchContainer<SearchPerson>>(cancellationToken).ConfigureAwait(false);
return resp;
}
}
}

View File

@ -1,34 +0,0 @@
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.TvShows;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
/// <summary>
/// Retrieve a collection of tv episode groups by id
/// </summary>
/// <param name="id">Episode group id</param>
/// <param name="language">If specified the api will attempt to return a localized result. ex: en,it,es </param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns>The requested collection of tv episode groups</returns>
public async Task<TvGroupCollection> GetTvEpisodeGroupsAsync(string id, string language = null, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("tv/episode_group/{id}");
req.AddUrlSegment("id", id);
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
using RestResponse<TvGroupCollection> response = await req.Get<TvGroupCollection>(cancellationToken).ConfigureAwait(false);
if (!response.IsValid)
return null;
return await response.GetDataObject().ConfigureAwait(false);
}
}
}

View File

@ -1,219 +0,0 @@
using System;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Authentication;
using TMDbLib.Objects.General;
using TMDbLib.Objects.TvShows;
using TMDbLib.Rest;
using TMDbLib.Utilities;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
private async Task<T> GetTvEpisodeMethodInternal<T>(int tvShowId, int seasonNumber, int episodeNumber, TvEpisodeMethods tvShowMethod, string dateFormat = null, string language = null, CancellationToken cancellationToken = default) where T : new()
{
RestRequest req = _client.Create("tv/{id}/season/{season_number}/episode/{episode_number}/{method}");
req.AddUrlSegment("id", tvShowId.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("season_number", seasonNumber.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("episode_number", episodeNumber.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("method", tvShowMethod.GetDescription());
// TODO: Dateformat?
//if (dateFormat != null)
// req.DateFormat = dateFormat;
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
T resp = await req.GetOfT<T>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<TvEpisodeAccountState> GetTvEpisodeAccountStateAsync(int tvShowId, int seasonNumber, int episodeNumber, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.UserSession);
RestRequest req = _client.Create("tv/{id}/season/{season_number}/episode/{episode_number}/account_states");
req.AddUrlSegment("id", tvShowId.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("season_number", seasonNumber.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("episode_number", episodeNumber.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("method", TvEpisodeMethods.AccountStates.GetDescription());
AddSessionId(req, SessionType.UserSession);
using RestResponse<TvEpisodeAccountState> response = await req.Get<TvEpisodeAccountState>(cancellationToken).ConfigureAwait(false);
return await response.GetDataObject().ConfigureAwait(false);
}
/// <summary>
/// Retrieve a specific episode using TMDb id of the associated tv show.
/// </summary>
/// <param name="tvShowId">TMDb id of the tv show the desired episode belongs to.</param>
/// <param name="seasonNumber">The season number of the season the episode belongs to. Note use 0 for specials.</param>
/// <param name="episodeNumber">The episode number of the episode you want to retrieve.</param>
/// <param name="extraMethods">Enum flags indicating any additional data that should be fetched in the same request.</param>
/// <param name="language">If specified the api will attempt to return a localized result. ex: en,it,es </param>
/// <param name="includeImageLanguage">If specified the api will attempt to return localized image results eg. en,it,es.</param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<TvEpisode> GetTvEpisodeAsync(int tvShowId, int seasonNumber, int episodeNumber, TvEpisodeMethods extraMethods = TvEpisodeMethods.Undefined, string language = null, string includeImageLanguage = null, CancellationToken cancellationToken = default)
{
if (extraMethods.HasFlag(TvEpisodeMethods.AccountStates))
RequireSessionId(SessionType.UserSession);
RestRequest req = _client.Create("tv/{id}/season/{season_number}/episode/{episode_number}");
req.AddUrlSegment("id", tvShowId.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("season_number", seasonNumber.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("episode_number", episodeNumber.ToString(CultureInfo.InvariantCulture));
if (extraMethods.HasFlag(TvEpisodeMethods.AccountStates))
AddSessionId(req, SessionType.UserSession);
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
includeImageLanguage ??= DefaultImageLanguage;
if (!string.IsNullOrWhiteSpace(includeImageLanguage))
req.AddParameter("include_image_language", includeImageLanguage);
string appends = string.Join(",",
Enum.GetValues(typeof(TvEpisodeMethods))
.OfType<TvEpisodeMethods>()
.Except(new[] { TvEpisodeMethods.Undefined })
.Where(s => extraMethods.HasFlag(s))
.Select(s => s.GetDescription()));
if (appends != string.Empty)
req.AddParameter("append_to_response", appends);
using RestResponse<TvEpisode> response = await req.Get<TvEpisode>(cancellationToken).ConfigureAwait(false);
if (!response.IsValid)
return null;
TvEpisode item = await response.GetDataObject().ConfigureAwait(false);
// No data to patch up so return
if (item == null)
return null;
// Patch up data, so that the end user won't notice that we share objects between request-types.
if (item.Videos != null)
item.Videos.Id = item.Id ?? 0;
if (item.Credits != null)
item.Credits.Id = item.Id ?? 0;
if (item.Images != null)
item.Images.Id = item.Id ?? 0;
if (item.ExternalIds != null)
item.ExternalIds.Id = item.Id ?? 0;
return item;
}
public async Task<ResultContainer<TvEpisodeInfo>> GetTvEpisodesScreenedTheatricallyAsync(int tvShowId, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("tv/{tv_id}/screened_theatrically");
req.AddUrlSegment("tv_id", tvShowId.ToString(CultureInfo.InvariantCulture));
return await req.GetOfT<ResultContainer<TvEpisodeInfo>>(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns a credits object for the specified episode.
/// </summary>
/// <param name="tvShowId">The TMDb id of the target tv show.</param>
/// <param name="seasonNumber">The season number of the season the episode belongs to. Note use 0 for specials.</param>
/// <param name="episodeNumber">The episode number of the episode you want to retrieve information for.</param>
/// <param name="language">If specified the api will attempt to return a localized result. ex: en,it,es </param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<CreditsWithGuestStars> GetTvEpisodeCreditsAsync(int tvShowId, int seasonNumber, int episodeNumber, string language = null, CancellationToken cancellationToken = default)
{
return await GetTvEpisodeMethodInternal<CreditsWithGuestStars>(tvShowId, seasonNumber, episodeNumber, TvEpisodeMethods.Credits, dateFormat: "yyyy-MM-dd", language: language, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns an object that contains all known exteral id's for the specified episode.
/// </summary>
/// <param name="tvShowId">The TMDb id of the target tv show.</param>
/// <param name="seasonNumber">The season number of the season the episode belongs to. Note use 0 for specials.</param>
/// <param name="episodeNumber">The episode number of the episode you want to retrieve information for.</param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<ExternalIdsTvEpisode> GetTvEpisodeExternalIdsAsync(int tvShowId, int seasonNumber, int episodeNumber, CancellationToken cancellationToken = default)
{
return await GetTvEpisodeMethodInternal<ExternalIdsTvEpisode>(tvShowId, seasonNumber, episodeNumber, TvEpisodeMethods.ExternalIds, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Retrieves all images all related to the season of specified episode.
/// </summary>
/// <param name="tvShowId">The TMDb id of the target tv show.</param>
/// <param name="seasonNumber">The season number of the season the episode belongs to. Note use 0 for specials.</param>
/// <param name="episodeNumber">The episode number of the episode you want to retrieve information for.</param>
/// <param name="language">
/// If specified the api will attempt to return a localized result. ex: en,it,es.
/// For images this means that the image might contain language specifc text
/// </param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<StillImages> GetTvEpisodeImagesAsync(int tvShowId, int seasonNumber, int episodeNumber, string language = null, CancellationToken cancellationToken = default)
{
return await GetTvEpisodeMethodInternal<StillImages>(tvShowId, seasonNumber, episodeNumber, TvEpisodeMethods.Images, language: language, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<ResultContainer<Video>> GetTvEpisodeVideosAsync(int tvShowId, int seasonNumber, int episodeNumber, CancellationToken cancellationToken = default)
{
return await GetTvEpisodeMethodInternal<ResultContainer<Video>>(tvShowId, seasonNumber, episodeNumber, TvEpisodeMethods.Videos, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<bool> TvEpisodeRemoveRatingAsync(int tvShowId, int seasonNumber, int episodeNumber, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.GuestSession);
RestRequest req = _client.Create("tv/{id}/season/{season_number}/episode/{episode_number}/rating");
req.AddUrlSegment("id", tvShowId.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("season_number", seasonNumber.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("episode_number", episodeNumber.ToString(CultureInfo.InvariantCulture));
AddSessionId(req);
using RestResponse<PostReply> response = await req.Delete<PostReply>(cancellationToken).ConfigureAwait(false);
// status code 13 = "The item/record was deleted successfully."
PostReply item = await response.GetDataObject().ConfigureAwait(false);
// TODO: Original code had a check for item=null
return item.StatusCode == 13;
}
public async Task<bool> TvEpisodeSetRatingAsync(int tvShowId, int seasonNumber, int episodeNumber, double rating, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.GuestSession);
RestRequest req = _client.Create("tv/{id}/season/{season_number}/episode/{episode_number}/rating");
req.AddUrlSegment("id", tvShowId.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("season_number", seasonNumber.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("episode_number", episodeNumber.ToString(CultureInfo.InvariantCulture));
AddSessionId(req);
req.SetBody(new { value = rating });
using RestResponse<PostReply> response = await req.Post<PostReply>(cancellationToken).ConfigureAwait(false);
// status code 1 = "Success"
// status code 12 = "The item/record was updated successfully" - Used when an item was previously rated by the user
PostReply item = await response.GetDataObject().ConfigureAwait(false);
// TODO: Original code had a check for item=null
return item.StatusCode == 1 || item.StatusCode == 12;
}
}
}

View File

@ -1,164 +0,0 @@
using System;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Authentication;
using TMDbLib.Objects.General;
using TMDbLib.Objects.TvShows;
using TMDbLib.Rest;
using TMDbLib.Utilities;
using Credits = TMDbLib.Objects.TvShows.Credits;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
private async Task<T> GetTvSeasonMethodInternal<T>(int tvShowId, int seasonNumber, TvSeasonMethods tvShowMethod, string dateFormat = null, string language = null, CancellationToken cancellationToken = default) where T : new()
{
RestRequest req = _client.Create("tv/{id}/season/{season_number}/{method}");
req.AddUrlSegment("id", tvShowId.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("season_number", seasonNumber.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("method", tvShowMethod.GetDescription());
// TODO: Dateformat?
//if (dateFormat != null)
// req.DateFormat = dateFormat;
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
T response = await req.GetOfT<T>(cancellationToken).ConfigureAwait(false);
return response;
}
public async Task<ResultContainer<TvEpisodeAccountStateWithNumber>> GetTvSeasonAccountStateAsync(int tvShowId, int seasonNumber, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.UserSession);
RestRequest req = _client.Create("tv/{id}/season/{season_number}/account_states");
req.AddUrlSegment("id", tvShowId.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("season_number", seasonNumber.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("method", TvEpisodeMethods.AccountStates.GetDescription());
AddSessionId(req, SessionType.UserSession);
using RestResponse<ResultContainer<TvEpisodeAccountStateWithNumber>> response = await req.Get<ResultContainer<TvEpisodeAccountStateWithNumber>>(cancellationToken).ConfigureAwait(false);
return await response.GetDataObject().ConfigureAwait(false);
}
/// <summary>
/// Retrieve a season for a specifc tv Show by id.
/// </summary>
/// <param name="tvShowId">TMDb id of the tv show the desired season belongs to.</param>
/// <param name="seasonNumber">The season number of the season you want to retrieve. Note use 0 for specials.</param>
/// <param name="extraMethods">Enum flags indicating any additional data that should be fetched in the same request.</param>
/// <param name="language">If specified the api will attempt to return a localized result. ex: en,it,es </param>
/// <param name="includeImageLanguage">If specified the api will attempt to return localized image results eg. en,it,es.</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns>The requested season for the specified tv show</returns>
public async Task<TvSeason> GetTvSeasonAsync(int tvShowId, int seasonNumber, TvSeasonMethods extraMethods = TvSeasonMethods.Undefined, string language = null, string includeImageLanguage = null, CancellationToken cancellationToken = default)
{
if (extraMethods.HasFlag(TvSeasonMethods.AccountStates))
RequireSessionId(SessionType.UserSession);
RestRequest req = _client.Create("tv/{id}/season/{season_number}");
req.AddUrlSegment("id", tvShowId.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("season_number", seasonNumber.ToString(CultureInfo.InvariantCulture));
if (extraMethods.HasFlag(TvSeasonMethods.AccountStates))
AddSessionId(req, SessionType.UserSession);
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
includeImageLanguage ??= DefaultImageLanguage;
if (!string.IsNullOrWhiteSpace(includeImageLanguage))
req.AddParameter("include_image_language", includeImageLanguage);
string appends = string.Join(",",
Enum.GetValues(typeof(TvSeasonMethods))
.OfType<TvSeasonMethods>()
.Except(new[] { TvSeasonMethods.Undefined })
.Where(s => extraMethods.HasFlag(s))
.Select(s => s.GetDescription()));
if (appends != string.Empty)
req.AddParameter("append_to_response", appends);
using RestResponse<TvSeason> response = await req.Get<TvSeason>(cancellationToken).ConfigureAwait(false);
if (!response.IsValid)
return null;
TvSeason item = await response.GetDataObject().ConfigureAwait(false);
// Nothing to patch up
if (item == null)
return null;
if (item.Images != null)
item.Images.Id = item.Id ?? 0;
if (item.Credits != null)
item.Credits.Id = item.Id ?? 0;
if (item.ExternalIds != null)
item.ExternalIds.Id = item.Id ?? 0;
if (item.AccountStates != null)
item.AccountStates.Id = item.Id ?? 0;
if (item.Videos != null)
item.Videos.Id = item.Id ?? 0;
return item;
}
/// <summary>
/// Returns a credits object for the season of the tv show associated with the provided TMDb id.
/// </summary>
/// <param name="tvShowId">The TMDb id of the target tv show.</param>
/// <param name="seasonNumber">The season number of the season you want to retrieve information for. Note use 0 for specials.</param>
/// <param name="language">If specified the api will attempt to return a localized result. ex: en,it,es </param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<Credits> GetTvSeasonCreditsAsync(int tvShowId, int seasonNumber, string language = null, CancellationToken cancellationToken = default)
{
return await GetTvSeasonMethodInternal<Credits>(tvShowId, seasonNumber, TvSeasonMethods.Credits, dateFormat: "yyyy-MM-dd", language: language, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns an object that contains all known exteral id's for the season of the tv show related to the specified TMDB id.
/// </summary>
/// <param name="tvShowId">The TMDb id of the target tv show.</param>
/// <param name="seasonNumber">The season number of the season you want to retrieve information for. Note use 0 for specials.</param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<ExternalIdsTvSeason> GetTvSeasonExternalIdsAsync(int tvShowId, int seasonNumber, CancellationToken cancellationToken = default)
{
return await GetTvSeasonMethodInternal<ExternalIdsTvSeason>(tvShowId, seasonNumber, TvSeasonMethods.ExternalIds, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Retrieves all images all related to the season of specified tv show.
/// </summary>
/// <param name="tvShowId">The TMDb id of the target tv show.</param>
/// <param name="seasonNumber">The season number of the season you want to retrieve information for. Note use 0 for specials.</param>
/// <param name="language">
/// If specified the api will attempt to return a localized result. ex: en,it,es.
/// For images this means that the image might contain language specifc text
/// </param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<PosterImages> GetTvSeasonImagesAsync(int tvShowId, int seasonNumber, string language = null, CancellationToken cancellationToken = default)
{
return await GetTvSeasonMethodInternal<PosterImages>(tvShowId, seasonNumber, TvSeasonMethods.Images, language: language, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<ResultContainer<Video>> GetTvSeasonVideosAsync(int tvShowId, int seasonNumber, string language = null, CancellationToken cancellationToken = default)
{
return await GetTvSeasonMethodInternal<ResultContainer<Video>>(tvShowId, seasonNumber, TvSeasonMethods.Videos, language: language, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
}

View File

@ -1,377 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Authentication;
using TMDbLib.Objects.Changes;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Reviews;
using TMDbLib.Objects.Search;
using TMDbLib.Objects.TvShows;
using TMDbLib.Rest;
using TMDbLib.Utilities;
using Credits = TMDbLib.Objects.TvShows.Credits;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
private async Task<T> GetTvShowMethodInternal<T>(int id, TvShowMethods tvShowMethod, string dateFormat = null, string language = null, string includeImageLanguage = null, int page = 0, CancellationToken cancellationToken = default) where T : new()
{
RestRequest req = _client.Create("tv/{id}/{method}");
req.AddUrlSegment("id", id.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("method", tvShowMethod.GetDescription());
// TODO: Dateformat?
//if (dateFormat != null)
// req.DateFormat = dateFormat;
if (page > 0)
req.AddParameter("page", page.ToString());
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
includeImageLanguage ??= DefaultImageLanguage;
if (!string.IsNullOrWhiteSpace(includeImageLanguage))
req.AddParameter("include_image_language", includeImageLanguage);
T resp = await req.GetOfT<T>(cancellationToken).ConfigureAwait(false);
return resp;
}
private async Task<SearchContainer<SearchTv>> GetTvShowListInternal(int page, string language, string tvShowListType, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("tv/" + tvShowListType);
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
if (page >= 1)
req.AddParameter("page", page.ToString());
SearchContainer<SearchTv> response = await req.GetOfT<SearchContainer<SearchTv>>(cancellationToken).ConfigureAwait(false);
return response;
}
public async Task<TvShow> GetLatestTvShowAsync(CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("tv/latest");
TvShow resp = await req.GetOfT<TvShow>(cancellationToken).ConfigureAwait(false);
return resp;
}
/// <summary>
/// Retrieves all information for a specific tv show in relation to the current user account
/// </summary>
/// <param name="tvShowId">The id of the tv show to get the account states for</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <remarks>Requires a valid user session</remarks>
/// <exception cref="UserSessionRequiredException">Thrown when the current client object doens't have a user session assigned.</exception>
public async Task<AccountState> GetTvShowAccountStateAsync(int tvShowId, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.UserSession);
RestRequest req = _client.Create("tv/{tvShowId}/{method}");
req.AddUrlSegment("tvShowId", tvShowId.ToString(CultureInfo.InvariantCulture));
req.AddUrlSegment("method", TvShowMethods.AccountStates.GetDescription());
AddSessionId(req, SessionType.UserSession);
using RestResponse<AccountState> response = await req.Get<AccountState>(cancellationToken).ConfigureAwait(false);
return await response.GetDataObject().ConfigureAwait(false);
}
public async Task<ResultContainer<AlternativeTitle>> GetTvShowAlternativeTitlesAsync(int id, CancellationToken cancellationToken = default)
{
return await GetTvShowMethodInternal<ResultContainer<AlternativeTitle>>(id, TvShowMethods.AlternativeTitles, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Retrieve a tv Show by id.
/// </summary>
/// <param name="id">TMDb id of the tv show to retrieve.</param>
/// <param name="extraMethods">Enum flags indicating any additional data that should be fetched in the same request.</param>
/// <param name="language">If specified the api will attempt to return a localized result. ex: en,it,es.</param>
/// <param name="includeImageLanguage">If specified the api will attempt to return localized image results eg. en,it,es.</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns>The requested Tv Show</returns>
public async Task<TvShow> GetTvShowAsync(int id, TvShowMethods extraMethods = TvShowMethods.Undefined, string language = null, string includeImageLanguage = null, CancellationToken cancellationToken = default)
{
if (extraMethods.HasFlag(TvShowMethods.AccountStates))
RequireSessionId(SessionType.UserSession);
RestRequest req = _client.Create("tv/{id}");
req.AddUrlSegment("id", id.ToString(CultureInfo.InvariantCulture));
if (extraMethods.HasFlag(TvShowMethods.AccountStates))
AddSessionId(req, SessionType.UserSession);
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
if (!string.IsNullOrWhiteSpace(includeImageLanguage))
req.AddParameter("include_image_language", includeImageLanguage);
string appends = string.Join(",",
Enum.GetValues(typeof(TvShowMethods))
.OfType<TvShowMethods>()
.Except(new[] { TvShowMethods.Undefined })
.Where(s => extraMethods.HasFlag(s))
.Select(s => s.GetDescription()));
if (appends != string.Empty)
req.AddParameter("append_to_response", appends);
using RestResponse<TvShow> response = await req.Get<TvShow>(cancellationToken).ConfigureAwait(false);
if (!response.IsValid)
return null;
TvShow item = await response.GetDataObject().ConfigureAwait(false);
// No data to patch up so return
if (item == null)
return null;
// Patch up data, so that the end user won't notice that we share objects between request-types.
if (item.Translations != null)
item.Translations.Id = id;
if (item.AccountStates != null)
item.AccountStates.Id = id;
if (item.Recommendations != null)
item.Recommendations.Id = id;
if (item.ExternalIds != null)
item.ExternalIds.Id = id;
return item;
}
public async Task<ChangesContainer> GetTvShowChangesAsync(int id, CancellationToken cancellationToken = default)
{
return await GetTvShowMethodInternal<ChangesContainer>(id, TvShowMethods.Changes, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<ResultContainer<ContentRating>> GetTvShowContentRatingsAsync(int id, CancellationToken cancellationToken = default)
{
return await GetTvShowMethodInternal<ResultContainer<ContentRating>>(id, TvShowMethods.ContentRatings, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns a credits object for the tv show associated with the provided TMDb id.
/// </summary>
/// <param name="id">The TMDb id of the target tv show.</param>
/// <param name="language">If specified the api will attempt to return a localized result. ex: en,it,es </param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<Credits> GetTvShowCreditsAsync(int id, string language = null, CancellationToken cancellationToken = default)
{
return await GetTvShowMethodInternal<Credits>(id, TvShowMethods.Credits, "yyyy-MM-dd", language, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns a credits object for the aggragation of tv show associated with the provided TMDb id.
/// </summary>
/// <param name="id">The TMDb id of the target tv show.</param>
/// <param name="language">If specified the api will attempt to return a localized result. ex: en,it,es </param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns></returns>
public async Task<CreditsAggregate> GetAggregateCredits(int id, string language = null, CancellationToken cancellationToken = default)
{
return await GetTvShowMethodInternal<CreditsAggregate>(id, TvShowMethods.CreditsAggregate, language: language, page: 0, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns an object that contains all known exteral id's for the tv show related to the specified TMDB id.
/// </summary>
/// <param name="id">The TMDb id of the target tv show.</param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<ExternalIdsTvShow> GetTvShowExternalIdsAsync(int id, CancellationToken cancellationToken = default)
{
return await GetTvShowMethodInternal<ExternalIdsTvShow>(id, TvShowMethods.ExternalIds, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Retrieves all images all related to the specified tv show.
/// </summary>
/// <param name="id">The TMDb id of the target tv show.</param>
/// <param name="language">
/// If specified the api will attempt to return a localized result. ex: en,it,es.
/// For images this means that the image might contain language specifc text
/// </param>
/// <param name="includeImageLanguage">If you want to include a fallback language (especially useful for backdrops) you can use the include_image_language parameter. This should be a comma separated value like so: include_image_language=en,null.</param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<ImagesWithId> GetTvShowImagesAsync(int id, string language = null, string includeImageLanguage = null, CancellationToken cancellationToken = default)
{
return await GetTvShowMethodInternal<ImagesWithId>(id, TvShowMethods.Images, language: language, includeImageLanguage: includeImageLanguage, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainerWithId<ReviewBase>> GetTvShowReviewsAsync(int id, string language = null, int page = 0, CancellationToken cancellationToken = default)
{
return await GetTvShowMethodInternal<SearchContainerWithId<ReviewBase>>(id, TvShowMethods.Reviews, language: language, page: page, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<ResultContainer<Keyword>> GetTvShowKeywordsAsync(int id, CancellationToken cancellationToken = default)
{
return await GetTvShowMethodInternal<ResultContainer<Keyword>>(id, TvShowMethods.Keywords, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Fetches a dynamic list of TV Shows
/// </summary>
/// <param name="list">Type of list to fetch</param>
/// <param name="page">Page</param>
/// <param name="timezone">Only relevant for list type AiringToday</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns></returns>
public async Task<SearchContainer<SearchTv>> GetTvShowListAsync(TvShowListType list, int page = 0, string timezone = null, CancellationToken cancellationToken = default)
{
return await GetTvShowListAsync(list, DefaultLanguage, page, timezone, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Fetches a dynamic list of TV Shows
/// </summary>
/// <param name="list">Type of list to fetch</param>
/// <param name="language">Language</param>
/// <param name="page">Page</param>
/// <param name="timezone">Only relevant for list type AiringToday</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns></returns>
public async Task<SearchContainer<SearchTv>> GetTvShowListAsync(TvShowListType list, string language, int page = 0, string timezone = null, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("tv/{method}");
req.AddUrlSegment("method", list.GetDescription());
if (page > 0)
req.AddParameter("page", page.ToString());
if (!string.IsNullOrEmpty(timezone))
req.AddParameter("timezone", timezone);
language ??= DefaultLanguage;
if (!string.IsNullOrWhiteSpace(language))
req.AddParameter("language", language);
SearchContainer<SearchTv> resp = await req.GetOfT<SearchContainer<SearchTv>>(cancellationToken).ConfigureAwait(false);
return resp;
}
/// <summary>
/// Get the list of popular TV shows. This list refreshes every day.
/// </summary>
/// <returns>
/// Returns the basic information about a tv show.
/// For additional data use the main GetTvShowAsync method using the tv show id as parameter.
/// </returns>
public async Task<SearchContainer<SearchTv>> GetTvShowPopularAsync(int page = -1, string language = null, CancellationToken cancellationToken = default)
{
return await GetTvShowListInternal(page, language, "popular", cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchTv>> GetTvShowSimilarAsync(int id, int page = 0, CancellationToken cancellationToken = default)
{
return await GetTvShowSimilarAsync(id, DefaultLanguage, page, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchTv>> GetTvShowSimilarAsync(int id, string language, int page = 0, CancellationToken cancellationToken = default)
{
return await GetTvShowMethodInternal<SearchContainer<SearchTv>>(id, TvShowMethods.Similar, language: language, page: page, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchTv>> GetTvShowRecommendationsAsync(int id, int page = 0, CancellationToken cancellationToken = default)
{
return await GetTvShowRecommendationsAsync(id, DefaultLanguage, page, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<SearchTv>> GetTvShowRecommendationsAsync(int id, string language, int page = 0, CancellationToken cancellationToken = default)
{
return await GetTvShowMethodInternal<SearchContainer<SearchTv>>(id, TvShowMethods.Recommendations, language: language, page: page, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get the list of top rated TV shows. By default, this list will only include TV shows that have 2 or more votes. This list refreshes every day.
/// </summary>
/// <returns>
/// Returns the basic information about a tv show.
/// For additional data use the main GetTvShowAsync method using the tv show id as parameter
/// </returns>
public async Task<SearchContainer<SearchTv>> GetTvShowTopRatedAsync(int page = -1, string language = null, CancellationToken cancellationToken = default)
{
return await GetTvShowListInternal(page, language, "top_rated", cancellationToken).ConfigureAwait(false);
}
public async Task<TranslationsContainerTv> GetTvShowTranslationsAsync(int id, CancellationToken cancellationToken = default)
{
return await GetTvShowMethodInternal<TranslationsContainerTv>(id, TvShowMethods.Translations, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<ResultContainer<Video>> GetTvShowVideosAsync(int id, CancellationToken cancellationToken = default)
{
return await GetTvShowMethodInternal<ResultContainer<Video>>(id, TvShowMethods.Videos, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<SingleResultContainer<Dictionary<string, WatchProviders>>> GetTvShowWatchProvidersAsync(int id, CancellationToken cancellationToken = default)
{
return await GetTvShowMethodInternal<SingleResultContainer<Dictionary<string, WatchProviders>>>(id, TvShowMethods.WatchProviders, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task<bool> TvShowRemoveRatingAsync(int tvShowId, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.GuestSession);
RestRequest req = _client.Create("tv/{tvShowId}/rating");
req.AddUrlSegment("tvShowId", tvShowId.ToString(CultureInfo.InvariantCulture));
AddSessionId(req);
using RestResponse<PostReply> response = await req.Delete<PostReply>(cancellationToken).ConfigureAwait(false);
// status code 13 = "The item/record was deleted successfully."
PostReply item = await response.GetDataObject().ConfigureAwait(false);
// TODO: Original code had a check for item=null
return item.StatusCode == 13;
}
/// <summary>
/// Change the rating of a specified tv show.
/// </summary>
/// <param name="tvShowId">The id of the tv show to rate</param>
/// <param name="rating">The rating you wish to assign to the specified tv show. Value needs to be between 0.5 and 10 and must use increments of 0.5. Ex. using 7.1 will not work and return false.</param>
/// <param name="cancellationToken">A cancellation token</param>
/// <returns>True if the the tv show's rating was successfully updated, false if not</returns>
/// <remarks>Requires a valid guest or user session</remarks>
/// <exception cref="GuestSessionRequiredException">Thrown when the current client object doens't have a guest or user session assigned.</exception>
public async Task<bool> TvShowSetRatingAsync(int tvShowId, double rating, CancellationToken cancellationToken = default)
{
RequireSessionId(SessionType.GuestSession);
RestRequest req = _client.Create("tv/{tvShowId}/rating");
req.AddUrlSegment("tvShowId", tvShowId.ToString(CultureInfo.InvariantCulture));
AddSessionId(req);
req.SetBody(new { value = rating });
using RestResponse<PostReply> response = await req.Post<PostReply>(cancellationToken).ConfigureAwait(false);
// status code 1 = "Success"
// status code 12 = "The item/record was updated successfully" - Used when an item was previously rated by the user
PostReply item = await response.GetDataObject().ConfigureAwait(false);
// TODO: Original code had a check for item=null
return item.StatusCode == 1 || item.StatusCode == 12;
}
}
}

View File

@ -1,64 +0,0 @@
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.General;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
/// <summary>
/// Returns a list of all of the countries TMDb has watch provider (OTT/streaming) data for.
/// </summary>
/// <param name="cancellationToken">A cancellation token</param>
/// <remarks>Uses <see cref="DefaultLanguage"/> to translate data</remarks>
public async Task<ResultContainer<WatchProviderRegion>> GetWatchProviderRegionsAsync(CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("watch/providers/regions");
if (DefaultLanguage != null)
req.AddParameter("language", DefaultLanguage);
ResultContainer<WatchProviderRegion> response = await req.GetOfT<ResultContainer<WatchProviderRegion>>(cancellationToken).ConfigureAwait(false);
return response;
}
/// <summary>
/// Returns a list of the watch provider (OTT/streaming) data TMDb has available for movies.
/// </summary>
/// <param name="cancellationToken">A cancellation token</param>
/// <remarks>Uses <see cref="DefaultCountry"/> and <see cref="DefaultLanguage"/> to filter or translate data</remarks>
public async Task<ResultContainer<WatchProviderItem>> GetMovieWatchProvidersAsync(CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("watch/providers/movie");
if (DefaultLanguage != null)
req.AddParameter("language", DefaultLanguage);
if (DefaultCountry != null)
req.AddParameter("watch_region", DefaultCountry);
ResultContainer<WatchProviderItem> response = await req.GetOfT<ResultContainer<WatchProviderItem>>(cancellationToken).ConfigureAwait(false);
return response;
}
/// <summary>
/// Returns a list of the watch provider (OTT/streaming) data TMDb has available for shows.
/// </summary>
/// <param name="cancellationToken">A cancellation token</param>
/// <remarks>Uses <see cref="DefaultCountry"/> and <see cref="DefaultLanguage"/> to filter or translate data</remarks>
public async Task<ResultContainer<WatchProviderItem>> GetTvWatchProvidersAsync(CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("watch/providers/tv");
if (DefaultLanguage != null)
req.AddParameter("language", DefaultLanguage);
if (DefaultCountry != null)
req.AddParameter("watch_region", DefaultCountry);
ResultContainer<WatchProviderItem> response = await req.GetOfT<ResultContainer<WatchProviderItem>>(cancellationToken).ConfigureAwait(false);
return response;
}
}
}

View File

@ -1,34 +0,0 @@
using Newtonsoft.Json;
namespace TMDbLib.Objects.Account
{
public class AccountDetails
{
[JsonProperty("avatar")]
public Avatar Avatar { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("include_adult")]
public bool IncludeAdult { get; set; }
/// <summary>
/// A country code, e.g. US
/// </summary>
[JsonProperty("iso_3166_1")]
public string Iso_3166_1 { get; set; }
/// <summary>
/// A language code, e.g. en
/// </summary>
[JsonProperty("iso_639_1")]
public string Iso_639_1 { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
}
}

View File

@ -1,11 +0,0 @@
using TMDbLib.Utilities;
namespace TMDbLib.Objects.Account
{
public enum AccountSortBy
{
Undefined = 0,
[EnumValue("created_at")]
CreatedAt = 1,
}
}

View File

@ -1,10 +0,0 @@
using Newtonsoft.Json;
namespace TMDbLib.Objects.Account
{
public class Avatar
{
[JsonProperty("gravatar")]
public Gravatar Gravatar { get; set; }
}
}

View File

@ -1,10 +0,0 @@
using Newtonsoft.Json;
namespace TMDbLib.Objects.Account
{
public class Gravatar
{
[JsonProperty("hash")]
public string Hash { get; set; }
}
}

View File

@ -1,28 +0,0 @@
using System;
using Newtonsoft.Json;
using TMDbLib.Utilities.Converters;
namespace TMDbLib.Objects.Authentication
{
/// <summary>
/// A guest session can be used to rate movies/tv shows without having a registered TMDb user account.
/// You should only generate a single guest session per user (or device) as you will be able to attach the ratings to a TMDb user account in the future.
/// There is also IP limits in place so you should always make sure it's the end user doing the guest session actions.
/// If a guest session is not used for the first time within 24 hours, it will be automatically discarded.
/// </summary>
public class GuestSession
{
/// <summary>
/// The date / time before which the session must be used for the first time else it will expire. Time is expressed as local time.
/// </summary>
[JsonProperty("expires_at")]
[JsonConverter(typeof(CustomDatetimeFormatConverter))]
public DateTime ExpiresAt { get; set; }
[JsonProperty("guest_session_id")]
public string GuestSessionId { get; set; }
[JsonProperty("success")]
public bool Success { get; set; }
}
}

View File

@ -1,13 +0,0 @@
using System;
namespace TMDbLib.Objects.Authentication
{
public class GuestSessionRequiredException : Exception
{
public GuestSessionRequiredException()
: base("The method you called requires a valid guest or user session to be set on the client object. Please use the 'SetSessionInformation' method to do so.")
{
}
}
}

View File

@ -1,9 +0,0 @@
namespace TMDbLib.Objects.Authentication
{
public enum SessionType
{
Unassigned = 0,
GuestSession = 1,
UserSession = 2
}
}

View File

@ -1,31 +0,0 @@
using System;
using Newtonsoft.Json;
using TMDbLib.Utilities.Converters;
namespace TMDbLib.Objects.Authentication
{
/// <summary>
/// A request token is required in order to request a user authenticated session id.
/// Request tokens will expire after 60 minutes.
/// As soon as a valid session id has been created the token will be useless.
/// </summary>
public class Token
{
// This field is populated by custom code
[JsonIgnore]
public string AuthenticationCallback { get; set; }
/// <summary>
/// The date / time before which the token must be used, else it will expire. Time is expressed as local time.
/// </summary>
[JsonProperty("expires_at")]
[JsonConverter(typeof(CustomDatetimeFormatConverter))]
public DateTime ExpiresAt { get; set; }
[JsonProperty("request_token")]
public string RequestToken { get; set; }
[JsonProperty("success")]
public bool Success { get; set; }
}
}

View File

@ -1,16 +0,0 @@
using Newtonsoft.Json;
namespace TMDbLib.Objects.Authentication
{
/// <summary>
/// Session object that can be retrieved after the user has correctly authenticated himself on the TMDb site. (using the referal url from the token provided previously)
/// </summary>
public class UserSession
{
[JsonProperty("session_id")]
public string SessionId { get; set; }
[JsonProperty("success")]
public bool Success { get; set; }
}
}

View File

@ -1,13 +0,0 @@
using System;
namespace TMDbLib.Objects.Authentication
{
public class UserSessionRequiredException : Exception
{
public UserSessionRequiredException()
: base("The method you called requires a valid user session to be set on the client object. Please use the 'SetSessionInformation' method to do so.")
{
}
}
}

View File

@ -1,9 +0,0 @@
namespace TMDbLib.Objects.Certifications
{
public class CertificationItem
{
public string Certification { get; set; }
public string Meaning { get; set; }
public int Order { get; set; }
}
}

View File

@ -1,9 +0,0 @@
using System.Collections.Generic;
namespace TMDbLib.Objects.Certifications
{
public class CertificationsContainer
{
public Dictionary<string, List<CertificationItem>> Certifications { get; set; }
}
}

View File

@ -1,14 +0,0 @@
using System.Collections.Generic;
using Newtonsoft.Json;
namespace TMDbLib.Objects.Changes
{
public class Change
{
[JsonProperty("items")]
public List<ChangeItemBase> Items { get; set; }
[JsonProperty("key")]
public string Key { get; set; }
}
}

View File

@ -1,27 +0,0 @@
using Newtonsoft.Json;
using TMDbLib.Utilities;
using TMDbLib.Utilities.Converters;
namespace TMDbLib.Objects.Changes
{
[JsonConverter(typeof(EnumStringValueConverter))]
public enum ChangeAction
{
Unknown,
[EnumValue("added")]
Added = 1,
[EnumValue("created")]
Created = 2,
[EnumValue("updated")]
Updated = 3,
[EnumValue("deleted")]
Deleted = 4,
[EnumValue("destroyed")]
Destroyed = 5
}
}

View File

@ -1,15 +0,0 @@
using Newtonsoft.Json;
namespace TMDbLib.Objects.Changes
{
public class ChangeItemAdded : ChangeItemBase
{
public ChangeItemAdded()
{
Action = ChangeAction.Added;
}
[JsonProperty("value")]
public object Value { get; set; }
}
}

View File

@ -1,26 +0,0 @@
using System;
using Newtonsoft.Json;
using TMDbLib.Utilities.Converters;
namespace TMDbLib.Objects.Changes
{
public abstract class ChangeItemBase
{
[JsonProperty("action")]
public ChangeAction Action { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// A language code, e.g. en
/// This field is not always set
/// </summary>
[JsonProperty("iso_639_1")]
public string Iso_639_1 { get; set; }
[JsonProperty("time")]
[JsonConverter(typeof(TmdbUtcTimeConverter))]
public DateTime Time { get; set; }
}
}

View File

@ -1,10 +0,0 @@
namespace TMDbLib.Objects.Changes
{
public class ChangeItemCreated : ChangeItemBase
{
public ChangeItemCreated()
{
Action = ChangeAction.Created;
}
}
}

View File

@ -1,15 +0,0 @@
using Newtonsoft.Json;
namespace TMDbLib.Objects.Changes
{
public class ChangeItemDeleted : ChangeItemBase
{
public ChangeItemDeleted()
{
Action = ChangeAction.Deleted;
}
[JsonProperty("original_value")]
public object OriginalValue { get; set; }
}
}

View File

@ -1,15 +0,0 @@
using Newtonsoft.Json;
namespace TMDbLib.Objects.Changes
{
public class ChangeItemDestroyed : ChangeItemBase
{
public ChangeItemDestroyed()
{
Action = ChangeAction.Destroyed;
}
[JsonProperty("value")]
public object Value { get; set; }
}
}

View File

@ -1,18 +0,0 @@
using Newtonsoft.Json;
namespace TMDbLib.Objects.Changes
{
public class ChangeItemUpdated : ChangeItemBase
{
public ChangeItemUpdated()
{
Action = ChangeAction.Updated;
}
[JsonProperty("original_value")]
public object OriginalValue { get; set; }
[JsonProperty("value")]
public object Value { get; set; }
}
}

View File

@ -1,11 +0,0 @@
using System.Collections.Generic;
using Newtonsoft.Json;
namespace TMDbLib.Objects.Changes
{
public class ChangesContainer
{
[JsonProperty("changes")]
public List<Change> Changes { get; set; }
}
}

View File

@ -1,15 +0,0 @@
using Newtonsoft.Json;
using TMDbLib.Utilities.Converters;
namespace TMDbLib.Objects.Changes
{
public class ChangesListItem
{
[JsonProperty("adult")]
public bool? Adult { get; set; }
[JsonProperty("id")]
[JsonConverter(typeof(TmdbNullIntAsZero))]
public int Id { get; set; }
}
}

View File

@ -1,31 +0,0 @@
using System.Collections.Generic;
using Newtonsoft.Json;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Search;
namespace TMDbLib.Objects.Collections
{
public class Collection
{
[JsonProperty("backdrop_path")]
public string BackdropPath { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("images")]
public Images Images { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("overview")]
public string Overview { get; set; }
[JsonProperty("parts")]
public List<SearchMovie> Parts { get; set; }
[JsonProperty("poster_path")]
public string PosterPath { get; set; }
}
}

View File

@ -1,14 +0,0 @@
using System;
using TMDbLib.Utilities;
namespace TMDbLib.Objects.Collections
{
[Flags]
public enum CollectionMethods
{
[EnumValue("Undefined")]
Undefined = 0,
[EnumValue("images")]
Images = 1
}
}

View File

@ -1,36 +0,0 @@
using Newtonsoft.Json;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Search;
namespace TMDbLib.Objects.Companies
{
public class Company
{
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("headquarters")]
public string Headquarters { get; set; }
[JsonProperty("homepage")]
public string Homepage { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("logo_path")]
public string LogoPath { get; set; }
[JsonProperty("movies")]
public SearchContainer<SearchMovie> Movies { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("parent_company")]
public SearchCompany ParentCompany { get; set; }
[JsonProperty("origin_country")]
public string OriginCountry { get; set; }
}
}

View File

@ -1,14 +0,0 @@
using System;
using TMDbLib.Utilities;
namespace TMDbLib.Objects.Companies
{
[Flags]
public enum CompanyMethods
{
[EnumValue("Undefined")]
Undefined = 0,
[EnumValue("movies")]
Movies = 1
}
}

View File

@ -1,14 +0,0 @@
using Newtonsoft.Json;
using System.Collections.Generic;
namespace TMDbLib.Objects.Configuration
{
public class APIConfiguration
{
[JsonProperty("images")]
public APIConfigurationImages Images { get; set; }
[JsonProperty("change_keys")]
public List<string> ChangeKeys { get; set; }
}
}

View File

@ -1,30 +0,0 @@
using Newtonsoft.Json;
using System.Collections.Generic;
namespace TMDbLib.Objects.Configuration
{
public class APIConfigurationImages
{
[JsonProperty("base_url")]
public string BaseUrl { get; set; }
[JsonProperty("secure_base_url")]
public string SecureBaseUrl { get; set; }
[JsonProperty("backdrop_sizes")]
public List<string> BackdropSizes { get; set; }
[JsonProperty("logo_sizes")]
public List<string> LogoSizes { get; set; }
[JsonProperty("poster_sizes")]
public List<string> PosterSizes { get; set; }
[JsonProperty("profile_sizes")]
public List<string> ProfileSizes { get; set; }
[JsonProperty("still_sizes")]
public List<string> StillSizes { get; set; }
}
}

View File

@ -1,13 +0,0 @@
using Newtonsoft.Json;
namespace TMDbLib.Objects.Countries
{
public class Country
{
[JsonProperty("iso_3166_1")]
public string Iso_3166_1 { get; set; }
[JsonProperty("english_name")]
public string EnglishName { get; set; }
}
}

View File

@ -1,29 +0,0 @@
using Newtonsoft.Json;
using TMDbLib.Objects.General;
namespace TMDbLib.Objects.Credit
{
public class Credit
{
[JsonProperty("credit_type")]
public CreditType CreditType { get; set; }
[JsonProperty("department")]
public string Department { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("job")]
public string Job { get; set; }
[JsonProperty("media")]
public CreditMedia Media { get; set; }
[JsonProperty("media_type")]
public MediaType MediaType { get; set; }
[JsonProperty("person")]
public CreditPerson Person { get; set; }
}
}

View File

@ -1,26 +0,0 @@
using System;
using Newtonsoft.Json;
namespace TMDbLib.Objects.Credit
{
public class CreditEpisode
{
[JsonProperty("air_date")]
public DateTime? AirDate { get; set; }
[JsonProperty("episode_number")]
public int EpisodeNumber { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("overview")]
public string Overview { get; set; }
[JsonProperty("season_number")]
public int SeasonNumber { get; set; }
[JsonProperty("still_path")]
public string StillPath { get; set; }
}
}

View File

@ -1,26 +0,0 @@
using System.Collections.Generic;
using Newtonsoft.Json;
namespace TMDbLib.Objects.Credit
{
public class CreditMedia
{
[JsonProperty("character")]
public string Character { get; set; }
[JsonProperty("episodes")]
public List<CreditEpisode> Episodes { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("original_name")]
public string OriginalName { get; set; }
[JsonProperty("seasons")]
public List<CreditSeason> Seasons { get; set; }
}
}

View File

@ -1,13 +0,0 @@
using Newtonsoft.Json;
namespace TMDbLib.Objects.Credit
{
public class CreditPerson
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
}

View File

@ -1,17 +0,0 @@
using System;
using Newtonsoft.Json;
namespace TMDbLib.Objects.Credit
{
public class CreditSeason
{
[JsonProperty("air_date")]
public DateTime? AirDate { get; set; }
[JsonProperty("poster_path")]
public string PosterPath { get; set; }
[JsonProperty("season_number")]
public int SeasonNumber { get; set; }
}
}

View File

@ -1,32 +0,0 @@
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Client;
using TMDbLib.Objects.General;
using TMDbLib.Utilities;
namespace TMDbLib.Objects.Discover
{
public abstract class DiscoverBase<T>
{
private readonly TMDbClient _client;
private readonly string _endpoint;
protected readonly SimpleNamedValueCollection Parameters;
public DiscoverBase(string endpoint, TMDbClient client)
{
_endpoint = endpoint;
_client = client;
Parameters = new SimpleNamedValueCollection();
}
public async Task<SearchContainer<T>> Query(int page = 0, CancellationToken cancellationToken = default)
{
return await Query(_client.DefaultLanguage, page, cancellationToken).ConfigureAwait(false);
}
public async Task<SearchContainer<T>> Query(string language, int page = 0, CancellationToken cancellationToken = default)
{
return await _client.DiscoverPerformAsync<T>(_endpoint, language, page, Parameters, cancellationToken).ConfigureAwait(false);
}
}
}

View File

@ -1,441 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using TMDbLib.Objects.Companies;
using TMDbLib.Objects.General;
using TMDbLib.Client;
using TMDbLib.Objects.Search;
using TMDbLib.Objects.TvShows;
using TMDbLib.Utilities;
namespace TMDbLib.Objects.Discover
{
public class DiscoverMovie : DiscoverBase<SearchMovie>
{
public DiscoverMovie(TMDbClient client)
: base("discover/movie", client)
{
}
private void ClearCertification()
{
Parameters.Remove("certification_country");
Parameters.Remove("certification");
Parameters.Remove("certification.lte");
Parameters.Remove("certification.gte");
}
/// <summary>
/// Toggle the inclusion of adult titles. Expected value is a boolean, true or false. Default is false.
/// </summary>
public DiscoverMovie IncludeAdultMovies(bool include = true)
{
Parameters["include_adult"] = include.ToString();
return this;
}
/// <summary>
/// Toggle the inclusion of items marked as a video. Expected value is a boolean, true or false. Default is true.
/// </summary>
public DiscoverMovie IncludeVideoMovies(bool include = true)
{
Parameters["include_video"] = include.ToString();
return this;
}
/// <summary>
/// Only include movies that have this person id added as a cast member. Expected value is an integer (the id of a person).
/// This method performs an AND query.
/// </summary>
public DiscoverMovie IncludeWithAllOfCast(IEnumerable<int> castIds)
{
Parameters["with_cast"] = string.Join(",", castIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Only include movies that have this person id added as a cast member.
/// This method performs an AND query.
/// </summary>
public DiscoverMovie IncludeWithAllOfCast(IEnumerable<Cast> casts)
{
return IncludeWithAllOfCast(casts.Select(s => s.Id));
}
/// <summary>
/// Only include movies that have this company id added as a crew member. Expected value is an integer (the id of a company).
/// This method performs an AND query.
/// </summary>
public DiscoverMovie IncludeWithAllOfCompany(IEnumerable<int> companyIds)
{
Parameters["with_companies"] = string.Join(",", companyIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Only include movies that have this company id added as a crew member.
/// This method performs an AND query.
/// </summary>
public DiscoverMovie IncludeWithAllOfCompany(IEnumerable<Company> companies)
{
return IncludeWithAllOfCompany(companies.Select(s => s.Id));
}
/// <summary>
/// Only include movies that have this person id added as a crew member. Expected value is an integer (the id of a person).
/// This method performs an AND query.
/// </summary>
public DiscoverMovie IncludeWithAllOfCrew(IEnumerable<int> crewIds)
{
Parameters["with_crew"] = string.Join(",", crewIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Only include movies that have this person id added as a crew member.
/// This method performs an AND query.
/// </summary>
public DiscoverMovie IncludeWithAllOfCrew(IEnumerable<Crew> crews)
{
return IncludeWithAllOfCrew(crews.Select(s => s.Id));
}
/// <summary>
/// Only include movies with the specified genres. Expected value is an integer (the id of a genre).
/// This method performs an AND query.
/// </summary>
public DiscoverMovie IncludeWithAllOfGenre(IEnumerable<int> genreIds)
{
Parameters["with_genres"] = string.Join(",", genreIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Only include movies with the specified genres.
/// This method performs an AND query.
/// </summary>
public DiscoverMovie IncludeWithAllOfGenre(IEnumerable<Genre> genres)
{
return IncludeWithAllOfGenre(genres.Select(s => s.Id));
}
/// <summary>
/// Only include movies with the specified keywords. Expected value is an integer (the id of a keyword).
/// This method performs an AND query.
/// </summary>
public DiscoverMovie IncludeWithAllOfKeywords(IEnumerable<int> keywordIds)
{
Parameters["with_keywords"] = string.Join(",", keywordIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Only include movies with the specified keywords.
/// This method performs an AND query.
/// </summary>
public DiscoverMovie IncludeWithAllOfKeywords(IEnumerable<Genre> keywords)
{
return IncludeWithAllOfKeywords(keywords.Select(s => s.Id));
}
/// <summary>
/// Only include movies that have these person id's added as a cast or crew member. Expected value is an integer (the id or ids of a person).
/// This method performs an AND query.
/// </summary>
public DiscoverMovie IncludeWithAllOfPeople(IEnumerable<int> peopleIds)
{
Parameters["with_people"] = string.Join(",", peopleIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Only include movies that have these person id's added as a cast or crew member.
/// This method performs an AND query.
/// </summary>
public DiscoverMovie IncludeWithAllOfPeople(IEnumerable<Genre> people)
{
return IncludeWithAllOfPeople(people.Select(s => s.Id));
}
/// <summary>
/// Only include movies that have this person id added as a cast member. Expected value is an integer (the id of a person).
/// This method performs an OR query.
/// </summary>
public DiscoverMovie IncludeWithAnyOfCast(IEnumerable<int> castIds)
{
Parameters["with_cast"] = string.Join("|", castIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Only include movies that have this person id added as a cast member.
/// This method performs an OR query.
/// </summary>
public DiscoverMovie IncludeWithAnyOfCast(IEnumerable<Cast> casts)
{
return IncludeWithAnyOfCast(casts.Select(s => s.Id));
}
/// <summary>
/// Only include movies that have this company id added as a crew member. Expected value is an integer (the id of a company).
/// This method performs an OR query.
/// </summary>
public DiscoverMovie IncludeWithAnyOfCompany(IEnumerable<int> companyIds)
{
Parameters["with_companies"] = string.Join("|", companyIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Only include movies that have this company id added as a crew member.
/// This method performs an OR query.
/// </summary>
public DiscoverMovie IncludeWithAnyOfCompany(IEnumerable<Company> companies)
{
return IncludeWithAnyOfCompany(companies.Select(s => s.Id));
}
/// <summary>
/// Only include movies that have this person id added as a crew member. Expected value is an integer (the id of a person).
/// This method performs an OR query.
/// </summary>
public DiscoverMovie IncludeWithAnyOfCrew(IEnumerable<int> crewIds)
{
Parameters["with_crew"] = string.Join("|", crewIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Only include movies that have this person id added as a crew member.
/// This method performs an OR query.
/// </summary>
public DiscoverMovie IncludeWithAnyOfCrew(IEnumerable<Crew> crews)
{
return IncludeWithAnyOfCrew(crews.Select(s => s.Id));
}
/// <summary>
/// Only include movies with the specified genres. Expected value is an integer (the id of a genre).
/// This method performs an OR query.
/// </summary>
public DiscoverMovie IncludeWithAnyOfGenre(IEnumerable<int> castIds)
{
Parameters["with_genres"] = string.Join("|", castIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Only include movies with the specified genres.
/// This method performs an OR query.
/// </summary>
public DiscoverMovie IncludeWithAnyOfGenre(IEnumerable<Genre> genres)
{
return IncludeWithAnyOfGenre(genres.Select(s => s.Id));
}
/// <summary>
/// Only include movies with the specified keywords. Expected value is an integer (the id of a keyword).
/// This method performs an OR query.
/// </summary>
public DiscoverMovie IncludeWithAnyOfKeywords(IEnumerable<int> keywordIds)
{
Parameters["with_keywords"] = string.Join("|", keywordIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Only include movies with the specified keywords.
/// This method performs an OR query.
/// </summary>
public DiscoverMovie IncludeWithAnyOfKeywords(IEnumerable<Genre> keywords)
{
return IncludeWithAnyOfKeywords(keywords.Select(s => s.Id));
}
/// <summary>
/// Only include movies that have these person id's added as a cast or crew member. Expected value is an integer (the id or ids of a person).
/// This method performs an OR query.
/// </summary>
public DiscoverMovie IncludeWithAnyOfPeople(IEnumerable<int> peopleIds)
{
Parameters["with_people"] = string.Join("|", peopleIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Only include movies that have these person id's added as a cast or crew member.
/// This method performs an OR query.
/// </summary>
public DiscoverMovie IncludeWithAnyOfPeople(IEnumerable<Genre> people)
{
return IncludeWithAnyOfPeople(people.Select(s => s.Id));
}
/// <summary>
/// Available options are: popularity.ascpopularity.descrelease_date.ascrelease_date.descrevenue.ascrevenue.descprimary_release_date.ascprimary_release_date.descoriginal_title.ascoriginal_title.descvote_average.ascvote_average.descvote_count.ascvote_count.desc
/// </summary>
public DiscoverMovie OrderBy(DiscoverMovieSortBy sortBy)
{
Parameters["sort_by"] = sortBy.GetDescription();
return this;
}
/// <summary>
/// Filter the results by all available release dates that have the specified value added as a year. Expected value is an integer (year).
/// </summary>
public DiscoverMovie WhereAnyReleaseDateIsInYear(int year)
{
Parameters["year"] = year.ToString("0000");
return this;
}
/// <summary>
/// Only include movies with this certification. Expected value is a valid certification for the specificed 'certification_country'.
/// </summary>
public DiscoverMovie WhereCertificationIs(string country, string certification)
{
ClearCertification();
Parameters["certification_country"] = country;
Parameters["certification"] = certification;
return this;
}
/// <summary>
/// Only include movies with this certification and lower. Expected value is a valid certification for the specificed 'certification_country'.
/// </summary>
public DiscoverMovie WhereCertificationIsAtMost(string country, string maxCertification)
{
ClearCertification();
Parameters["certification_country"] = country;
Parameters["certification.lte"] = maxCertification;
return this;
}
/// <summary>
/// Only include movies with this certification and higher. Expected value is a valid certification for the specificed 'certification_country'.
/// </summary>
public DiscoverMovie WhereCertificationIsAtLeast(string country, string minCertification)
{
ClearCertification();
Parameters["certification_country"] = country;
Parameters["certification.gte"] = minCertification;
return this;
}
/// <summary>
/// Filter by the primary release date and only include those which are greater than or equal to the specified value. Expected format is YYYY-MM-DD.
/// </summary>
public DiscoverMovie WherePrimaryReleaseDateIsAfter(DateTime date)
{
Parameters["primary_release_date.gte"] = date.ToString("yyyy-MM-dd");
return this;
}
/// <summary>
/// Filter by the primary release date and only include those which are greater than or equal to the specified value. Expected format is YYYY-MM-DD.
/// </summary>
public DiscoverMovie WherePrimaryReleaseDateIsBefore(DateTime date)
{
Parameters["primary_release_date.lte"] = date.ToString("yyyy-MM-dd");
return this;
}
/// <summary>
/// Filter the results so that only the primary release date year has this value. Expected value is a year.
/// </summary>
public DiscoverMovie WherePrimaryReleaseIsInYear(int year)
{
Parameters["primary_release_year"] = year.ToString("0000");
return this;
}
/// <summary>
/// Filter by all available release dates and only include those which are greater or equal to the specified value. Expected format is YYYY-MM-DD.
/// </summary>
public DiscoverMovie WhereReleaseDateIsAfter(DateTime date)
{
Parameters["release_date.gte"] = date.ToString("yyyy-MM-dd");
return this;
}
/// <summary>
/// Filter by all available release dates and only include those which are less or equal to the specified value. Expected format is YYYY-MM-DD.
/// </summary>
public DiscoverMovie WhereReleaseDateIsBefore(DateTime date)
{
Parameters["release_date.lte"] = date.ToString("yyyy-MM-dd");
return this;
}
/// <summary>
/// Filter movies by their vote average and only include those that have an average rating that is equal to or higher than the specified value. Expected value is a float.
/// </summary>
public DiscoverMovie WhereVoteAverageIsAtLeast(double score)
{
// TODO: Apply culture to the ToString
Parameters["vote_average.gte"] = score.ToString();
return this;
}
/// <summary>
/// Filter movies by their vote average and only include those that have an average rating that is equal to or lower than the specified value. Expected value is a float.
/// </summary>
public DiscoverMovie WhereVoteAverageIsAtMost(double score)
{
// TODO: Apply culture to the ToString
Parameters["vote_average.lte"] = score.ToString();
return this;
}
/// <summary>
/// Filter movies by their vote count and only include movies that have a vote count that is equal to or lower than the specified value.
/// </summary>
public DiscoverMovie WhereVoteCountIsAtLeast(int count)
{
Parameters["vote_count.gte"] = count.ToString();
return this;
}
/// <summary>
/// Filter movies by their vote count and only include movies that have a vote count that is equal to or lower than the specified value. Expected value is an integer.
/// </summary>
public DiscoverMovie WhereVoteCountIsAtMost(int count)
{
Parameters["vote_count.lte"] = count.ToString();
return this;
}
/// <summary>
/// Specifies which region to use for release date filtering (using ISO 3166-1 code)
/// </summary>
public DiscoverMovie WhereReleaseDateIsInRegion(string region)
{
Parameters["region"] = region;
return this;
}
/// <summary>
/// Specifies which language to use for translatable fields
/// </summary>
public DiscoverMovie WhereLanguageIs(string language)
{
Parameters["language"] = language;
return this;
}
/// <summary>
/// Specifies which language to use for translatable fields
/// </summary>
public DiscoverMovie WhereOriginalLanguageIs(string language)
{
Parameters["with_original_language"] = language;
return this;
}
}
}

View File

@ -1,37 +0,0 @@
using TMDbLib.Utilities;
namespace TMDbLib.Objects.Discover
{
public enum DiscoverMovieSortBy
{
Undefined,
[EnumValue("popularity.asc")]
Popularity,
[EnumValue("popularity.desc")]
PopularityDesc,
[EnumValue("release_date.asc")]
ReleaseDate,
[EnumValue("release_date.desc")]
ReleaseDateDesc,
[EnumValue("revenue.asc")]
Revenue,
[EnumValue("revenue.desc")]
RevenueDesc,
[EnumValue("primary_release_date.asc")]
PrimaryReleaseDate,
[EnumValue("primary_release_date.desc")]
PrimaryReleaseDateDesc,
[EnumValue("original_title.asc")]
OriginalTitle,
[EnumValue("original_title.desc")]
OriginalTitleDesc,
[EnumValue("vote_average.asc")]
VoteAverage,
[EnumValue("vote_average.desc")]
VoteAverageDesc,
[EnumValue("vote_count.asc")]
VoteCount,
[EnumValue("vote_count.desc")]
VoteCountDesc
}
}

View File

@ -1,259 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using TMDbLib.Client;
using TMDbLib.Objects.Companies;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Search;
using TMDbLib.Objects.TvShows;
using TMDbLib.Utilities;
namespace TMDbLib.Objects.Discover
{
public class DiscoverTv : DiscoverBase<SearchTv>
{
public DiscoverTv(TMDbClient client)
: base("discover/tv", client)
{
}
/// <summary>
/// Available options are vote_average.desc, vote_average.asc, first_air_date.desc, first_air_date.asc, popularity.desc, popularity.asc
/// </summary>
public DiscoverTv OrderBy(DiscoverTvShowSortBy sortBy)
{
Parameters["sort_by"] = sortBy.GetDescription();
return this;
}
/// <summary>
/// Specify a timeone to calculate proper date offsets. A list of valid timezones can be found by using the timezones/list method.
/// </summary>
public DiscoverTv UseTimezone(string timezone)
{
Parameters["timezone"] = timezone;
return this;
}
/// <summary>
/// The minimum episode air date to include. Expected format is YYYY-MM-DD. Can be used in conjunction with a specified timezone.
/// </summary>
public DiscoverTv WhereAirDateIsAfter(DateTime date)
{
Parameters["air_date.gte"] = date.ToString("yyyy-MM-dd");
return this;
}
/// <summary>
/// The maximum episode air date to include. Expected format is YYYY-MM-DD. Can be used in conjunction with a specified timezone.
/// </summary>
public DiscoverTv WhereAirDateIsBefore(DateTime date)
{
Parameters["air_date.lte"] = date.ToString("yyyy-MM-dd");
return this;
}
/// <summary>
/// The minimum release to include. Expected format is YYYY-MM-DD.
/// </summary>
public DiscoverTv WhereFirstAirDateIsAfter(DateTime date)
{
Parameters["first_air_date.gte"] = date.ToString("yyyy-MM-dd");
return this;
}
/// <summary>
/// The maximum release to include. Expected format is YYYY-MM-DD.
/// </summary>
public DiscoverTv WhereFirstAirDateIsBefore(DateTime date)
{
Parameters["first_air_date.lte"] = date.ToString("yyyy-MM-dd");
return this;
}
/// <summary>
/// Filter the results release dates to matches that include this value. Expected value is a year.
/// </summary>
public DiscoverTv WhereFirstAirDateIsInYear(int year)
{
Parameters["first_air_date_year"] = year.ToString("0000");
return this;
}
/// <summary>
/// Only include TV shows with the specified genres. Expected value is an integer (the id of a genre). Multiple values can be specified. Comma separated indicates an 'AND' query, while a pipe (|) separated value indicates an 'OR'.
/// </summary>
public DiscoverTv WhereGenresInclude(IEnumerable<Genre> genres)
{
return WhereGenresInclude(genres.Select(s => s.Id));
}
/// <summary>
/// Only include TV shows with the specified genres. Expected value is an integer (the id of a genre). Multiple values can be specified. Comma separated indicates an 'AND' query, while a pipe (|) separated value indicates an 'OR'.
/// </summary>
public DiscoverTv WhereGenresInclude(IEnumerable<int> genreIds)
{
Parameters["with_genres"] = string.Join(",", genreIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Filter TV shows to include a specific network. Expected value is an integer (the id of a network). They can be comma separated to indicate an 'AND' query.
/// </summary>
public DiscoverTv WhereNetworksInclude(IEnumerable<Network> networks)
{
return WhereNetworksInclude(networks.Select(s => s.Id));
}
/// <summary>
/// Filter TV shows to include a specific network. Expected value is an integer (the id of a network). They can be comma separated to indicate an 'AND' query.
/// </summary>
public DiscoverTv WhereNetworksInclude(IEnumerable<int> networkIds)
{
Parameters["with_networks"] = string.Join(",", networkIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Only include TV shows that are equal to, or have a higher average rating than this value. Expected value is a float.
/// </summary>
public DiscoverTv WhereVoteAverageIsAtLeast(double score)
{
// TODO: Apply culture to the ToString
Parameters["vote_average.gte"] = score.ToString();
return this;
}
/// <summary>
/// Only include TV shows that are equal to, or have a vote count higher than this value. Expected value is an integer.
/// </summary>
public DiscoverTv WhereVoteCountIsAtLeast(int count)
{
Parameters["vote_count.gte"] = count.ToString();
return this;
}
/// <summary>
/// Specifies which language to use for translatable fields
/// </summary>
public DiscoverTv WhereOriginalLanguageIs(string language)
{
Parameters["with_original_language"] = language;
return this;
}
/// <summary>
/// Only include TV shows that are equal to, or have a runtime higher than this value. Expected value is an integer (minutes).
/// </summary>
public DiscoverTv WhereRuntimeIsAtLeast(int minutes)
{
Parameters["with_runtime.gte"] = minutes.ToString();
return this;
}
/// <summary>
/// Only include TV shows that are equal to, or have a runtime lower than this value. Expected value is an integer (minutes).
/// </summary>
public DiscoverTv WhereRuntimeIsAtMost(int minutes)
{
Parameters["with_runtime.lte"] = minutes.ToString();
return this;
}
/// <summary>
/// Toggle the inclusion of TV shows with null first air data. Expected value is a boolean, true or false.
/// </summary>
public DiscoverTv IncludeNullFirstAirDates(bool include)
{
Parameters["include_null_first_air_dates"] = include.ToString();
return this;
}
/// <summary>
/// Exclude TV shows with the specified genres. Expected value is a list of Generes.
/// </summary>
public DiscoverTv WhereGenresExclude(IEnumerable<Genre> genres)
{
return WhereGenresInclude(genres.Select(s => s.Id));
}
/// <summary>
/// Exclude TV shows with the specified genres. Expected value is an integer (the id of a genre).
/// </summary>
public DiscoverTv WhereGenresExclude(IEnumerable<int> genreIds)
{
Parameters["without_genres"] = string.Join(",", genreIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Only include TV shows with the specified companies. Expected value is an list of companies.
/// </summary>
public DiscoverTv WhereCompaniesInclude(IEnumerable<Company> companies)
{
return WhereCompaniesInclude(companies.Select(s => s.Id));
}
/// <summary>
/// Only include TV shows with the specified companies. Expected value is a list of integer (the id of a company).
/// </summary>
public DiscoverTv WhereCompaniesInclude(IEnumerable<int> companyIds)
{
Parameters["with_companies"] = string.Join(",", companyIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Filter results to include items that have been screened theatrically.
/// </summary>
public DiscoverTv WhereScreenedTheatrically(bool theatrical)
{
Parameters["screened_theatrically"] = theatrical.ToString();
return this;
}
/// <summary>
/// Filter TV shows to include a specific keyword. Expected value is a list of keywords.
/// </summary>
public DiscoverTv WhereKeywordsInclude(IEnumerable<Keyword> keywords)
{
return WhereKeywordsInclude(keywords.Select(s => s.Id));
}
/// <summary>
/// Filter TV shows to include a specific keyword. Expected value is a list of integer (the id of a keyword).
/// </summary>
public DiscoverTv WhereKeywordsInclude(IEnumerable<int> keywordIds)
{
Parameters["with_keywords"] = string.Join(",", keywordIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Filter TV shows to exclude a specific keyword. Expected value is a list of keywords.
/// </summary>
public DiscoverTv WhereKeywordsExclude(IEnumerable<Keyword> keywords)
{
return WhereKeywordsInclude(keywords.Select(s => s.Id));
}
/// <summary>
/// Filter TV shows to exclude a specific keyword. Expected value is a list of integer (the id of a keyword).
/// </summary>
public DiscoverTv WhereKeywordsExclude(IEnumerable<int> keywordIds)
{
Parameters["without_keywords"] = string.Join("|", keywordIds.Select(s => s.ToString()));
return this;
}
/// <summary>
/// Specifies which language to use for translatable fields
/// </summary>
public DiscoverTv WhereLanguageIs(string language)
{
Parameters["language"] = language;
return this;
}
}
}

View File

@ -1,21 +0,0 @@
using TMDbLib.Utilities;
namespace TMDbLib.Objects.Discover
{
public enum DiscoverTvShowSortBy
{
Undefined,
[EnumValue("vote_average.asc")]
VoteAverage,
[EnumValue("vote_average.desc")]
VoteAverageDesc,
[EnumValue("first_air_date.asc")]
FirstAirDate,
[EnumValue("first_air_date.desc")]
FirstAirDateDesc,
[EnumValue("popularity.asc")]
Popularity,
[EnumValue("popularity.desc")]
PopularityDesc
}
}

View File

@ -1,12 +0,0 @@
namespace TMDbLib.Objects.Exceptions
{
public class APIException : TMDbException
{
public TMDbStatusMessage StatusMessage { get; }
public APIException(string message, TMDbStatusMessage statusMessage) : base(message)
{
StatusMessage = statusMessage;
}
}
}

View File

@ -1,15 +0,0 @@
using System.Net;
namespace TMDbLib.Objects.Exceptions
{
public class GeneralHttpException : TMDbException
{
public HttpStatusCode HttpStatusCode { get; }
public GeneralHttpException(HttpStatusCode httpStatusCode)
: base("TMDb returned an unexpected HTTP error")
{
HttpStatusCode = httpStatusCode;
}
}
}

Some files were not shown because too many files have changed in this diff Show More