This commit is contained in:
crobibero
2020-09-08 15:10:57 -06:00
commit d4debbbb18
40 changed files with 2984 additions and 0 deletions
@@ -0,0 +1,32 @@
using System;
namespace Jellyfin.Plugin.Simkl.API.Exceptions
{
/// <inheritdoc />
public class InvalidTokenException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="InvalidTokenException"/> class.
/// </summary>
public InvalidTokenException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InvalidTokenException"/> class.
/// </summary>
/// <param name="msg">The message.</param>
public InvalidTokenException(string msg) : base(msg)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InvalidTokenException"/> class.
/// </summary>
/// <param name="msg">The message.</param>
/// <param name="inner">The inner exception.</param>
public InvalidTokenException(string msg, Exception inner) : base(msg, inner)
{
}
}
}
+14
View File
@@ -0,0 +1,14 @@
using Jellyfin.Plugin.Simkl.API.Responses;
using MediaBrowser.Model.Services;
namespace Jellyfin.Plugin.Simkl.API
{
/// <summary>
/// Get oauth pin.
/// </summary>
[Route("/Simkl/oauth/pin", "GET")]
public class GetPin : IReturn<CodeResponse>
{
// Doesn't receive anything
}
}
+18
View File
@@ -0,0 +1,18 @@
using Jellyfin.Plugin.Simkl.API.Responses;
using MediaBrowser.Model.Services;
namespace Jellyfin.Plugin.Simkl.API
{
/// <summary>
/// Get pin status.
/// </summary>
[Route("/Simkl/oauth/pin/{user_code}", "GET")]
public class GetPinStatus : IReturn<CodeStatusResponse>
{
/// <summary>
/// Gets or sets user code.
/// </summary>
[ApiMember(Name = "user_code", Description = "pin to be introduced by the user", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string UserCode { get; set; }
}
}
@@ -0,0 +1,22 @@
using System;
using Jellyfin.Plugin.Simkl.API.Objects;
using MediaBrowser.Model.Services;
namespace Jellyfin.Plugin.Simkl.API
{
/// <summary>
/// Get user settings.
/// </summary>
[Route("/Simkl/users/settings/{userId}", "GET")]
public class GetUserSettings : IReturn<UserSettings>
{
/// <summary>
/// Gets or sets user id.
/// </summary>
/// <remarks>
/// Note: In the future, when we'll have config for more than one user, we'll use a parameter.
/// </remarks>
[ApiMember(Name = "id", Description = "user id", IsRequired = true, DataType = "Guid", ParameterType = "path", Verb = "GET")]
public Guid UserId { get; set; }
}
}
@@ -0,0 +1,18 @@
namespace Jellyfin.Plugin.Simkl.API.Objects
{
/// <summary>
/// Account.
/// </summary>
public class Account
{
/// <summary>
/// Gets or sets account id.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Gets or sets timezone.
/// </summary>
public string Timezone { get; set; }
}
}
@@ -0,0 +1,13 @@
namespace Jellyfin.Plugin.Simkl.API.Objects
{
/// <summary>
/// Connections.
/// </summary>
public class Connections
{
/// <summary>
/// Gets or sets a value indicating whether facebook.
/// </summary>
public bool Facebook { get; set; }
}
}
@@ -0,0 +1,18 @@
namespace Jellyfin.Plugin.Simkl.API.Objects
{
/// <summary>
/// Season.
/// </summary>
public class Season
{
/// <summary>
/// Gets or sets the season number.
/// </summary>
public int? Number { get; set; }
/// <summary>
/// Gets or sets the episodes.
/// </summary>
public ShowEpisode[] Episodes { get; set; }
}
}
@@ -0,0 +1,14 @@
namespace Jellyfin.Plugin.Simkl.API.Objects
{
/// <summary>
/// Show episode.
/// </summary>
public class ShowEpisode
{
/// <summary>
/// Gets or sets episode number.
/// </summary>
public int? Number { get; set; }
// TODO: watched_at
}
}
@@ -0,0 +1,41 @@
using System.Text.Json.Serialization;
namespace Jellyfin.Plugin.Simkl.API.Objects
{
/// <summary>
/// Simkl episode container.
/// </summary>
public class SimklEpisode : SimklMediaObject
{
/// <summary>
/// Gets or sets watched at.
/// </summary>
[JsonPropertyName("watched_at")]
public string WatchedAt { get; set; }
/// <summary>
/// Gets or sets ids.
/// </summary>
public override SimklIds Ids { get; set; }
/// <summary>
/// Gets or sets the title.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets the season.
/// </summary>
public int Season { get; set; }
/// <summary>
/// Gets or sets the episode.
/// </summary>
public int Episode { get; set; }
/// <summary>
/// Gets or sets multipart.
/// </summary>
public bool? Multipart { get; set; }
}
}
@@ -0,0 +1,23 @@
namespace Jellyfin.Plugin.Simkl.API.Objects
{
/// <summary>
/// Simkl File.
/// </summary>
public class SimklFile
{
/// <summary>
/// Gets or sets the file.
/// </summary>
public string File { get; set; }
/// <summary>
/// Gets or sets the part.
/// </summary>
public int? Part { get; set; }
/// <summary>
/// Gets or sets the hash.
/// </summary>
public string Hash { get; set; }
}
}
@@ -0,0 +1,37 @@
#pragma warning disable CA2227
using System.Collections.Generic;
namespace Jellyfin.Plugin.Simkl.API.Objects
{
/// <summary>
/// Simkl history container.
/// </summary>
public class SimklHistory
{
/// <summary>
/// Initializes a new instance of the <see cref="SimklHistory"/> class.
/// </summary>
public SimklHistory()
{
Movies = new List<SimklMovie>();
Shows = new List<SimklShow>();
Episodes = new List<SimklEpisode>();
}
/// <summary>
/// Gets or sets list of movies.
/// </summary>
public List<SimklMovie> Movies { get; set; }
/// <summary>
/// Gets or sets the list of shows.
/// </summary>
public List<SimklShow> Shows { get; set; }
/// <summary>
/// Gets or sets the list of episodes.
/// </summary>
public List<SimklEpisode> Episodes { get; set; }
}
}
@@ -0,0 +1,57 @@
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
namespace Jellyfin.Plugin.Simkl.API.Objects
{
/// <summary>
/// Simkl Ids.
/// </summary>
public class SimklIds
{
/// <summary>
/// Initializes a new instance of the <see cref="SimklIds"/> class.
/// </summary>
/// <param name="providerIds">The provider ids.</param>
public SimklIds(Dictionary<string, string> providerIds)
{
foreach (var (key, value) in providerIds)
{
var prop = GetType().GetProperty(key, BindingFlags.IgnoreCase);
if (prop.PropertyType == typeof(int?))
{
prop.SetValue(this, int.Parse(value, NumberStyles.Any, CultureInfo.InvariantCulture));
}
else if (prop.PropertyType == typeof(string))
{
prop.SetValue(this, value);
}
}
}
/// <summary>
/// Gets or sets simkl.
/// </summary>
public int? Simkl { get; set; }
/// <summary>
/// Gets or sets the imdb id.
/// </summary>
public string Imdb { get; set; }
/// <summary>
/// Gets or sets the slug.
/// </summary>
public string Slug { get; set; }
/// <summary>
/// Gets or sets the netflix id.
/// </summary>
public string Netflix { get; set; }
/// <summary>
/// Gets or sets the TMDb id.
/// </summary>
public string Tmdb { get; set; }
}
}
@@ -0,0 +1,13 @@
namespace Jellyfin.Plugin.Simkl.API.Objects
{
/// <summary>
/// Simkl media object.
/// </summary>
public abstract class SimklMediaObject
{
/// <summary>
/// Gets or sets ids.
/// </summary>
public abstract SimklIds Ids { get; set; }
}
}
@@ -0,0 +1,42 @@
using System;
using System.Globalization;
using MediaBrowser.Model.Dto;
namespace Jellyfin.Plugin.Simkl.API.Objects
{
/// <summary>
/// Simkl movie.
/// </summary>
public class SimklMovie : SimklMediaObject
{
/// <summary>
/// Initializes a new instance of the <see cref="SimklMovie"/> class.
/// </summary>
/// <param name="item">The base item dto.</param>
public SimklMovie(BaseItemDto item)
{
Title = item.OriginalTitle;
Year = item.ProductionYear;
Ids = new SimklMovieIds(item.ProviderIds);
WatchedAt = DateTime.UtcNow.ToString("yyyy-MM-dd HH\\:mm\\:ss", CultureInfo.InvariantCulture);
}
/// <summary>
/// Gets or sets the movie title.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets the year.
/// </summary>
public int? Year { get; set; }
/// <inheritdoc />
public override SimklIds Ids { get; set; }
/// <summary>
/// Gets watched at.
/// </summary>
public string WatchedAt { get; }
}
}
@@ -0,0 +1,49 @@
using System.Collections.Generic;
namespace Jellyfin.Plugin.Simkl.API.Objects
{
/// <summary>
/// Simkl movie ids.
/// </summary>
public class SimklMovieIds : SimklIds
{
/// <summary>
/// Initializes a new instance of the <see cref="SimklMovieIds"/> class.
/// </summary>
/// <param name="providerMovieIds">the provider movie ids.</param>
public SimklMovieIds(Dictionary<string, string> providerMovieIds)
: base(providerMovieIds)
{
}
/// <summary>
/// Gets or sets the tvdb id.
/// </summary>
public int? Tvdb { get; set; }
/// <summary>
/// Gets or sets the mal id.
/// </summary>
public int? Mal { get; set; }
/// <summary>
/// Gets or sets the anidb id.
/// </summary>
public int? Anidb { get; set; }
/// <summary>
/// Gets or sets the hulu id.
/// </summary>
public int? Hulu { get; set; }
/// <summary>
/// Gets or sets the crunchyroll id.
/// </summary>
public int? Crunchyroll { get; set; }
/// <summary>
/// Gets or sets the movie db id.
/// </summary>
public string Moviedb { get; set; }
}
}
@@ -0,0 +1,55 @@
using MediaBrowser.Model.Dto;
namespace Jellyfin.Plugin.Simkl.API.Objects
{
/// <summary>
/// Simkl show.
/// </summary>
public class SimklShow : SimklMediaObject
{
/// <summary>
/// Initializes a new instance of the <see cref="SimklShow"/> class.
/// </summary>
/// <param name="mediaInfo">The media info.</param>
public SimklShow(BaseItemDto mediaInfo)
{
Title = mediaInfo.SeriesName;
Ids = new SimklShowIds(mediaInfo.ProviderIds);
Year = mediaInfo.ProductionYear;
Seasons = new Season[]
{
new Season
{
Number = mediaInfo.ParentIndexNumber,
Episodes = new[]
{
new ShowEpisode
{
Number = mediaInfo.IndexNumber
}
}
}
};
}
/// <summary>
/// Gets or sets title.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets year.
/// </summary>
public int? Year { get; set; }
/// <summary>
/// Gets or sets seasons.
/// </summary>
public Season[] Seasons { get; set; }
/// <summary>
/// Gets or sets ids.
/// </summary>
public override SimklIds Ids { get; set; }
}
}
@@ -0,0 +1,49 @@
using System.Collections.Generic;
namespace Jellyfin.Plugin.Simkl.API.Objects
{
/// <summary>
/// Simkl show ids.
/// </summary>
public class SimklShowIds : SimklIds
{
/// <summary>
/// Initializes a new instance of the <see cref="SimklShowIds"/> class.
/// </summary>
/// <param name="providerMovieIds">The provider movie ids.</param>
public SimklShowIds(Dictionary<string, string> providerMovieIds)
: base(providerMovieIds)
{
}
/// <summary>
/// Gets or sets tvdb.
/// </summary>
public int? Tvdb { get; set; }
/// <summary>
/// Gets or sets mal.
/// </summary>
public int? Mal { get; set; }
/// <summary>
/// Gets or sets anidb.
/// </summary>
public int? Anidb { get; set; }
/// <summary>
/// Gets or sets hulu.
/// </summary>
public int? Hulu { get; set; }
/// <summary>
/// Gets or sets crunchyroll.
/// </summary>
public int? Crunchyroll { get; set; }
/// <summary>
/// Gets or sets zap2it.
/// </summary>
public string Zap2It { get; set; }
}
}
+47
View File
@@ -0,0 +1,47 @@
using System;
using System.Text.Json.Serialization;
namespace Jellyfin.Plugin.Simkl.API.Objects
{
/// <summary>
/// User.
/// </summary>
public class User
{
/// <summary>
/// Gets or sets name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets joined at.
/// </summary>
[JsonPropertyName("joined_at")]
public DateTime JoinedAt { get; set; }
/// <summary>
/// Gets or sets gender.
/// </summary>
public string Gender { get; set; }
/// <summary>
/// Gets or sets avatar.
/// </summary>
public string Avatar { get; set; }
/// <summary>
/// Gets or sets bio.
/// </summary>
public string Bio { get; set; }
/// <summary>
/// Gets or sets loc.
/// </summary>
public string Loc { get; set; }
/// <summary>
/// Gets or sets age.
/// </summary>
public string Age { get; set; }
}
}
@@ -0,0 +1,23 @@
namespace Jellyfin.Plugin.Simkl.API.Objects
{
/// <summary>
/// User settings.
/// </summary>
public class UserSettings
{
/// <summary>
/// Gets or sets user.
/// </summary>
public User User { get; set; }
/// <summary>
/// Gets or sets account.
/// </summary>
public Account Account { get; set; }
/// <summary>
/// Gets or sets error.
/// </summary>
public string Error { get; set; }
}
}
@@ -0,0 +1,44 @@
using System.Text.Json.Serialization;
namespace Jellyfin.Plugin.Simkl.API.Responses
{
/// <summary>
/// Code response.
/// </summary>
public class CodeResponse
{
/// <summary>
/// Gets or sets result.
/// </summary>
public string Result { get; set; }
/// <summary>
/// Gets or sets device code.
/// </summary>
[JsonPropertyName("device_code")]
public string DeviceCode { get; set; }
/// <summary>
/// Gets or sets user code.
/// </summary>
[JsonPropertyName("user_code")]
public string UserCode { get; set; }
/// <summary>
/// Gets or sets verification url.
/// </summary>
[JsonPropertyName("verification_url")]
public string VerificationUrl { get; set; }
/// <summary>
/// Gets or sets expires in.
/// </summary>
[JsonPropertyName("expires_in")]
public int ExpiresIn { get; set; }
/// <summary>
/// Gets or sets interval.
/// </summary>
public int Interval { get; set; }
}
}
@@ -0,0 +1,26 @@
using System.Text.Json.Serialization;
namespace Jellyfin.Plugin.Simkl.API.Responses
{
/// <summary>
/// Code status response.
/// </summary>
public class CodeStatusResponse
{
/// <summary>
/// Gets or sets result.
/// </summary>
public string Result { get; set; }
/// <summary>
/// Gets or sets message.
/// </summary>
public string Message { get; set; }
/// <summary>
/// Gets or sets access token.
/// </summary>
[JsonPropertyName("access_token")]
public string AccessToken { get; set; }
}
}
@@ -0,0 +1,30 @@
using Jellyfin.Plugin.Simkl.API.Objects;
namespace Jellyfin.Plugin.Simkl.API.Responses
{
/// <summary>
/// Search file response.
/// </summary>
public class SearchFileResponse
{
/// <summary>
/// Gets or sets type.
/// </summary>
public string Type { get; set; }
/// <summary>
/// Gets or sets episode.
/// </summary>
public SimklEpisode Episode { get; set; }
/// <summary>
/// Gets or sets movie.
/// </summary>
public SimklMovie Movie { get; set; }
/// <summary>
/// Gets or sets show.
/// </summary>
public SimklShow Show { get; set; }
}
}
@@ -0,0 +1,25 @@
using Jellyfin.Plugin.Simkl.API.Objects;
namespace Jellyfin.Plugin.Simkl.API.Responses
{
/// <summary>
/// sync history not found.
/// </summary>
public class SyncHistoryNotFound
{
/// <summary>
/// Gets or sets movies.
/// </summary>
public SimklMovie[] Movies { get; set; }
/// <summary>
/// Gets or sets shows.
/// </summary>
public SimklShow[] Shows { get; set; }
/// <summary>
/// Gets or sets episodes.
/// </summary>
public SimklEpisode[] Episodes { get; set; }
}
}
@@ -0,0 +1,21 @@
using System.Text.Json.Serialization;
namespace Jellyfin.Plugin.Simkl.API.Responses
{
/// <summary>
/// Sync history response.
/// </summary>
public class SyncHistoryResponse
{
/// <summary>
/// Gets or sets added.
/// </summary>
public SyncHistoryResponseCount Added { get; set; }
/// <summary>
/// Gets or sets not found.
/// </summary>
[JsonPropertyName("not_found")]
public SyncHistoryNotFound NotFound { get; set; }
}
}
@@ -0,0 +1,23 @@
namespace Jellyfin.Plugin.Simkl.API.Responses
{
/// <summary>
/// Sync history response count.
/// </summary>
public class SyncHistoryResponseCount
{
/// <summary>
/// Gets or sets movies.
/// </summary>
public int Movies { get; set; }
/// <summary>
/// Gets or sets shows.
/// </summary>
public int Shows { get; set; }
/// <summary>
/// Gets or sets episodes.
/// </summary>
public int Episodes { get; set; }
}
}
@@ -0,0 +1,74 @@
using Jellyfin.Plugin.Simkl.API.Objects;
using Jellyfin.Plugin.Simkl.API.Responses;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Services;
using Microsoft.Extensions.Logging;
#pragma warning disable CA1801
namespace Jellyfin.Plugin.Simkl.API
{
/// <summary>
/// Server endpoints.
/// </summary>
public class ServerEndpoint : IService, IHasResultFactory
{
private readonly SimklApi _api;
private readonly ILogger _logger;
private readonly IJsonSerializer _json;
/// <summary>
/// Initializes a new instance of the <see cref="ServerEndpoint"/> class.
/// </summary>
/// <param name="api">The simkl api.</param>
/// <param name="logger">Instance of the <see cref="ILogger{ServerEndpoint}"/> interface.</param>
/// <param name="json">Instance of the <see cref="IJsonSerializer"/> interface.</param>
public ServerEndpoint(SimklApi api, ILogger logger, IJsonSerializer json)
{
_api = api;
_logger = logger;
_json = json;
}
/// <summary>
/// Gets or sets result factory.
/// </summary>
public IHttpResultFactory ResultFactory { get; set; }
/// <summary>
/// Gets or sets request.
/// </summary>
public IRequest Request { get; set; }
/// <summary>
/// Get pin request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>The code response.</returns>
public CodeResponse Get(GetPin request)
{
return _api.GetCode().GetAwaiter().GetResult();
}
/// <summary>
/// Get pin status.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Code status response.</returns>
public CodeStatusResponse Get(GetPinStatus request)
{
return _api.GetCodeStatus(request.UserCode).GetAwaiter().GetResult();
}
/// <summary>
/// Get user settings.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>User settings.</returns>
public UserSettings Get(GetUserSettings request)
{
_logger.LogDebug(_json.SerializeToString(request));
return _api.GetUserSettings(SimklPlugin.Instance.Configuration.GetByGuid(request.UserId).UserToken).Result;
}
}
}
+280
View File
@@ -0,0 +1,280 @@
using System.IO;
using System.Threading.Tasks;
using Jellyfin.Plugin.Simkl.API.Exceptions;
using Jellyfin.Plugin.Simkl.API.Objects;
using Jellyfin.Plugin.Simkl.API.Responses;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging; // using System.Threading;
namespace Jellyfin.Plugin.Simkl.API
{
/// <summary>
/// Simkl Api.
/// </summary>
public class SimklApi
{
/* INTERFACES */
private readonly IJsonSerializer _json;
private readonly ILogger<SimklApi> _logger;
private readonly IHttpClient _httpClient;
/* BASIC API THINGS */
/// <summary>
/// Base url.
/// </summary>
public const string Baseurl = @"https://api.simkl.com";
// public const string BASE_URL = @"http://private-9c39b-simkl.apiary-proxy.com";
/// <summary>
/// Redirect uri.
/// </summary>
public const string RedirectUri = @"https://simkl.com/apps/emby/connected/";
/// <summary>
/// Api key.
/// </summary>
public const string Apikey = @"27dd5d6adc24aa1ad9f95ef913244cbaf6df5696036af577ed41670473dc97d0";
/// <summary>
/// Secret.
/// </summary>
public const string Secret = @"d7b9feb9d48bbaa69dbabaca21ba4671acaa89198637e9e136a4d69ec97ab68b";
/// <summary>
/// Initializes a new instance of the <see cref="SimklApi"/> class.
/// </summary>
/// <param name="json">Instance of the <see cref="IJsonSerializer"/> interface.</param>
/// <param name="logger">Instance of the <see cref="ILogger{SimklApi}"/> interface.</param>
/// <param name="httpClient">Instance of the <see cref="IHttpClient"/> interface.</param>
public SimklApi(IJsonSerializer json, ILogger<SimklApi> logger, IHttpClient httpClient)
{
_json = json;
_logger = logger;
_httpClient = httpClient;
}
/// <summary>
/// Get code.
/// </summary>
/// <returns>Code response.</returns>
public async Task<CodeResponse> GetCode()
{
var uri = $"/oauth/pin?client_id={Apikey}&redirect={RedirectUri}";
return _json.DeserializeFromStream<CodeResponse>(await Get(uri).ConfigureAwait(false));
}
/// <summary>
/// Get code status.
/// </summary>
/// <param name="userCode">User code.</param>
/// <returns>Code status.</returns>
public async Task<CodeStatusResponse> GetCodeStatus(string userCode)
{
var uri = $"/oauth/pin/{userCode}?client_id={Apikey}";
return _json.DeserializeFromStream<CodeStatusResponse>(await Get(uri).ConfigureAwait(false));
}
/// <summary>
/// Get user settings.
/// </summary>
/// <param name="userToken">User token.</param>
/// <returns>User settings.</returns>
public async Task<UserSettings> GetUserSettings(string userToken)
{
try
{
return _json.DeserializeFromStream<UserSettings>(await Post("/users/settings/", userToken).ConfigureAwait(false));
}
catch (MediaBrowser.Model.Net.HttpException e) when (e.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
// Wontfix: Custom status codes
// "You don't get to pick your response code" - Luke (System Architect of Emby)
// https://emby.media/community/index.php?/topic/61889-wiki-issue-resultfactorythrowerror/
return new UserSettings { Error = "user_token_failed" };
}
}
/// <summary>
/// Mark as watched.
/// </summary>
/// <param name="item">Item.</param>
/// <param name="userToken">User token.</param>
/// <returns>Status.</returns>
public async Task<(bool success, BaseItemDto item)> MarkAsWatched(BaseItemDto item, string userToken)
{
var history = CreateHistoryFromItem(item);
var r = await SyncHistoryAsync(history, userToken).ConfigureAwait(false);
_logger.LogDebug("Response: " + _json.SerializeToString(r));
if (history.Movies.Count == r.Added.Movies && history.Shows.Count == r.Added.Shows)
{
return (true, item);
}
// If we are here, is because the item has not been found
// let's try scrobbling from full path
try
{
(history, item) = await GetHistoryFromFileName(item).ConfigureAwait(false);
}
catch (InvalidDataException)
{
// Let's try again but this time using only the FILE name
_logger.LogDebug("Couldn't scrobble using full path, trying using only filename");
(history, item) = await GetHistoryFromFileName(item, false).ConfigureAwait(false);
}
r = await SyncHistoryAsync(history, userToken).ConfigureAwait(false);
_logger.LogDebug("Response: " + _json.SerializeToString(r));
return (history.Movies.Count == r.Added.Movies && history.Shows.Count == r.Added.Shows, item);
}
/// <summary>
/// Get from file.
/// </summary>
/// <param name="filename">Filename.</param>
/// <returns>Search file response.</returns>
private async Task<SearchFileResponse> GetFromFile(string filename)
{
var f = new SimklFile { File = filename };
_logger.LogInformation("Posting: " + _json.SerializeToString(f));
using var r = new StreamReader(await Post("/search/file/", null, f).ConfigureAwait(false));
var t = r.ReadToEnd();
_logger.LogDebug("Response: " + t);
return _json.DeserializeFromString<SearchFileResponse>(t);
}
/// <summary>
/// Get history from file name.
/// </summary>
/// <param name="item">Item.</param>
/// <param name="fullpath">Full path.</param>
/// <returns>Srobble history.</returns>
private async Task<(SimklHistory history, BaseItemDto item)> GetHistoryFromFileName(BaseItemDto item, bool fullpath = true)
{
var fname = fullpath ? item.Path : Path.GetFileName(item.Path);
var mo = await GetFromFile(fname).ConfigureAwait(false);
var history = new SimklHistory();
if (item.IsMovie == true || item.Type == "Movie")
{
if (mo.Type != "movie")
{
throw new InvalidDataException("type != movie (" + mo.Type + ")");
}
item.Name = mo.Movie.Title;
item.ProductionYear = mo.Movie.Year;
history.Movies.Add(mo.Movie);
}
else if (item.IsSeries == true || item.Type == "Episode")
{
if (mo.Type != "episode")
{
throw new InvalidDataException("type != episode (" + mo.Type + ")");
}
item.Name = mo.Episode.Title;
item.SeriesName = mo.Show.Title;
item.IndexNumber = mo.Episode.Episode;
item.ParentIndexNumber = mo.Episode.Season;
item.ProductionYear = mo.Show.Year;
history.Episodes.Add(mo.Episode);
}
return (history, item);
}
private static HttpRequestOptions GetOptions(string userToken = null)
{
var options = new HttpRequestOptions
{
RequestContentType = "application/json",
LogErrorResponseBody = true,
EnableDefaultUserAgent = true
};
options.RequestHeaders.Add("simkl-api-key", Apikey);
// options.RequestHeaders.Add("Content-Type", "application/json");
if (!string.IsNullOrEmpty(userToken))
{
options.RequestHeaders.Add("Authorization", "Bearer " + userToken);
}
return options;
}
private static SimklHistory CreateHistoryFromItem(BaseItemDto item)
{
var history = new SimklHistory();
if (item.IsMovie == true || item.Type == "Movie")
{
history.Movies.Add(new SimklMovie(item));
}
else if (item.IsSeries == true || item.Type == "Episode")
{
// TODO: TV Shows scrobbling (WIP)
history.Shows.Add(new SimklShow(item));
}
return history;
}
/// <summary>
/// Implements /sync/history method from simkl.
/// </summary>
/// <param name="history">History object.</param>
/// <param name="userToken">User token.</param>
/// <returns>The sync history response.</returns>
private async Task<SyncHistoryResponse> SyncHistoryAsync(SimklHistory history, string userToken)
{
try
{
_logger.LogInformation("Syncing History: " + _json.SerializeToString(history));
return _json.DeserializeFromStream<SyncHistoryResponse>(await Post("/sync/history", userToken, history).ConfigureAwait(false));
}
catch (MediaBrowser.Model.Net.HttpException e) when (e.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
_logger.LogError("Invalid user token " + userToken + ", deleting");
SimklPlugin.Instance.Configuration.DeleteUserToken(userToken);
throw new InvalidTokenException("Invalid user token " + userToken);
}
}
/// <summary>
/// API's private get method, given RELATIVE url and headers.
/// </summary>
/// <param name="url">Relative url.</param>
/// <param name="userToken">Authentication token.</param>
/// <returns>HTTP(s) Stream to be used.</returns>
private async Task<Stream> Get(string url, string userToken = null)
{
// Todo: If string is not null neither empty
var options = GetOptions(userToken);
options.Url = Baseurl + url;
return await _httpClient.Get(options).ConfigureAwait(false);
}
/// <summary>
/// API's private post method.
/// </summary>
/// <param name="url">Relative post url.</param>
/// <param name="userToken">Authentication token.</param>
/// <param name="data">Object to serialize.</param>
private async Task<Stream> Post(string url, string userToken = null, object data = null)
{
var options = GetOptions(userToken);
options.Url = Baseurl + url;
if (data != null)
{
options.RequestContent = _json.SerializeToString(data);
}
return (await _httpClient.Post(options).ConfigureAwait(false)).Content;
}
}
}