Initial commit

This commit is contained in:
PingWin committed 2020-07-05 14:54:46 +03:00
1 parent 3ea56ab6e0
commit 57fbc1fd79
21 files changed
+1209

No files matched your search

+194
View File
@@ -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
+2
View File
@@ -0,0 +1,2 @@
src/*/bin/*
src/*/obj/*
+25
View File
@@ -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}"
}
]
}
+39
View File
@@ -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"
}
]
}
+8
View File
@@ -0,0 +1,8 @@
{
"folders": [
{
"path": "."
}
],
"settings": {}
}
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
<PackageReference Include="coverlet.collector" Version="1.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Jellyfin.Plugin.Kinopoisk\Jellyfin.Plugin.Kinopoisk.csproj" />
</ItemGroup>
</Project>
@@ -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);
}
}
}
@@ -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; }
}
}
}
@@ -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<Film> 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; }
}
}
}
@@ -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<RemoteImageInfo> ToRemoteImageInfos(this FilmDetails src)
{
var res = Enumerable.Empty<RemoteImageInfo>();
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;
}
}
}
@@ -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;
}
}
@@ -0,0 +1,53 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Template</title>
</head>
<body>
<div id="TemplateConfigPage" data-role="page" class="page type-interior pluginConfigurationPage" data-require="emby-input,emby-button,emby-select,emby-checkbox">
<div data-role="content">
<div class="content-primary">
<form id="TemplateConfigForm">
<div class="inputContainer">
<label class="inputeLabel inputLabelUnfocused" for="ApiToken">ApiToken</label>
<input id="ApiToken" name="ApiToken" type="text" is="emby-input" />
<div class="fieldDescription">Personal api token, you can get your own on
<a href="https://kinopoiskapiunofficial.tech">https://kinopoiskapiunofficial.tech</a>
</div>
</div>
<div>
<button is="emby-button" type="submit" class="raised button-submit block emby-button">
<span>Save</span>
</button>
</div>
</form>
</div>
</div>
<script type="text/javascript">
var TemplateConfig = {
pluginUniqueId: '33e6d249-648f-44cd-a9ce-497be06c08df'
};
$('#TemplateConfigPage').on('pageshow', function () {
Dashboard.showLoadingMsg();
ApiClient.getPluginConfiguration(TemplateConfig.pluginUniqueId).then(function (config) {
$('#ApiToken').val(config.ApiToken).change();
Dashboard.hideLoadingMsg();
});
});
$('#TemplateConfigForm').on('submit', function () {
Dashboard.showLoadingMsg();
ApiClient.getPluginConfiguration(TemplateConfig.pluginUniqueId).then(function (config) {
config.ApiToken = $('#ApiToken').val();
ApiClient.updatePluginConfiguration(TemplateConfig.pluginUniqueId, config).then(function (result) {
Dashboard.processPluginConfigurationUpdateResult(result);
});
});
return false;
});
</script>
</div>
</body>
</html>
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Jellyfin.Controller" Version="10.5.5" />
<PackageReference Include="Jellyfin.Model" Version="10.5.5" />
</ItemGroup>
<ItemGroup>
<None Remove="Configuration\configPage.html" />
<EmbeddedResource Include="Configuration\configPage.html" />
</ItemGroup>
</Project>
@@ -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<SearchResult> 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<SearchResult>(jsonStream).ConfigureAwait(false);
}
}
public async Task<FilmDetails> 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<FilmDetails>(jsonStream).ConfigureAwait(false);
}
}
public async Task<FilmDetails> 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<FilmDetails>(jsonStream).ConfigureAwait(false);
}
}
}
}
@@ -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;
}
}
}
@@ -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<KinopoiskImageProvider> _logger;
private readonly IHttpClient _httpClient;
private readonly IJsonSerializer _jsonSerializer;
private readonly KinopoiskApiProxy _apiProxy;
public string Name => Utils.ProviderName;
public KinopoiskImageProvider(ILogger<KinopoiskImageProvider> 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<ImageType> GetSupportedImages(BaseItem item)
=> new ImageType[]
{
ImageType.Primary,
ImageType.Backdrop
};
public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
{
return _httpClient.GetResponse(new HttpRequestOptions
{
CancellationToken = cancellationToken,
Url = url
});
}
public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
{
if (!Utils.TryGetKinopoiskId(item, _logger, out var kinopoiskId))
return Enumerable.Empty<RemoteImageInfo>();
var film = await _apiProxy.GetSingleFilmImages(kinopoiskId, cancellationToken);
return film.ToRemoteImageInfos();
}
}
}
@@ -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<Movie, MovieInfo>
{
private readonly ILogger<KinopoiskMovieProvider> _logger;
private readonly IHttpClient _httpClient;
private readonly IJsonSerializer _jsonSerializer;
private readonly KinopoiskApiProxy _apiProxy;
public string Name => Utils.ProviderName;
public KinopoiskMovieProvider(ILogger<KinopoiskMovieProvider> 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<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
{
return _httpClient.GetResponse(new HttpRequestOptions
{
CancellationToken = cancellationToken,
Url = url
});
}
public async Task<MetadataResult<Movie>> GetMetadata(MovieInfo info, CancellationToken cancellationToken)
{
var result = new MetadataResult<Movie>()
{
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<IEnumerable<RemoteSearchResult>> 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;
});
}
}
}
}
@@ -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<Series, SeriesInfo>
{
private readonly ILogger<KinopoiskSeriesProvider> _logger;
private readonly IHttpClient _httpClient;
private readonly IJsonSerializer _jsonSerializer;
private readonly KinopoiskApiProxy _apiProxy;
public string Name => Utils.ProviderName;
public KinopoiskSeriesProvider(ILogger<KinopoiskSeriesProvider> 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<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
{
return _httpClient.GetResponse(new HttpRequestOptions
{
CancellationToken = cancellationToken,
Url = url
});
}
public async Task<MetadataResult<Series>> GetMetadata(SeriesInfo info, CancellationToken cancellationToken)
{
var result = new MetadataResult<Series>()
{
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<IEnumerable<RemoteSearchResult>> 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;
});
}
}
}
}
+38
View File
@@ -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<PluginConfiguration>, 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<PluginPageInfo> GetPages()
{
return new[]
{
new PluginPageInfo
{
Name = this.Name,
EmbeddedResourcePath = string.Format("{0}.Configuration.configPage.html", GetType().Namespace)
}
};
}
}
}
+55
View File
@@ -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;
}
}
}
+48
View File
@@ -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