diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..b84e563 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,194 @@ +# With more recent updates Visual Studio 2017 supports EditorConfig files out of the box +# Visual Studio Code needs an extension: https://github.com/editorconfig/editorconfig-vscode +# For emacs, vim, np++ and other editors, see here: https://github.com/editorconfig +############################### +# Core EditorConfig Options # +############################### +root = true +# All files +[*] +indent_style = space +indent_size = 4 +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +end_of_line = lf +max_line_length = off + +# YAML indentation +[*.{yml,yaml}] +indent_size = 2 + +# XML indentation +[*.{csproj,xml}] +indent_size = 2 + +############################### +# .NET Coding Conventions # +############################### +[*.{cs,vb}] +# Organize usings +dotnet_sort_system_directives_first = true +# this. preferences +dotnet_style_qualification_for_field = false:silent +dotnet_style_qualification_for_property = false:silent +dotnet_style_qualification_for_method = false:silent +dotnet_style_qualification_for_event = false:silent +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true:silent +dotnet_style_predefined_type_for_member_access = true:silent +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent +dotnet_style_readonly_field = true:suggestion +# Expression-level preferences +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:silent +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent + +############################### +# Naming Conventions # +############################### +# Style Definitions (From Roslyn) + +# Non-private static fields are PascalCase +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.symbols = non_private_static_fields +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style + +dotnet_naming_symbols.non_private_static_fields.applicable_kinds = field +dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected +dotnet_naming_symbols.non_private_static_fields.required_modifiers = static + +dotnet_naming_style.non_private_static_field_style.capitalization = pascal_case + +# Constants are PascalCase +dotnet_naming_rule.constants_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.constants_should_be_pascal_case.symbols = constants +dotnet_naming_rule.constants_should_be_pascal_case.style = constant_style + +dotnet_naming_symbols.constants.applicable_kinds = field, local +dotnet_naming_symbols.constants.required_modifiers = const + +dotnet_naming_style.constant_style.capitalization = pascal_case + +# Static fields are camelCase and start with s_ +dotnet_naming_rule.static_fields_should_be_camel_case.severity = suggestion +dotnet_naming_rule.static_fields_should_be_camel_case.symbols = static_fields +dotnet_naming_rule.static_fields_should_be_camel_case.style = static_field_style + +dotnet_naming_symbols.static_fields.applicable_kinds = field +dotnet_naming_symbols.static_fields.required_modifiers = static + +dotnet_naming_style.static_field_style.capitalization = camel_case +dotnet_naming_style.static_field_style.required_prefix = _ + +# Instance fields are camelCase and start with _ +dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion +dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields +dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style + +dotnet_naming_symbols.instance_fields.applicable_kinds = field + +dotnet_naming_style.instance_field_style.capitalization = camel_case +dotnet_naming_style.instance_field_style.required_prefix = _ + +# Locals and parameters are camelCase +dotnet_naming_rule.locals_should_be_camel_case.severity = suggestion +dotnet_naming_rule.locals_should_be_camel_case.symbols = locals_and_parameters +dotnet_naming_rule.locals_should_be_camel_case.style = camel_case_style + +dotnet_naming_symbols.locals_and_parameters.applicable_kinds = parameter, local + +dotnet_naming_style.camel_case_style.capitalization = camel_case + +# Local functions are PascalCase +dotnet_naming_rule.local_functions_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions +dotnet_naming_rule.local_functions_should_be_pascal_case.style = local_function_style + +dotnet_naming_symbols.local_functions.applicable_kinds = local_function + +dotnet_naming_style.local_function_style.capitalization = pascal_case + +# By default, name items with PascalCase +dotnet_naming_rule.members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.members_should_be_pascal_case.symbols = all_members +dotnet_naming_rule.members_should_be_pascal_case.style = pascal_case_style + +dotnet_naming_symbols.all_members.applicable_kinds = * + +dotnet_naming_style.pascal_case_style.capitalization = pascal_case + +############################### +# C# Coding Conventions # +############################### +[*.cs] +# var preferences +csharp_style_var_for_built_in_types = true:silent +csharp_style_var_when_type_is_apparent = true:silent +csharp_style_var_elsewhere = true:silent +# Expression-bodied members +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +# Pattern matching preferences +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +# Null-checking preferences +csharp_style_throw_expression = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion +# Modifier preferences +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion +# Expression-level preferences +csharp_prefer_braces = true:silent +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_pattern_local_over_anonymous_function = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion + +############################### +# C# Formatting Rules # +############################### +# New line preferences +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true +# Indentation preferences +csharp_indent_case_contents = true +csharp_indent_switch_labels = true +csharp_indent_labels = flush_left +# Space preferences +csharp_space_after_cast = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_around_binary_operators = before_and_after +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +# Wrapping preferences +csharp_preserve_single_line_statements = true +csharp_preserve_single_line_blocks = true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fa76d31 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +src/*/bin/* +src/*/obj/* diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..b70caee --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,25 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + "program": "${workspaceFolder}/src/Jellyfin.Plugin.Kinopoisk/bin/Debug/netstandard2.1/Jellyfin.Plugin.Kinopoisk.dll", + "args": [], + "cwd": "${workspaceFolder}", + "console": "internalConsole", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickProcess}" + } + ] +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..cf15b16 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,39 @@ +{ + // See https://go.microsoft.com/fwlink/?LinkId=733558 + // for the documentation about the tasks.json format + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "shell", + "args": [ + "build", + "${workspaceFolder}/src/Jellyfin.Plugin.Kinopoisk/Jellyfin.Plugin.Kinopoisk.csproj" + // Ask dotnet build to generate full paths for file names. + "/property:GenerateFullPaths=true", + // Do not generate summary otherwise it leads to duplicate errors in Problems panel + "/consoleloggerparameters:NoSummary" + ], + "group": "build", + "presentation": { + "reveal": "silent" + }, + "problemMatcher": "$msCompile" + }, + { + "label": "test", + "command": "dotnet", + "type": "shell", + "args": [ + "test", + "${workspaceFolder}/src/Jellyfin.Plugin.Kinopoisk/Jellyfin.Plugin.Kinopoisk.csproj" + ], + "group": "test", + "presentation": { + "reveal": "silent" + }, + "problemMatcher": "$msCompile" + } + ] +} diff --git a/kinopoisk.code-workspace b/kinopoisk.code-workspace new file mode 100644 index 0000000..876a149 --- /dev/null +++ b/kinopoisk.code-workspace @@ -0,0 +1,8 @@ +{ + "folders": [ + { + "path": "." + } + ], + "settings": {} +} \ No newline at end of file diff --git a/src/Jellyfin.Plugin.Kinopoisk.Tests/Jellyfin.Plugin.Kinopoisk.Tests.csproj b/src/Jellyfin.Plugin.Kinopoisk.Tests/Jellyfin.Plugin.Kinopoisk.Tests.csproj new file mode 100644 index 0000000..c2e1ee3 --- /dev/null +++ b/src/Jellyfin.Plugin.Kinopoisk.Tests/Jellyfin.Plugin.Kinopoisk.Tests.csproj @@ -0,0 +1,20 @@ + + + + net5.0 + + false + + + + + + + + + + + + + + diff --git a/src/Jellyfin.Plugin.Kinopoisk.Tests/UtilsTests.cs b/src/Jellyfin.Plugin.Kinopoisk.Tests/UtilsTests.cs new file mode 100644 index 0000000..85b3ecc --- /dev/null +++ b/src/Jellyfin.Plugin.Kinopoisk.Tests/UtilsTests.cs @@ -0,0 +1,16 @@ +using System; +using Xunit; + +namespace Jellyfin.Plugin.Kinopoisk.Tests +{ + public class UtilsTests + { + [Fact] + public void GetFirstYear_ShouldParseYearsSpan() + { + var inp = "2014-2017"; + var res = Utils.GetFirstYear(inp); + Assert.Equal(2014, res); + } + } +} diff --git a/src/Jellyfin.Plugin.Kinopoisk/ApiModel/FilmDetails.cs b/src/Jellyfin.Plugin.Kinopoisk/ApiModel/FilmDetails.cs new file mode 100644 index 0000000..75949cd --- /dev/null +++ b/src/Jellyfin.Plugin.Kinopoisk/ApiModel/FilmDetails.cs @@ -0,0 +1,94 @@ +using System.Collections.Generic; + +namespace Jellyfin.Plugin.Kinopoisk.ApiModel +{ + public class FilmDetails + { + public FilmData Data { get; set; } + + public FilmExtId ExternalId { get; set; } + + public FilmRating Rating { get; set; } + + // "budget": { + // "grossRu": null, + // "grossUsa": null, + // "grossWorld": null, + // "budget": null, + // "marketing": null + // }, + + // "review": { + // "reviewsCount": 0, + // "ratingGoodReview": "", + // "ratingGoodReviewVoteCount": 0 + // }, + + public FilmImages Images { get; set; } + + public class FilmData + { + public int FilmId { get; set; } + public string NameRu { get; set; } + public string NameEn { get; set; } + public string WebUrl { get; set; } + public string PosterUrl { get; set; } + public string Year { get; set; } + public string FilmLength { get; set; } + public string Slogan { get; set; } + public string Description { get; set; } + public string Type { get; set; } // FILM, TV_SHOW + public string RatingMpaa { get; set; } + public string RatingAgeLimits { get; set; } + public string PremiereRu { get; set; } + public string Distributors { get; set; } + public string PremiereWorld { get; set; } + public string PremiereDigital { get; set; } + public string PremiereWorldCountry { get; set; } + public string PremiereDvd { get; set; } + public string PremiereBluRay { get; set; } + public string DistributorRelease { get; set; } + public CountryItem[] Countries { get; set; } + public GenreItem[] Genres { get; set; } + + public class CountryItem + { + public string Country { get; set; } + } + + public class GenreItem + { + public string Genre { get; set; } + } + } + + public class FilmExtId + { + public string ImdbId { get; set; } + } + + public class FilmRating + { + public float Rating { get; set; } + public int RatingVoteCount { get; set; } + public float? RatingImdb { get; set; } + public int RatingImdbVoteCount { get; set; } + public string RatingFilmCritics { get; set; } + public int RatingFilmCriticsVoteCount { get; set; } + } + + public class FilmImages + { + public FilmImageRef[] Posters { get; set; } + public FilmImageRef[] Backdrops { get; set; } + } + + public class FilmImageRef + { + public string Language { get; set; } + public string Url { get; set; } + public int Height { get; set; } + public int Width { get; set; } + } + } +} diff --git a/src/Jellyfin.Plugin.Kinopoisk/ApiModel/SearchResult.cs b/src/Jellyfin.Plugin.Kinopoisk/ApiModel/SearchResult.cs new file mode 100644 index 0000000..c463e47 --- /dev/null +++ b/src/Jellyfin.Plugin.Kinopoisk/ApiModel/SearchResult.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; + +namespace Jellyfin.Plugin.Kinopoisk.ApiModel +{ + public class SearchResult + { + public string Keyword { get; set; } + public int PagesCount { get; set; } + public List Films { get; set; } + + public class Film + { + public int FilmId { get; set; } + public string NameRu { get; set; } + public string NameEn { get; set; } + public string Type { get; set; } + public string Year { get; set; } + public string Description { get; set; } + public string FilmLength { get; set; } + public string Rating { get; set; } + public string RatingVoteCount { get; set; } + public string PosterUrl { get; set; } + } + } +} diff --git a/src/Jellyfin.Plugin.Kinopoisk/ApiModelExtensions.cs b/src/Jellyfin.Plugin.Kinopoisk/ApiModelExtensions.cs new file mode 100644 index 0000000..6076c26 --- /dev/null +++ b/src/Jellyfin.Plugin.Kinopoisk/ApiModelExtensions.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Jellyfin.Plugin.Kinopoisk.ApiModel; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Providers; + +namespace Jellyfin.Plugin.Kinopoisk +{ + public static class ApiModelExtensions + { + public static Series ToSeries(this FilmDetails src) + { + if (src.Data is null) + return null; + + var res = new Series(); + + FillCommonFilmInfo(src, res); + + return res; + } + + public static Movie ToMovie(this FilmDetails src) + { + if (src.Data is null) + return null; + + var res = new Movie(); + + FillCommonFilmInfo(src, res); + + return res; + } + + private static void FillCommonFilmInfo(FilmDetails src, BaseItem dst) + { + dst.SetProviderId(Utils.ProviderId, Convert.ToString(src.Data.FilmId)); + dst.Name = src.Data.NameRu; + if (string.IsNullOrWhiteSpace(dst.Name)) + dst.Name = src.Data.NameEn; + // if (!string.IsNullOrWhiteSpace(film.Data.WebUrl)) + // result.Item.HomePageUrl = film.Data.WebUrl; + dst.ProductionYear = Utils.GetFirstYear(src.Data.Year); + dst.Overview = src.Data.Description; + if (src.Data.Countries != null) + dst.ProductionLocations = src.Data.Countries.Select(c => c.Country).ToArray(); + if (src.Data.Genres != null) + foreach(var genre in src.Data.Genres.Select(c => c.Genre)) + dst.AddGenre(genre); + if (!string.IsNullOrWhiteSpace(src.Data.RatingAgeLimits)) + dst.OfficialRating = $"{src.Data.RatingAgeLimits}+"; + else + dst.OfficialRating = src.Data.RatingMpaa; + + if (src.Rating != null) + { + dst.CommunityRating = src.Rating.Rating > 0 + ? src.Rating.Rating + : src.Rating.RatingImdb; + dst.CriticRating = src.Rating.GetCriticRatingAsTenPointBased(); + } + + if (src.ExternalId != null) + { + if (!string.IsNullOrWhiteSpace(src.ExternalId.ImdbId)) + dst.SetProviderId(MetadataProviders.Imdb, src.ExternalId.ImdbId); + } + } + + public static float? GetCriticRatingAsTenPointBased(this FilmDetails.FilmRating src) + { + if (src is null) + return null; + + if (string.IsNullOrWhiteSpace(src.RatingFilmCritics)) + return null; + + if (float.TryParse(src.RatingFilmCritics, out var res)) + return res; + + var ratingStr = src.RatingFilmCritics.Replace("%", string.Empty); + if (int.TryParse(ratingStr, out var res_pct)) + return res_pct * 0.1f; + + return null; + } + + public static IEnumerable ToRemoteImageInfos(this FilmDetails src) + { + var res = Enumerable.Empty(); + if (src is null) + return res; + + if (src?.Data?.PosterUrl != null) + { + var mainPoster = new RemoteImageInfo(){ + Type = ImageType.Primary, + Url = src.Data.PosterUrl, + Language = Utils.ProviderMetadataLanguage, + ProviderName = Utils.ProviderName + }; + res = res.Concat(Enumerable.Repeat(mainPoster, 1)); + } + + if (src.Images != null) + { + if (src.Images.Posters != null) + res = res.Concat(src.Images.Posters.Select(i => new RemoteImageInfo(){ + Type = ImageType.Primary, + Url = i.Url, + Language = i.Language, + Height = i.Height, + Width = i.Width, + ProviderName = Utils.ProviderName + })); + if (src.Images.Backdrops != null) + res = res.Concat(src.Images.Backdrops.Select(i => new RemoteImageInfo(){ + Type = ImageType.Backdrop, + Url = i.Url, + Language = i.Language, + Height = i.Height, + Width = i.Width, + ProviderName = Utils.ProviderName + })); + } + + return res; + } + } +} diff --git a/src/Jellyfin.Plugin.Kinopoisk/Configuration/PluginConfiguration.cs b/src/Jellyfin.Plugin.Kinopoisk/Configuration/PluginConfiguration.cs new file mode 100644 index 0000000..c9fde7c --- /dev/null +++ b/src/Jellyfin.Plugin.Kinopoisk/Configuration/PluginConfiguration.cs @@ -0,0 +1,10 @@ +using MediaBrowser.Model.Plugins; + +namespace Jellyfin.Plugin.Kinopoisk.Configuration +{ + public class PluginConfiguration : BasePluginConfiguration + { + // https://kinopoiskapiunofficial.tech/ + public string ApiToken { get; set; } = string.Empty; + } +} diff --git a/src/Jellyfin.Plugin.Kinopoisk/Configuration/configPage.html b/src/Jellyfin.Plugin.Kinopoisk/Configuration/configPage.html new file mode 100644 index 0000000..d819e3e --- /dev/null +++ b/src/Jellyfin.Plugin.Kinopoisk/Configuration/configPage.html @@ -0,0 +1,53 @@ + + + + + Template + + +
+
+
+
+
+ + +
Personal api token, you can get your own on + https://kinopoiskapiunofficial.tech +
+
+
+ +
+
+
+
+ +
+ + diff --git a/src/Jellyfin.Plugin.Kinopoisk/Jellyfin.Plugin.Kinopoisk.csproj b/src/Jellyfin.Plugin.Kinopoisk/Jellyfin.Plugin.Kinopoisk.csproj new file mode 100644 index 0000000..8e03de2 --- /dev/null +++ b/src/Jellyfin.Plugin.Kinopoisk/Jellyfin.Plugin.Kinopoisk.csproj @@ -0,0 +1,17 @@ + + + + netstandard2.1 + + + + + + + + + + + + + diff --git a/src/Jellyfin.Plugin.Kinopoisk/KinopoiskApiProxy.cs b/src/Jellyfin.Plugin.Kinopoisk/KinopoiskApiProxy.cs new file mode 100644 index 0000000..dda6fb0 --- /dev/null +++ b/src/Jellyfin.Plugin.Kinopoisk/KinopoiskApiProxy.cs @@ -0,0 +1,104 @@ +using System; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using System.Web; +using Jellyfin.Plugin.Kinopoisk.ApiModel; +using MediaBrowser.Common.Net; +using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.Kinopoisk +{ + public class KinopoiskApiProxy + { + private readonly ILogger _logger; + private readonly IHttpClient _httpClient; + private readonly IJsonSerializer _jsonSerializer; + private readonly string _apiToken; + + public KinopoiskApiProxy(ILogger logger, IHttpClient httpClient, IJsonSerializer jsonSerializer) + { + this._logger = logger; + this._httpClient = httpClient; + this._jsonSerializer = jsonSerializer; + this._apiToken = Plugin.Instance.Configuration.ApiToken; + } + + public async Task SearchByKeyword(string keyword, int page = 1, CancellationToken? cancellationToken = null) + { + if (!cancellationToken.HasValue) + cancellationToken = CancellationToken.None; + var uriBuilder = new UriBuilder("https://kinopoiskapiunofficial.tech/api/v2.1/films/search-by-keyword"); + + var @params = HttpUtility.ParseQueryString(string.Empty); + @params["keyword"] = keyword; + @params["page"] = Convert.ToString(page); + uriBuilder.Query = @params.ToString(); + + var requestOptions = new HttpRequestOptions + { + Url = uriBuilder.Uri.AbsoluteUri, + CancellationToken = cancellationToken.Value, + BufferContent = true, + EnableDefaultUserAgent = true, + AcceptHeader = "application/json" + }; + requestOptions.RequestHeaders.Add("X-API-KEY", _apiToken); + using(var response = await _httpClient.SendAsync(requestOptions, HttpMethod.Get).ConfigureAwait(false)) + // todo: status code! + using(var jsonStream = response.Content) + { + return await _jsonSerializer.DeserializeFromStreamAsync(jsonStream).ConfigureAwait(false); + } + } + + public async Task GetSingleFilm(int filmId, CancellationToken? cancellationToken = null) + { + if (!cancellationToken.HasValue) + cancellationToken = CancellationToken.None; + + var uri = new Uri($"https://kinopoiskapiunofficial.tech/api/v2.1/films/{filmId}?append_to_response=EXTERNAL_ID&append_to_response=RATING"); + + var requestOptions = new HttpRequestOptions + { + Url = uri.AbsoluteUri, + CancellationToken = cancellationToken.Value, + BufferContent = true, + EnableDefaultUserAgent = true, + AcceptHeader = "application/json" + }; + requestOptions.RequestHeaders.Add("X-API-KEY", _apiToken); + using(var response = await _httpClient.SendAsync(requestOptions, HttpMethod.Get).ConfigureAwait(false)) + // todo: status code! + using(var jsonStream = response.Content) + { + return await _jsonSerializer.DeserializeFromStreamAsync(jsonStream).ConfigureAwait(false); + } + } + + public async Task GetSingleFilmImages(int filmId, CancellationToken? cancellationToken = null) + { + if (!cancellationToken.HasValue) + cancellationToken = CancellationToken.None; + + var uri = new Uri($"https://kinopoiskapiunofficial.tech/api/v2.1/films/{filmId}?append_to_response=POSTERS"); + + var requestOptions = new HttpRequestOptions + { + Url = uri.AbsoluteUri, + CancellationToken = cancellationToken.Value, + BufferContent = true, + EnableDefaultUserAgent = true, + AcceptHeader = "application/json" + }; + requestOptions.RequestHeaders.Add("X-API-KEY", _apiToken); + using(var response = await _httpClient.SendAsync(requestOptions, HttpMethod.Get).ConfigureAwait(false)) + // todo: status code! + using(var jsonStream = response.Content) + { + return await _jsonSerializer.DeserializeFromStreamAsync(jsonStream).ConfigureAwait(false); + } + } + } +} diff --git a/src/Jellyfin.Plugin.Kinopoisk/KinopoiskExternalId.cs b/src/Jellyfin.Plugin.Kinopoisk/KinopoiskExternalId.cs new file mode 100644 index 0000000..47e6d32 --- /dev/null +++ b/src/Jellyfin.Plugin.Kinopoisk/KinopoiskExternalId.cs @@ -0,0 +1,23 @@ +using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Entities; + +namespace Jellyfin.Plugin.Kinopoisk +{ + public class KinopoiskExternalId : IExternalId + { + public string ProviderName => Utils.ProviderName; + + public string Name => Utils.ProviderName; + + public string Key => Utils.ProviderId; + + public string UrlFormatString => "https://www.kinopoisk.ru/film/{0}"; + + public bool Supports(IHasProviderIds item) + { + return item is Movie || item is Series; + } + } +} diff --git a/src/Jellyfin.Plugin.Kinopoisk/KinopoiskImageProvider.cs b/src/Jellyfin.Plugin.Kinopoisk/KinopoiskImageProvider.cs new file mode 100644 index 0000000..81d9a58 --- /dev/null +++ b/src/Jellyfin.Plugin.Kinopoisk/KinopoiskImageProvider.cs @@ -0,0 +1,80 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Providers; +using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.Kinopoisk +{ + public class KinopoiskImageProvider : IRemoteImageProvider + { + private readonly ILogger _logger; + private readonly IHttpClient _httpClient; + private readonly IJsonSerializer _jsonSerializer; + private readonly KinopoiskApiProxy _apiProxy; + + public string Name => Utils.ProviderName; + + public KinopoiskImageProvider(ILogger logger, + IHttpClient httpClient, + IJsonSerializer jsonSerializer) + { + if (logger is null) + { + throw new System.ArgumentNullException(nameof(logger)); + } + + if (httpClient is null) + { + throw new System.ArgumentNullException(nameof(httpClient)); + } + + if (jsonSerializer is null) + { + throw new System.ArgumentNullException(nameof(jsonSerializer)); + } + + this._logger = logger; + this._httpClient = httpClient; + this._jsonSerializer = jsonSerializer; + this._apiProxy = new KinopoiskApiProxy(logger, httpClient, jsonSerializer); + } + + public bool Supports(BaseItem item) + => item is Movie || item is Series; + + public IEnumerable GetSupportedImages(BaseItem item) + => new ImageType[] + { + ImageType.Primary, + ImageType.Backdrop + }; + + public Task GetImageResponse(string url, CancellationToken cancellationToken) + { + return _httpClient.GetResponse(new HttpRequestOptions + { + CancellationToken = cancellationToken, + Url = url + }); + } + + public async Task> GetImages(BaseItem item, CancellationToken cancellationToken) + { + if (!Utils.TryGetKinopoiskId(item, _logger, out var kinopoiskId)) + return Enumerable.Empty(); + + var film = await _apiProxy.GetSingleFilmImages(kinopoiskId, cancellationToken); + + return film.ToRemoteImageInfos(); + } + } +} diff --git a/src/Jellyfin.Plugin.Kinopoisk/KinopoiskMovieProvider.cs b/src/Jellyfin.Plugin.Kinopoisk/KinopoiskMovieProvider.cs new file mode 100644 index 0000000..acde0aa --- /dev/null +++ b/src/Jellyfin.Plugin.Kinopoisk/KinopoiskMovieProvider.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Providers; +using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.Kinopoisk +{ + public class KinopoiskMovieProvider : IRemoteMetadataProvider + { + private readonly ILogger _logger; + private readonly IHttpClient _httpClient; + private readonly IJsonSerializer _jsonSerializer; + private readonly KinopoiskApiProxy _apiProxy; + + public string Name => Utils.ProviderName; + + public KinopoiskMovieProvider(ILogger logger, + IHttpClient httpClient, + IJsonSerializer jsonSerializer) + { + if (logger is null) + { + throw new System.ArgumentNullException(nameof(logger)); + } + + if (httpClient is null) + { + throw new System.ArgumentNullException(nameof(httpClient)); + } + + if (jsonSerializer is null) + { + throw new System.ArgumentNullException(nameof(jsonSerializer)); + } + + this._logger = logger; + this._httpClient = httpClient; + this._jsonSerializer = jsonSerializer; + this._apiProxy = new KinopoiskApiProxy(logger, httpClient, jsonSerializer); + } + + public Task GetImageResponse(string url, CancellationToken cancellationToken) + { + return _httpClient.GetResponse(new HttpRequestOptions + { + CancellationToken = cancellationToken, + Url = url + }); + } + + public async Task> GetMetadata(MovieInfo info, CancellationToken cancellationToken) + { + var result = new MetadataResult() + { + QueriedById = true, + Provider = Utils.ProviderName, + ResultLanguage = Utils.ProviderMetadataLanguage + }; + + if (!Utils.TryGetKinopoiskId(info, _logger, out var kinopoiskId)) + return result; + + var film = await _apiProxy.GetSingleFilm(kinopoiskId, cancellationToken); + + result.Item = film.ToMovie(); + if (result.Item != null) + result.HasMetadata = true; + + return result; + } + + public async Task> GetSearchResults(MovieInfo searchInfo, CancellationToken cancellationToken) + { + if (Utils.TryGetKinopoiskId(searchInfo, _logger, out var kinopoiskId)) + { + var film = await _apiProxy.GetSingleFilm(kinopoiskId, cancellationToken); + var singleResult = new RemoteSearchResult() { + Name = film.Data.NameRu ?? film.Data.NameEn, + ImageUrl = film.Data.PosterUrl, + ProductionYear = Utils.GetFirstYear(film.Data.Year), + Overview = film.Data.Description, + SearchProviderName = Utils.ProviderName + }; + singleResult.SetProviderId(Utils.ProviderId, Convert.ToString(film.Data.FilmId)); + return Enumerable.Repeat(singleResult, 1); + } + else + { + var searchResults = await _apiProxy.SearchByKeyword(searchInfo.Name, cancellationToken: cancellationToken); + return searchResults.Films.Select(f => { + var res = new RemoteSearchResult() { + Name = f.NameRu ?? f.NameEn, + ImageUrl = f.PosterUrl, + ProductionYear = Utils.GetFirstYear(f.Year), + Overview = f.Description, + SearchProviderName = Utils.ProviderName + }; + res.SetProviderId(Utils.ProviderId, Convert.ToString(f.FilmId)); + return res; + }); + } + } + } +} diff --git a/src/Jellyfin.Plugin.Kinopoisk/KinopoiskSeriesProvider.cs b/src/Jellyfin.Plugin.Kinopoisk/KinopoiskSeriesProvider.cs new file mode 100644 index 0000000..821de1d --- /dev/null +++ b/src/Jellyfin.Plugin.Kinopoisk/KinopoiskSeriesProvider.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Providers; +using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.Kinopoisk +{ + public class KinopoiskSeriesProvider : IRemoteMetadataProvider + { + private readonly ILogger _logger; + private readonly IHttpClient _httpClient; + private readonly IJsonSerializer _jsonSerializer; + private readonly KinopoiskApiProxy _apiProxy; + + public string Name => Utils.ProviderName; + + public KinopoiskSeriesProvider(ILogger logger, + IHttpClient httpClient, + IJsonSerializer jsonSerializer) + { + if (logger is null) + { + throw new System.ArgumentNullException(nameof(logger)); + } + + if (httpClient is null) + { + throw new System.ArgumentNullException(nameof(httpClient)); + } + + if (jsonSerializer is null) + { + throw new System.ArgumentNullException(nameof(jsonSerializer)); + } + + this._logger = logger; + this._httpClient = httpClient; + this._jsonSerializer = jsonSerializer; + this._apiProxy = new KinopoiskApiProxy(logger, httpClient, jsonSerializer); + } + + public Task GetImageResponse(string url, CancellationToken cancellationToken) + { + return _httpClient.GetResponse(new HttpRequestOptions + { + CancellationToken = cancellationToken, + Url = url + }); + } + + public async Task> GetMetadata(SeriesInfo info, CancellationToken cancellationToken) + { + var result = new MetadataResult() + { + QueriedById = true, + Provider = Utils.ProviderName, + ResultLanguage = Utils.ProviderMetadataLanguage + }; + + if (!Utils.TryGetKinopoiskId(info, _logger, out var kinopoiskId)) + return result; + + var film = await _apiProxy.GetSingleFilm(kinopoiskId, cancellationToken); + + result.Item = film.ToSeries(); + if (result.Item != null) + result.HasMetadata = true; + + return result; + } + + public async Task> GetSearchResults(SeriesInfo searchInfo, CancellationToken cancellationToken) + { + if (Utils.TryGetKinopoiskId(searchInfo, _logger, out var kinopoiskId)) + { + var film = await _apiProxy.GetSingleFilm(kinopoiskId, cancellationToken); + var singleResult = new RemoteSearchResult() { + Name = film.Data.NameRu ?? film.Data.NameEn, + ImageUrl = film.Data.PosterUrl, + ProductionYear = Utils.GetFirstYear(film.Data.Year), + Overview = film.Data.Description, + SearchProviderName = Utils.ProviderName + }; + singleResult.SetProviderId(Utils.ProviderId, Convert.ToString(film.Data.FilmId)); + return Enumerable.Repeat(singleResult, 1); + } + else + { + var searchResults = await _apiProxy.SearchByKeyword(searchInfo.Name, cancellationToken: cancellationToken); + return searchResults.Films.Select(f => { + var res = new RemoteSearchResult() { + Name = f.NameRu ?? f.NameEn, + ImageUrl = f.PosterUrl, + ProductionYear = Utils.GetFirstYear(f.Year), + Overview = f.Description, + SearchProviderName = Utils.ProviderName + }; + res.SetProviderId(Utils.ProviderId, Convert.ToString(f.FilmId)); + return res; + }); + } + } + } +} diff --git a/src/Jellyfin.Plugin.Kinopoisk/Plugin.cs b/src/Jellyfin.Plugin.Kinopoisk/Plugin.cs new file mode 100644 index 0000000..c8512d6 --- /dev/null +++ b/src/Jellyfin.Plugin.Kinopoisk/Plugin.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using Jellyfin.Plugin.Kinopoisk.Configuration; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Plugins; +using MediaBrowser.Model.Plugins; +using MediaBrowser.Model.Serialization; + +namespace Jellyfin.Plugin.Kinopoisk +{ + public class Plugin : BasePlugin, IHasWebPages + { + public static Plugin Instance { get; private set; } + + public override string Name => Utils.ProviderName; + + public override string Description => Utils.ProviderDescription; + + public override Guid Id => Guid.Parse("33e6d249-648f-44cd-a9ce-497be06c08df"); + + public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) : base(applicationPaths, xmlSerializer) + { + Instance = this; + } + + public IEnumerable GetPages() + { + return new[] + { + new PluginPageInfo + { + Name = this.Name, + EmbeddedResourcePath = string.Format("{0}.Configuration.configPage.html", GetType().Namespace) + } + }; + } + } +} diff --git a/src/Jellyfin.Plugin.Kinopoisk/Utils.cs b/src/Jellyfin.Plugin.Kinopoisk/Utils.cs new file mode 100644 index 0000000..6334dd9 --- /dev/null +++ b/src/Jellyfin.Plugin.Kinopoisk/Utils.cs @@ -0,0 +1,55 @@ +using System; +using MediaBrowser.Model.Entities; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.Kinopoisk +{ + public static class Utils + { + public const string ProviderId = "kinopoisk"; + public const string ProviderName = "КиноПоиск"; + public const string ProviderDescription = "Загружает рейтинги сайта КиноПоиск"; + public const string ProviderMetadataLanguage = "ru"; + + public static int? GetFirstYear(string years) + { + if (string.IsNullOrWhiteSpace(years)) + return null; + + years = years.Trim(); + + if (int.TryParse(years, out var res)) + return res; + + var i = 0; + while (i < 4) { + if (!char.IsDigit(years[i])) + break; + i++; + } + + return Convert.ToInt32(years.Substring(0, i)); + } + + public static bool TryGetKinopoiskId(IHasProviderIds item, ILogger logger, out int result) + { + var kinopoiskIdStr = item.GetProviderId(Utils.ProviderId); + + if (string.IsNullOrWhiteSpace(kinopoiskIdStr)) + { + logger.LogDebug("Empty ProviderId, skipping"); + result = 0; + return false; + } + + if (!int.TryParse(kinopoiskIdStr, out result)) + { + logger.LogDebug($"Can't parse ProviderId to int, skipping ({kinopoiskIdStr})"); + result = 0; + return false; + } + + return true; + } + } +} diff --git a/src/Kinopoisk.sln b/src/Kinopoisk.sln new file mode 100644 index 0000000..3c4b484 --- /dev/null +++ b/src/Kinopoisk.sln @@ -0,0 +1,48 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26124.0 +MinimumVisualStudioVersion = 15.0.26124.0 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Plugin.Kinopoisk", "Jellyfin.Plugin.Kinopoisk\Jellyfin.Plugin.Kinopoisk.csproj", "{C9335ABD-972B-4FF9-B564-72D9FF7122A2}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Plugin.Kinopoisk.Tests", "Jellyfin.Plugin.Kinopoisk.Tests\Jellyfin.Plugin.Kinopoisk.Tests.csproj", "{7DB17100-0B13-4713-AEDE-B4B9CA96E1CD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C9335ABD-972B-4FF9-B564-72D9FF7122A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C9335ABD-972B-4FF9-B564-72D9FF7122A2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C9335ABD-972B-4FF9-B564-72D9FF7122A2}.Debug|x64.ActiveCfg = Debug|Any CPU + {C9335ABD-972B-4FF9-B564-72D9FF7122A2}.Debug|x64.Build.0 = Debug|Any CPU + {C9335ABD-972B-4FF9-B564-72D9FF7122A2}.Debug|x86.ActiveCfg = Debug|Any CPU + {C9335ABD-972B-4FF9-B564-72D9FF7122A2}.Debug|x86.Build.0 = Debug|Any CPU + {C9335ABD-972B-4FF9-B564-72D9FF7122A2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C9335ABD-972B-4FF9-B564-72D9FF7122A2}.Release|Any CPU.Build.0 = Release|Any CPU + {C9335ABD-972B-4FF9-B564-72D9FF7122A2}.Release|x64.ActiveCfg = Release|Any CPU + {C9335ABD-972B-4FF9-B564-72D9FF7122A2}.Release|x64.Build.0 = Release|Any CPU + {C9335ABD-972B-4FF9-B564-72D9FF7122A2}.Release|x86.ActiveCfg = Release|Any CPU + {C9335ABD-972B-4FF9-B564-72D9FF7122A2}.Release|x86.Build.0 = Release|Any CPU + {7DB17100-0B13-4713-AEDE-B4B9CA96E1CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7DB17100-0B13-4713-AEDE-B4B9CA96E1CD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7DB17100-0B13-4713-AEDE-B4B9CA96E1CD}.Debug|x64.ActiveCfg = Debug|Any CPU + {7DB17100-0B13-4713-AEDE-B4B9CA96E1CD}.Debug|x64.Build.0 = Debug|Any CPU + {7DB17100-0B13-4713-AEDE-B4B9CA96E1CD}.Debug|x86.ActiveCfg = Debug|Any CPU + {7DB17100-0B13-4713-AEDE-B4B9CA96E1CD}.Debug|x86.Build.0 = Debug|Any CPU + {7DB17100-0B13-4713-AEDE-B4B9CA96E1CD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7DB17100-0B13-4713-AEDE-B4B9CA96E1CD}.Release|Any CPU.Build.0 = Release|Any CPU + {7DB17100-0B13-4713-AEDE-B4B9CA96E1CD}.Release|x64.ActiveCfg = Release|Any CPU + {7DB17100-0B13-4713-AEDE-B4B9CA96E1CD}.Release|x64.Build.0 = Release|Any CPU + {7DB17100-0B13-4713-AEDE-B4B9CA96E1CD}.Release|x86.ActiveCfg = Release|Any CPU + {7DB17100-0B13-4713-AEDE-B4B9CA96E1CD}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal