Значительно улучшено авто-привязка фильмов при добавлении в медиатеку.

Пытаюсь найти идентификатор кинопоиска по паттерну kp-12345 или kp12345 в имени файла/папки.
  Пытаюсь найти единственное совпадение на кинопоиске по имени + году.
  Пытаюсь перебрать все совпадения по имени + сравнение IMDB ID.
This commit is contained in:
PingWin committed 2021-05-23 15:31:18 +00:00
1 parent b8b92cf60b
commit ea2ef35664
37 files changed
+723 -155

No files matched your search

+14
View File
@@ -49,6 +49,20 @@
"presentation": { "presentation": {
"reveal": "silent" "reveal": "silent"
}, },
"problemMatcher": "$msCompile",
"dependsOn": ["clear-plugin-state-before-debug"]
},
{
"label": "clear-plugin-state-before-debug",
"command": "rm",
"type": "process",
"args": [
"-f", "/jellyfin-data/plugins/kinopoisk/meta.json"
],
"group": "build",
"presentation": {
"reveal": "silent"
},
"problemMatcher": "$msCompile" "problemMatcher": "$msCompile"
}, },
{ {
+24 -2
View File
@@ -1,8 +1,30 @@
# jellyfin-plugin-kinopoisk # jellyfin-plugin-kinopoisk
Fetches metadata from kinopoisk
Установка: Fetches metadata from https://www.kinopoisk.ru/. This site is popular in the Russian-speaking community and contains almost no English-language information, so further description will be in Russian.
## Установка
Администрирование - Панель - Расширенное - Плагины - вкладка Репозитории - добавить адрес https://raw.githubusercontent.com/LinFor/jellyfin-plugin-kinopoisk/master/dist/manifest.json. Администрирование - Панель - Расширенное - Плагины - вкладка Репозитории - добавить адрес https://raw.githubusercontent.com/LinFor/jellyfin-plugin-kinopoisk/master/dist/manifest.json.
После этого на вкладке Каталог найти "КиноПоиск" (раздел Метаданные) и установить. После этого на вкладке Каталог найти "КиноПоиск" (раздел Метаданные) и установить.
## Настройка
Параметры плагина искать в: Администрирование - Панель - Расширенное - Плагины - вкладка "Мои плагины" - КиноПоиск - "три точки" - Параметры
Если плагин не работает или работает плохо - попробуйте зарегистрировать (и указать в параметрах) свой собственный ApiToken (на сайте https://kinopoiskapiunofficial.tech). По-умолчанию прописан общий, ограничение порядка 10 запросов/сек - для общего ApiToken быстро заканчивается.
## Использование
Поддерживаются:
- Фильмы
- Сериалы
На данный момент грузятся:
- Рейтинг
- Описание
- Постеры и задники
- Актёры
- Трейлеры (только те, что лежат на ютубе - Jellyfin-Web не умеет играть трейлеры, лежащие на самом КиноПоиске)
Плагин будет пытаться найти в имени файла (для фильмов) или имени корневой папки (для сериалов) паттерн вида "kp-12345" или "kp12345", где число - id фильма на сайте КиноПоиск.
Binary file not shown.
+10 -2
View File
@@ -3,11 +3,19 @@
"category": "Metadata", "category": "Metadata",
"guid": "0c136f8a-ff77-4f2b-ade5-13462cae6216", "guid": "0c136f8a-ff77-4f2b-ade5-13462cae6216",
"name": "\u041a\u0438\u043d\u043e\u041f\u043e\u0438\u0441\u043a", "name": "\u041a\u0438\u043d\u043e\u041f\u043e\u0438\u0441\u043a",
"overview": "\u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u0442 \u0440\u0435\u0439\u0442\u0438\u043d\u0433\u0438 \u0441\u0430\u0439\u0442\u0430 \u041a\u0438\u043d\u043e\u041f\u043e\u0438\u0441\u043a", "overview": "\u0418\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f \u043e \u0444\u0438\u043b\u044c\u043c\u0430\u0445 \u0438 \u0441\u0435\u0440\u0438\u0430\u043b\u0430\u0445 \u0441 \u041a\u0438\u043d\u043e\u041f\u043e\u0438\u0441\u043a\u0430",
"owner": "linfor", "owner": "linfor",
"description": "\u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u0442 \u0440\u0435\u0439\u0442\u0438\u043d\u0433\u0438 \u0441\u0430\u0439\u0442\u0430 \u041a\u0438\u043d\u043e\u041f\u043e\u0438\u0441\u043a\n", "description": "\u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u0442 \u0440\u0435\u0439\u0442\u0438\u043d\u0433, \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u044f, \u0430\u043a\u0442\u0451\u0440\u043e\u0432, \u0442\u0440\u0435\u0439\u043b\u0435\u0440\u044b \u0438 \u0442.\u0434. \u0441 \u0441\u0430\u0439\u0442\u0430 \u041a\u0438\u043d\u043e\u041f\u043e\u0438\u0441\u043a. \u041c\u043e\u0436\u0435\u0442 \u043f\u043e\u0442\u0440\u0435\u0431\u043e\u0432\u0430\u0442\u044c\u0441\u044f \u0437\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0441\u0432\u043e\u0439 ApiToken, \u0441\u043c. \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044e \u0432 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u0430\u0445 \u043f\u043b\u0430\u0433\u0438\u043d\u0430. \u0414\u043b\u044f \u0442\u043e\u0447\u043d\u043e\u0433\u043e \u0440\u0430\u0441\u043f\u043e\u0437\u043d\u0430\u0432\u0430\u043d\u0438\u044f \u0440\u0435\u043a\u043e\u043c\u0435\u043d\u0434\u0443\u0435\u0442\u0441\u044f \u0443\u043a\u0430\u0437\u044b\u0432\u0430\u0442\u044c id \u0444\u0438\u043b\u044c\u043c\u0430 \u0441 \u0441\u0430\u0439\u0442\u0430 \u041a\u0438\u043d\u043e\u041f\u043e\u0438\u0441\u043a \u0432 \u0438\u043c\u0435\u043d\u0438 \u0444\u0430\u0439\u043b\u0430 \u0432 \u0444\u043e\u0440\u043c\u0430\u0442\u0435 kp-12345 \u0438\u043b\u0438 kp12345. \u041f\u043e\u0434\u0440\u043e\u0431\u043d\u0435\u0435 \u0441\u043c. https://github.com/LinFor/jellyfin-plugin-kinopoisk/blob/master/README.md\n",
"imageUrl": "https://kinopoisk.userecho.com/s/attachments/28876/0/1/25f8c0315e6ccb2aa6c2642e48f2c9e9.png", "imageUrl": "https://kinopoisk.userecho.com/s/attachments/28876/0/1/25f8c0315e6ccb2aa6c2642e48f2c9e9.png",
"versions": [ "versions": [
{
"version": "10.7.5.0",
"changelog": "Short: Huge improvement in auto-identifying of movies. Rus: \u0417\u043d\u0430\u0447\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u0443\u043b\u0443\u0447\u0448\u0435\u043d\u043e \u0430\u0432\u0442\u043e-\u043f\u0440\u0438\u0432\u044f\u0437\u043a\u0430 \u0444\u0438\u043b\u044c\u043c\u043e\u0432 \u043f\u0440\u0438 \u0434\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0438 \u0432 \u043c\u0435\u0434\u0438\u0430\u0442\u0435\u043a\u0443. \u041f\u044b\u0442\u0430\u044e\u0441\u044c \u043d\u0430\u0439\u0442\u0438 \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u043a\u0438\u043d\u043e\u043f\u043e\u0438\u0441\u043a\u0430 \u043f\u043e \u043f\u0430\u0442\u0442\u0435\u0440\u043d\u0443 kp-12345 \u0438\u043b\u0438 kp12345 \u0432 \u0438\u043c\u0435\u043d\u0438 \u0444\u0430\u0439\u043b\u0430/\u043f\u0430\u043f\u043a\u0438. \u041f\u044b\u0442\u0430\u044e\u0441\u044c \u043d\u0430\u0439\u0442\u0438 \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u043e\u0435 \u0441\u043e\u0432\u043f\u0430\u0434\u0435\u043d\u0438\u0435 \u043d\u0430 \u043a\u0438\u043d\u043e\u043f\u043e\u0438\u0441\u043a\u0435 \u043f\u043e \u0438\u043c\u0435\u043d\u0438 + \u0433\u043e\u0434\u0443. \u041f\u044b\u0442\u0430\u044e\u0441\u044c \u043f\u0435\u0440\u0435\u0431\u0440\u0430\u0442\u044c \u0432\u0441\u0435 \u0441\u043e\u0432\u043f\u0430\u0434\u0435\u043d\u0438\u044f \u043f\u043e \u0438\u043c\u0435\u043d\u0438 + \u0441\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0435 IMDB ID.\n",
"targetAbi": "10.7.0",
"sourceUrl": "https://raw.githubusercontent.com/LinFor/jellyfin-plugin-kinopoisk/master/dist/kinopoisk/kinopoisk_10.7.5.0.zip",
"checksum": "ea7eabac0fc4d1891529616a16a02897",
"timestamp": "2021-05-23T15:30:18Z"
},
{ {
"version": "10.7.0.5", "version": "10.7.0.5",
"changelog": "Added trailers filtering: jellyfin-web can only play youtube trailers, not kinopoisk-hosted\n", "changelog": "Added trailers filtering: jellyfin-web can only play youtube trailers, not kinopoisk-hosted\n",
@@ -23,9 +23,9 @@ namespace Jellyfin.Plugin.Kinopoisk
ImageUrl = src.Data.PosterUrl, ImageUrl = src.Data.PosterUrl,
PremiereDate = src.Data.GetPremiereDate(), PremiereDate = src.Data.GetPremiereDate(),
Overview = src.Data.Description, Overview = src.Data.Description,
SearchProviderName = Utils.ProviderName SearchProviderName = Constants.ProviderName
}; };
res.SetProviderId(Utils.ProviderId, Convert.ToString(src.Data.FilmId)); res.SetProviderId(Constants.ProviderId, Convert.ToString(src.Data.FilmId));
return res; return res;
} }
@@ -48,9 +48,9 @@ namespace Jellyfin.Plugin.Kinopoisk
ImageUrl = src.PosterUrl, ImageUrl = src.PosterUrl,
PremiereDate = src.GetPremiereDate(), PremiereDate = src.GetPremiereDate(),
Overview = src.Description, Overview = src.Description,
SearchProviderName = Utils.ProviderName SearchProviderName = Constants.ProviderName
}; };
res.SetProviderId(Utils.ProviderId, Convert.ToString(src.FilmId)); res.SetProviderId(Constants.ProviderId, Convert.ToString(src.FilmId));
return res; return res;
} }
@@ -86,7 +86,7 @@ namespace Jellyfin.Plugin.Kinopoisk
private static void FillCommonFilmInfo(Film src, BaseItem dst) private static void FillCommonFilmInfo(Film src, BaseItem dst)
{ {
dst.SetProviderId(Utils.ProviderId, Convert.ToString(src.Data.FilmId)); dst.SetProviderId(Constants.ProviderId, Convert.ToString(src.Data.FilmId));
dst.Name = src.GetLocalName(); dst.Name = src.GetLocalName();
dst.OriginalTitle = src.GetOriginalNameIfNotSame(); dst.OriginalTitle = src.GetOriginalNameIfNotSame();
dst.PremiereDate = src.Data.GetPremiereDate(); dst.PremiereDate = src.Data.GetPremiereDate();
@@ -148,8 +148,8 @@ namespace Jellyfin.Plugin.Kinopoisk
var mainPoster = new RemoteImageInfo(){ var mainPoster = new RemoteImageInfo(){
Type = ImageType.Primary, Type = ImageType.Primary,
Url = src.Data.PosterUrl, Url = src.Data.PosterUrl,
Language = Utils.ProviderMetadataLanguage, Language = Constants.ProviderMetadataLanguage,
ProviderName = Utils.ProviderName ProviderName = Constants.ProviderName
}; };
res = res.Concat(Enumerable.Repeat(mainPoster, 1)); res = res.Concat(Enumerable.Repeat(mainPoster, 1));
} }
@@ -182,7 +182,7 @@ namespace Jellyfin.Plugin.Kinopoisk
Language = src.Language, Language = src.Language,
Height = src.Height, Height = src.Height,
Width = src.Width, Width = src.Width,
ProviderName = Utils.ProviderName ProviderName = Constants.ProviderName
}; };
} }
@@ -203,11 +203,19 @@ namespace Jellyfin.Plugin.Kinopoisk
return new MediaUrl return new MediaUrl
{ {
Name = src.Name, Name = src.Name,
Url = src.Url Url = src.Url.SanitizeYoutubeLink()
.Replace("https://youtu.be/", "https://www.youtube.com/watch?v=") // Jellyfin web currently don't recognize youtu.be links
}; };
} }
public static string SanitizeYoutubeLink(this string src)
{
// Jellyfin web currently recognizes only https://www.youtube.com/watch?v=xxx links
return src
.Replace("http://", "https://")
.Replace("https://youtu.be/", "https://www.youtube.com/watch?v=")
.Replace("https://www.youtube.com/v/", "https://www.youtube.com/watch?v=");
}
public static RemoteImageInfo ToRemoteImageInfo(this PersonResponse src) public static RemoteImageInfo ToRemoteImageInfo(this PersonResponse src)
{ {
if (src is null || string.IsNullOrEmpty(src.PosterUrl)) if (src is null || string.IsNullOrEmpty(src.PosterUrl))
@@ -216,7 +224,7 @@ namespace Jellyfin.Plugin.Kinopoisk
return new RemoteImageInfo(){ return new RemoteImageInfo(){
Type = ImageType.Primary, Type = ImageType.Primary,
Url = src.PosterUrl, Url = src.PosterUrl,
ProviderName = Utils.ProviderName ProviderName = Constants.ProviderName
}; };
} }
@@ -234,7 +242,10 @@ namespace Jellyfin.Plugin.Kinopoisk
}; };
if (string.IsNullOrWhiteSpace(res.Name)) if (string.IsNullOrWhiteSpace(res.Name))
res.Name = src.NameEn ?? string.Empty; res.Name = src.NameEn ?? string.Empty;
res.SetProviderId(Utils.ProviderId, Convert.ToString(src.StaffId)); if (src.AdditionalProperties.TryGetValue("description", out var description))
res.Role = description as string;
res.SetProviderId(Constants.ProviderId, Convert.ToString(src.StaffId));
return res; return res;
} }
@@ -0,0 +1,16 @@
using System;
using System.Text.RegularExpressions;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.Kinopoisk
{
public static class Constants
{
public const string ProviderId = "kinopoisk";
public const string ProviderName = "КиноПоиск";
public const string ProviderDescription = "Информация о фильмах и сериалах с КиноПоиска";
public const string ProviderMetadataLanguage = "ru";
}
}
@@ -1,6 +1,10 @@
using System.Net.Http; using System.Net.Http;
using Jellyfin.Plugin.Kinopoisk.ProviderIdResolvers;
using KinopoiskUnofficialInfo.ApiClient; using KinopoiskUnofficialInfo.ApiClient;
using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Plugins;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -13,10 +17,21 @@ namespace Jellyfin.Plugin.Kinopoisk
{ {
public void RegisterServices(IServiceCollection serviceCollection) public void RegisterServices(IServiceCollection serviceCollection)
{ {
serviceCollection.AddSingleton<IKinopoiskApiClient>((sp) => new KinopoiskApiClient( serviceCollection.AddSingleton((sp) => new KinopoiskApiClient(
Plugin.Instance.Configuration.ApiToken, Plugin.Instance.Configuration.ApiToken,
sp.GetRequiredService<ILogger<KinopoiskApiClient>>(), sp.GetRequiredService<ILogger<KinopoiskApiClient>>(),
sp.GetRequiredService<IHttpClientFactory>())); sp.GetRequiredService<IHttpClientFactory>()
));
serviceCollection.AddSingleton<IKinopoiskApiClient>((sp) => new CachedKinopoiskApiClient(
sp.GetRequiredService<KinopoiskApiClient>(),
sp.GetRequiredService<IMemoryCache>(),
sp.GetRequiredService<ILogger<CachedKinopoiskApiClient>>()
));
serviceCollection.AddSingleton<IProviderIdResolver<MovieInfo>, VideoResolver<MovieInfo>>();
serviceCollection.AddSingleton<IProviderIdResolver<SeriesInfo>, VideoResolver<SeriesInfo>>();
serviceCollection.AddSingleton<IProviderIdResolver<PersonLookupInfo>, CommonResolver<PersonLookupInfo>>();
serviceCollection.AddSingleton<IProviderIdResolver<BaseItem>, CommonResolver<BaseItem>>();
} }
} }
} }
@@ -15,7 +15,7 @@ namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders
_httpClientFactory = httpClientFactory ?? throw new System.ArgumentNullException(nameof(httpClientFactory)); _httpClientFactory = httpClientFactory ?? throw new System.ArgumentNullException(nameof(httpClientFactory));
} }
public string Name => Utils.ProviderName; public string Name => Constants.ProviderName;
public async Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken) public async Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
{ {
@@ -3,26 +3,30 @@ using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Jellyfin.Plugin.Kinopoisk.ProviderIdResolvers;
using KinopoiskUnofficialInfo.ApiClient; using KinopoiskUnofficialInfo.ApiClient;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers; using MediaBrowser.Model.Providers;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders
{ {
public abstract class VideoBaseProvider<TItemType, TLookupInfoType> : BaseMetadataProvider, IRemoteMetadataProvider<TItemType, TLookupInfoType> public abstract class BaseVideoMetadataProvider<TItemType, TLookupInfoType> : BaseMetadataProvider, IRemoteMetadataProvider<TItemType, TLookupInfoType>
where TItemType : BaseItem, IHasLookupInfo<TLookupInfoType> where TItemType : BaseItem, IHasLookupInfo<TLookupInfoType>
where TLookupInfoType : ItemLookupInfo, new() where TLookupInfoType : ItemLookupInfo, new()
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IKinopoiskApiClient _apiClient; private readonly IKinopoiskApiClient _apiClient;
private readonly IProviderIdResolver<TLookupInfoType> _providerIdResolver;
public VideoBaseProvider(IKinopoiskApiClient kinopoiskApiClient, ILogger logger, IHttpClientFactory httpClientFactory) public BaseVideoMetadataProvider(IKinopoiskApiClient kinopoiskApiClient, IProviderIdResolver<TLookupInfoType> providerIdResolver, ILogger logger, IHttpClientFactory httpClientFactory)
: base(httpClientFactory) : base(httpClientFactory)
{ {
this._logger = logger ?? throw new System.ArgumentNullException(nameof(logger)); _logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
this._apiClient = kinopoiskApiClient ?? throw new System.ArgumentNullException(nameof(kinopoiskApiClient)); _apiClient = kinopoiskApiClient ?? throw new System.ArgumentNullException(nameof(kinopoiskApiClient));
_providerIdResolver = providerIdResolver ?? throw new System.ArgumentNullException(nameof(providerIdResolver));
} }
protected abstract TItemType ConvertResponseToItem(Film apiResponse); protected abstract TItemType ConvertResponseToItem(Film apiResponse);
@@ -32,11 +36,12 @@ namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders
var result = new MetadataResult<TItemType>() var result = new MetadataResult<TItemType>()
{ {
QueriedById = true, QueriedById = true,
Provider = Utils.ProviderName, Provider = Constants.ProviderName,
ResultLanguage = Utils.ProviderMetadataLanguage ResultLanguage = Constants.ProviderMetadataLanguage
}; };
if (!Utils.TryGetKinopoiskId(info, _logger, out var kinopoiskId)) var (resolveResult, kinopoiskId) = await _providerIdResolver.TryResolve(info, cancellationToken);
if (!resolveResult)
return result; return result;
var film = await _apiClient.GetSingleFilm(kinopoiskId, cancellationToken); var film = await _apiClient.GetSingleFilm(kinopoiskId, cancellationToken);
@@ -51,7 +56,8 @@ namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
foreach (var item in staff.ToPersonInfos()) var sanitizedPersons = await SanitizeEmptyImagePersonInfos(staff.ToPersonInfos());
foreach (var item in sanitizedPersons)
result.AddPerson(item); result.AddPerson(item);
var trailers = await _apiClient.GetTrailers(kinopoiskId, cancellationToken); var trailers = await _apiClient.GetTrailers(kinopoiskId, cancellationToken);
@@ -65,7 +71,8 @@ namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders
public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(TLookupInfoType searchInfo, CancellationToken cancellationToken) public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(TLookupInfoType searchInfo, CancellationToken cancellationToken)
{ {
if (Utils.TryGetKinopoiskId(searchInfo, _logger, out var kinopoiskId)) if (searchInfo.TryGetProviderId(Constants.ProviderId, out var kinopoiskIdStr)
&& int.TryParse(kinopoiskIdStr, out var kinopoiskId))
{ {
var singleResult = (await _apiClient.GetSingleFilm(kinopoiskId, cancellationToken)).ToRemoteSearchResult(); var singleResult = (await _apiClient.GetSingleFilm(kinopoiskId, cancellationToken)).ToRemoteSearchResult();
return Enumerable.Repeat(singleResult, 1); return Enumerable.Repeat(singleResult, 1);
@@ -75,5 +82,17 @@ namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders
return (await _apiClient.SearchByKeyword(searchInfo.Name, cancellationToken: cancellationToken)).ToRemoteSearchResults(); return (await _apiClient.SearchByKeyword(searchInfo.Name, cancellationToken: cancellationToken)).ToRemoteSearchResults();
} }
} }
protected async Task<IEnumerable<PersonInfo>> SanitizeEmptyImagePersonInfos(IEnumerable<PersonInfo> images)
{
using var httpClient = new HttpClient(new HttpClientHandler() { AllowAutoRedirect = false }, true);
var sanitizer = new RemoteImageUrlSanitizer(httpClient);
var res = await Task.WhenAll(images.Select(async p => {
p.ImageUrl = await sanitizer.SanitizeRemoteImageUrl(p.ImageUrl);
return p;
}));
return res.Where(i => i != null).ToArray();
}
} }
} }
@@ -0,0 +1,20 @@
using System.Net.Http;
using Jellyfin.Plugin.Kinopoisk.ProviderIdResolvers;
using KinopoiskUnofficialInfo.ApiClient;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Providers;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders
{
public class MovieMetadataProvider : BaseVideoMetadataProvider<Movie, MovieInfo>
{
public MovieMetadataProvider(IKinopoiskApiClient kinopoiskApiClient, IProviderIdResolver<MovieInfo> providerIdResolver, ILogger<MovieMetadataProvider> logger, IHttpClientFactory httpClientFactory)
: base(kinopoiskApiClient, providerIdResolver, logger, httpClientFactory)
{
}
protected override Movie ConvertResponseToItem(Film apiResponse)
=> apiResponse.ToMovie();
}
}
@@ -1,18 +0,0 @@
using System.Net.Http;
using KinopoiskUnofficialInfo.ApiClient;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Providers;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders
{
public class MovieProvider : VideoBaseProvider<Movie, MovieInfo>
{
public MovieProvider(IKinopoiskApiClient kinopoiskApiClient, ILogger<MovieProvider> logger, IHttpClientFactory httpClientFactory) : base(kinopoiskApiClient, logger, httpClientFactory)
{
}
protected override Movie ConvertResponseToItem(Film apiResponse)
=> apiResponse.ToMovie();
}
}
@@ -3,25 +3,26 @@ using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Jellyfin.Plugin.Kinopoisk; using Jellyfin.Plugin.Kinopoisk.ProviderIdResolvers;
using Jellyfin.Plugin.Kinopoisk.MetadataProviders;
using KinopoiskUnofficialInfo.ApiClient; using KinopoiskUnofficialInfo.ApiClient;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Providers; using MediaBrowser.Model.Providers;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace k.MetadataProviders namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders
{ {
public class PersonProvider : BaseMetadataProvider, IRemoteMetadataProvider<Person, PersonLookupInfo> public class PersonMetadataProvider : BaseMetadataProvider, IRemoteMetadataProvider<Person, PersonLookupInfo>
{ {
private readonly IKinopoiskApiClient _apiClient; private readonly IKinopoiskApiClient _apiClient;
private readonly ILogger<PersonProvider> _logger; private readonly IProviderIdResolver<PersonLookupInfo> _providerIdResolver;
private readonly ILogger<PersonMetadataProvider> _logger;
public PersonProvider(IKinopoiskApiClient apiClient, ILogger<PersonProvider> logger, IHttpClientFactory httpClientFactory) public PersonMetadataProvider(IKinopoiskApiClient apiClient, IProviderIdResolver<PersonLookupInfo> providerIdResolver, ILogger<PersonMetadataProvider> logger, IHttpClientFactory httpClientFactory)
: base(httpClientFactory) : base(httpClientFactory)
{ {
_apiClient = apiClient ?? throw new System.ArgumentNullException(nameof(apiClient)); _apiClient = apiClient ?? throw new System.ArgumentNullException(nameof(apiClient));
_providerIdResolver = providerIdResolver ?? throw new System.ArgumentNullException(nameof(providerIdResolver));
_logger = logger ?? throw new System.ArgumentNullException(nameof(logger)); _logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
} }
@@ -30,11 +31,12 @@ namespace k.MetadataProviders
var result = new MetadataResult<Person>() var result = new MetadataResult<Person>()
{ {
QueriedById = true, QueriedById = true,
Provider = Utils.ProviderName, Provider = Constants.ProviderName,
ResultLanguage = Utils.ProviderMetadataLanguage ResultLanguage = Constants.ProviderMetadataLanguage
}; };
if (!Utils.TryGetKinopoiskId(info, _logger, out var kinopoiskId)) var (resolveResult, kinopoiskId) = await _providerIdResolver.TryResolve(info, cancellationToken);
if (!resolveResult)
return result; return result;
var person = await _apiClient.GetPerson(kinopoiskId, cancellationToken); var person = await _apiClient.GetPerson(kinopoiskId, cancellationToken);
@@ -0,0 +1,20 @@
using System.Net.Http;
using Jellyfin.Plugin.Kinopoisk.ProviderIdResolvers;
using KinopoiskUnofficialInfo.ApiClient;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders
{
public class SeriesMetadataProvider : BaseVideoMetadataProvider<Series, SeriesInfo>
{
public SeriesMetadataProvider(IKinopoiskApiClient kinopoiskApiClient, IProviderIdResolver<SeriesInfo> providerIdResolver, ILogger<SeriesMetadataProvider> logger, IHttpClientFactory httpClientFactory)
: base(kinopoiskApiClient, providerIdResolver, logger, httpClientFactory)
{
}
protected override Series ConvertResponseToItem(Film apiResponse)
=> apiResponse.ToSeries();
}
}
@@ -1,18 +0,0 @@
using System.Net.Http;
using KinopoiskUnofficialInfo.ApiClient;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders
{
public class SeriesProvider : VideoBaseProvider<Series, SeriesInfo>
{
public SeriesProvider(IKinopoiskApiClient kinopoiskApiClient, ILogger<SeriesProvider> logger, IHttpClientFactory httpClientFactory) : base(kinopoiskApiClient, logger, httpClientFactory)
{
}
protected override Series ConvertResponseToItem(Film apiResponse)
=> apiResponse.ToSeries();
}
}
@@ -9,9 +9,9 @@ namespace Jellyfin.Plugin.Kinopoisk.Model
{ {
public class KinopoiskExternalId : IExternalId public class KinopoiskExternalId : IExternalId
{ {
public string ProviderName => Utils.ProviderName; public string ProviderName => Constants.ProviderName;
public string Key => Utils.ProviderId; public string Key => Constants.ProviderId;
public string UrlFormatString => "https://www.kinopoisk.ru/film/{0}"; public string UrlFormatString => "https://www.kinopoisk.ru/film/{0}";
@@ -7,9 +7,9 @@ namespace Jellyfin.Plugin.Kinopoisk.Model
{ {
public class KinopoiskPersonExternalId : IExternalId public class KinopoiskPersonExternalId : IExternalId
{ {
public string ProviderName => Utils.ProviderName; public string ProviderName => Constants.ProviderName;
public string Key => Utils.ProviderId; public string Key => Constants.ProviderId;
public string UrlFormatString => "https://www.kinopoisk.ru/name/{0}"; public string UrlFormatString => "https://www.kinopoisk.ru/name/{0}";
+2 -2
View File
@@ -12,9 +12,9 @@ namespace Jellyfin.Plugin.Kinopoisk
{ {
public static Plugin Instance { get; private set; } public static Plugin Instance { get; private set; }
public override string Name => Utils.ProviderName; public override string Name => Constants.ProviderName;
public override string Description => Utils.ProviderDescription; public override string Description => Constants.ProviderDescription;
public override Guid Id => Guid.Parse("33e6d249-648f-44cd-a9ce-497be06c08df"); public override Guid Id => Guid.Parse("33e6d249-648f-44cd-a9ce-497be06c08df");
@@ -0,0 +1,39 @@
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Providers;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.Kinopoisk.ProviderIdResolvers
{
public class CommonLookupInfoResolver<T> : CommonResolver<T>
where T : ItemLookupInfo
{
private readonly Regex _kinopoiskIdRegex = new(@"kp-?(?<kinopoiskId>\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
public CommonLookupInfoResolver(ILogger<CommonLookupInfoResolver<T>> logger)
: base(logger)
{
}
public override async Task<(bool IsSuccess, int ProviderId)> TryResolve(T info, CancellationToken? ct = null)
{
// Try to get from stored metadata
var baseResult = await base.TryResolve(info, ct);
if (baseResult.IsSuccess)
return baseResult;
// Try to get from filename
if (!string.IsNullOrEmpty(info.Path))
{
var match = _kinopoiskIdRegex.Match(info.Path);
if (match.Success && int.TryParse(match.Groups["kinopoiskId"].Value, out var result))
{
_logger.LogDebug($"Got KinopoiskProviderId from filename ({result}, {info.Path})");
return (true, result);
}
}
return (false, 0);
}
}
}
@@ -0,0 +1,33 @@
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Entities;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.Kinopoisk.ProviderIdResolvers
{
public class CommonResolver<T> : IProviderIdResolver<T>
where T : IHasProviderIds
{
protected readonly ILogger<CommonResolver<T>> _logger;
public CommonResolver(ILogger<CommonResolver<T>> logger)
{
_logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
}
public virtual Task<(bool IsSuccess, int ProviderId)> TryResolve(T info, CancellationToken? ct = null)
{
// Try to get from stored metadata
var kinopoiskIdStr = info.GetProviderId(Constants.ProviderId);
// Try to get from stored metadata
if (!string.IsNullOrEmpty(kinopoiskIdStr) && int.TryParse(kinopoiskIdStr, out var result))
{
_logger.LogDebug($"Got KinopoiskProviderId from metadata ({result})");
return Task.FromResult((true, result));
}
return Task.FromResult((false, 0));
}
}
}
@@ -0,0 +1,12 @@
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Entities;
namespace Jellyfin.Plugin.Kinopoisk.ProviderIdResolvers
{
public interface IProviderIdResolver<T>
where T: IHasProviderIds
{
Task<(bool IsSuccess, int ProviderId)> TryResolve(T info, CancellationToken? ct = null);
}
}
@@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using KinopoiskUnofficialInfo.ApiClient;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.Kinopoisk.ProviderIdResolvers
{
public class VideoResolver<T> : CommonLookupInfoResolver<T>
where T : ItemLookupInfo
{
private readonly IKinopoiskApiClient _kinopoiskApiClient;
public VideoResolver(IKinopoiskApiClient kinopoiskApiClient, ILogger<VideoResolver<T>> logger) : base(logger)
{
_kinopoiskApiClient = kinopoiskApiClient ?? throw new ArgumentNullException(nameof(kinopoiskApiClient));
}
public override async Task<(bool IsSuccess, int ProviderId)> TryResolve(T info, CancellationToken? ct = null)
{
// Try to get from standart sources
var possibleResult = await base.TryResolve(info, ct);
if (possibleResult.IsSuccess)
return possibleResult;
// Trying to find empirically on kinopoisk
if (string.IsNullOrWhiteSpace(info.Name))
{
_logger.LogDebug($"Film name is empty, skipping KinopoiskProviderId search");
return (false, 0);
}
_logger.LogDebug($"Trying to get suitable film with name '{info.Name}'...");
var searchResult = await _kinopoiskApiClient.SearchByKeyword(info.Name, 1, ct ?? CancellationToken.None);
if (searchResult.SearchFilmsCountResult < 1 || searchResult?.Films.Count < 1)
{
_logger.LogDebug($"Received empty search result");
return (false, 0);
}
var candidates = searchResult.Films.ToArray();
_logger.LogDebug($"Received {candidates.Length} results, trying to filter and match...");
// Check if there are single candidate filtered by year
possibleResult = await TryResolveBySingleCandidateLeft(info, FilterByYear(info, candidates), ct);
if (possibleResult.IsSuccess)
return possibleResult;
// Try to resolve by ImdbId match filtered by year
possibleResult = await TryResolveByImdbMatch(info, FilterByYear(info, candidates), ct);
if (possibleResult.IsSuccess)
return possibleResult;
// Try to resolve by ImdbId match without filtering
possibleResult = await TryResolveByImdbMatch(info, candidates, ct);
if (possibleResult.IsSuccess)
return possibleResult;
_logger.LogDebug($"Suitable result not found");
return (false, 0);
}
public async Task<(bool IsSuccess, int ProviderId)> TryResolveByImdbMatch(T info, ICollection<FilmSearchResponse_films> candidates, CancellationToken? ct = null)
{
if (info.TryGetProviderId(MetadataProvider.Imdb, out var imdbId))
{
_logger.LogDebug($"Trying to find result with ImdbId '{imdbId}'...");
var index = 0;
foreach (var candidate in candidates)
{
try
{
var film = await _kinopoiskApiClient.GetSingleFilm(candidate.FilmId, ct);
if (imdbId == film?.ExternalId?.ImdbId)
{
_logger.LogDebug($"Found match: {candidate.FilmId} '{film.GetLocalName()}', ImdbId '{film?.ExternalId?.ImdbId}', setting KinopoiskProviderId to {candidate.FilmId}");
return (true, candidate.FilmId);
}
_logger.LogDebug($"Film {candidate.FilmId} '{film.GetLocalName()}' has ImdbId '{film?.ExternalId?.ImdbId}', skipping, {candidates.Count - ++index} candidates left...");
} catch (Exception e)
{
_logger.LogError(e, $"Error while retrieving film {candidate.FilmId}");
continue;
}
}
}
return (false, 0);
}
public Task<(bool IsSuccess, int ProviderId)> TryResolveBySingleCandidateLeft(T info, ICollection<FilmSearchResponse_films> candidates, CancellationToken? ct = null)
{
if (candidates.Count == 1)
{
var kinopoiskId = candidates.Single().FilmId;
_logger.LogDebug($"There is single candidate left, setting KinopoiskProviderId to {kinopoiskId} ({info.Name})");
return Task.FromResult((true, kinopoiskId));
}
return Task.FromResult((false, 0));
}
public ICollection<FilmSearchResponse_films> FilterByYear(T info, ICollection<FilmSearchResponse_films> candidates)
{
if (!info.Year.HasValue)
{
_logger.LogDebug($"Can't filter by year, no year set in metadata...");
return Array.Empty<FilmSearchResponse_films>();
}
var targetYear = info.Year.Value.ToString();
var res = candidates.Where(f => f.Year == targetYear).ToArray();
_logger.LogDebug($"Filtered by year {targetYear}, {res.Length} results left...");
return res;
}
}
}
@@ -37,34 +37,17 @@ namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders
protected async Task<IEnumerable<RemoteImageInfo>> FilterEmptyImages(IEnumerable<RemoteImageInfo> images) protected async Task<IEnumerable<RemoteImageInfo>> FilterEmptyImages(IEnumerable<RemoteImageInfo> images)
{ {
using var httpClient = new HttpClient(new HttpClientHandler() { AllowAutoRedirect = false }, true); using var httpClient = new HttpClient(new HttpClientHandler() { AllowAutoRedirect = false }, true);
var res = await Task.WhenAll(images.Select(i => NullIfEmptyImage(i, httpClient))); var sanitizer = new RemoteImageUrlSanitizer(httpClient);
var res = await Task.WhenAll(images.Select(async i => {
var sanitizedUrl = await sanitizer.SanitizeRemoteImageUrl(i.Url);
if (string.IsNullOrEmpty(sanitizedUrl))
return null;
return res.Where(i => i != null); i.Url = sanitizedUrl;
} return i;
}));
protected async Task<RemoteImageInfo> NullIfEmptyImage(RemoteImageInfo info, HttpClient httpClient) return res.Where(i => i != null).ToArray();
{
if (info == null)
return null;
var currentUrl = info.Url;
while (!currentUrl.Contains("no-poster"))
{
var response = await httpClient.SendAsync(
new HttpRequestMessage(HttpMethod.Get, currentUrl), HttpCompletionOption.ResponseHeadersRead);
if ((int)response.StatusCode <= 299)
return info;
else if (response.Headers.Location != null)
{
currentUrl = response.Headers.Location.ToString();
continue;
}
else
throw new InvalidOperationException("Not expected answer");
}
return null;
} }
} }
} }
@@ -3,6 +3,7 @@ using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Jellyfin.Plugin.Kinopoisk.ProviderIdResolvers;
using KinopoiskUnofficialInfo.ApiClient; using KinopoiskUnofficialInfo.ApiClient;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Entities; using MediaBrowser.Model.Entities;
@@ -14,23 +15,26 @@ namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders
public class PersonImageProvider : BaseImageProvider public class PersonImageProvider : BaseImageProvider
{ {
private readonly IKinopoiskApiClient _apiClient; private readonly IKinopoiskApiClient _apiClient;
private readonly IProviderIdResolver<BaseItem> _providerIdResolver;
private readonly ILogger<PersonImageProvider> _logger; private readonly ILogger<PersonImageProvider> _logger;
public PersonImageProvider(IKinopoiskApiClient kinopoiskApiClient, ILogger<PersonImageProvider> logger, IHttpClientFactory httpClientFactory) public PersonImageProvider(IKinopoiskApiClient kinopoiskApiClient, IProviderIdResolver<BaseItem> providerIdResolver, ILogger<PersonImageProvider> logger, IHttpClientFactory httpClientFactory)
: base(httpClientFactory) : base(httpClientFactory)
{ {
_apiClient = kinopoiskApiClient ?? throw new System.ArgumentNullException(nameof(kinopoiskApiClient)); _apiClient = kinopoiskApiClient ?? throw new System.ArgumentNullException(nameof(kinopoiskApiClient));
_providerIdResolver = providerIdResolver ?? throw new System.ArgumentNullException(nameof(providerIdResolver));
_logger = logger ?? throw new System.ArgumentNullException(nameof(logger)); _logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
} }
public override string Name => Utils.ProviderName; public override string Name => Constants.ProviderName;
public override bool Supports(BaseItem item) public override bool Supports(BaseItem item)
=> item is Person; => item is Person;
public override async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken) public override async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
{ {
if (!Utils.TryGetKinopoiskId(item, _logger, out var kinopoiskId)) var (resolveResult, kinopoiskId) = await _providerIdResolver.TryResolve(item, cancellationToken);
if (!resolveResult)
return Enumerable.Empty<RemoteImageInfo>(); return Enumerable.Empty<RemoteImageInfo>();
var person = await _apiClient.GetPerson(kinopoiskId, cancellationToken); var person = await _apiClient.GetPerson(kinopoiskId, cancellationToken);
@@ -4,6 +4,7 @@ using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Jellyfin.Plugin.Kinopoisk.ProviderIdResolvers;
using KinopoiskUnofficialInfo.ApiClient; using KinopoiskUnofficialInfo.ApiClient;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Entities.Movies;
@@ -18,14 +19,16 @@ namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders
{ {
private readonly ILogger<VideoImageProvider> _logger; private readonly ILogger<VideoImageProvider> _logger;
private readonly IKinopoiskApiClient _apiClient; private readonly IKinopoiskApiClient _apiClient;
private readonly IProviderIdResolver<BaseItem> _providerIdResolver;
public override string Name => Utils.ProviderName; public override string Name => Constants.ProviderName;
public VideoImageProvider(IKinopoiskApiClient kinopoiskApiClient, ILogger<VideoImageProvider> logger, IHttpClientFactory httpClientFactory) public VideoImageProvider(IKinopoiskApiClient kinopoiskApiClient, IProviderIdResolver<BaseItem> providerIdResolver, ILogger<VideoImageProvider> logger, IHttpClientFactory httpClientFactory)
: base(httpClientFactory) : base(httpClientFactory)
{ {
this._logger = logger ?? throw new ArgumentNullException(nameof(logger)); _logger = logger ?? throw new ArgumentNullException(nameof(logger));
this._apiClient = kinopoiskApiClient ?? throw new ArgumentNullException(nameof(kinopoiskApiClient)); _apiClient = kinopoiskApiClient ?? throw new ArgumentNullException(nameof(kinopoiskApiClient));
_providerIdResolver = providerIdResolver ?? throw new ArgumentNullException(nameof(providerIdResolver));
} }
public override bool Supports(BaseItem item) public override bool Supports(BaseItem item)
@@ -40,7 +43,8 @@ namespace Jellyfin.Plugin.Kinopoisk.MetadataProviders
public override async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken) public override async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
{ {
if (!Utils.TryGetKinopoiskId(item, _logger, out var kinopoiskId)) var (resolveResult, kinopoiskId) = await _providerIdResolver.TryResolve(item, cancellationToken);
if (!resolveResult)
return Enumerable.Empty<RemoteImageInfo>(); return Enumerable.Empty<RemoteImageInfo>();
var film = await _apiClient.GetSingleFilm(kinopoiskId, cancellationToken); var film = await _apiClient.GetSingleFilm(kinopoiskId, cancellationToken);
@@ -0,0 +1,41 @@
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace Jellyfin.Plugin.Kinopoisk
{
public class RemoteImageUrlSanitizer
{
private readonly HttpClient _httpClient;
public RemoteImageUrlSanitizer(HttpClient httpClient)
{
_httpClient = httpClient ?? throw new System.ArgumentNullException(nameof(httpClient));
}
public async Task<string> SanitizeRemoteImageUrl(string url)
{
if (string.IsNullOrEmpty(url))
return null;
var currentUrl = url;
while (!currentUrl.Contains("no-poster"))
{
var response = await _httpClient.SendAsync(
new HttpRequestMessage(HttpMethod.Get, currentUrl), HttpCompletionOption.ResponseHeadersRead);
if ((int)response.StatusCode <= 299)
return currentUrl;
else if (response.Headers.Location != null)
{
currentUrl = response.Headers.Location.ToString();
continue;
}
else
throw new InvalidOperationException($"Unexpected answer HTTP {response.StatusCode}");
}
return null;
}
}
}
-35
View File
@@ -1,35 +0,0 @@
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 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.LogWarning($"Can't parse Kinopoisk ProviderId to int, skipping ({kinopoiskIdStr})");
result = 0;
return false;
}
return true;
}
}
}
+11 -4
View File
@@ -2,17 +2,24 @@
name: "КиноПоиск" name: "КиноПоиск"
guid: "0c136f8a-ff77-4f2b-ade5-13462cae6216" guid: "0c136f8a-ff77-4f2b-ade5-13462cae6216"
imageUrl: "https://kinopoisk.userecho.com/s/attachments/28876/0/1/25f8c0315e6ccb2aa6c2642e48f2c9e9.png" imageUrl: "https://kinopoisk.userecho.com/s/attachments/28876/0/1/25f8c0315e6ccb2aa6c2642e48f2c9e9.png"
version: "10.7.0.5" version: "10.7.5.0"
targetAbi: "10.7.0" targetAbi: "10.7.0"
framework: "net5.0" framework: "net5.0"
owner: "linfor" owner: "linfor"
overview: "Загружает рейтинги сайта КиноПоиск" overview: "Информация о фильмах и сериалах с КиноПоиска"
description: > description: >
Загружает рейтинги сайта КиноПоиск Загружает рейтинг, описания, актёров, трейлеры и т.д. с сайта КиноПоиск.
Может потребоваться зарегистрировать свой ApiToken, см. информацию в параметрах плагина.
Для точного распознавания рекомендуется указывать id фильма с сайта КиноПоиск в имени файла в формате kp-12345 или kp12345.
Подробнее см. https://github.com/LinFor/jellyfin-plugin-kinopoisk/blob/master/README.md
category: "Metadata" category: "Metadata"
artifacts: artifacts:
- "Jellyfin.Plugin.Kinopoisk.dll" - "Jellyfin.Plugin.Kinopoisk.dll"
- "KinopoiskUnofficialInfo.ApiClient.dll" - "KinopoiskUnofficialInfo.ApiClient.dll"
- "Newtonsoft.Json.dll" - "Newtonsoft.Json.dll"
changelog: > changelog: >
Added trailers filtering: jellyfin-web can only play youtube trailers, not kinopoisk-hosted Short: Huge improvement in auto-identifying of movies.
Rus: Значительно улучшено авто-привязка фильмов при добавлении в медиатеку.
Пытаюсь найти идентификатор кинопоиска по паттерну kp-12345 или kp12345 в имени файла/папки.
Пытаюсь найти единственное совпадение на кинопоиске по имени + году.
Пытаюсь перебрать все совпадения по имени + сравнение IMDB ID.
@@ -38,6 +38,7 @@ namespace KinopoiskUnofficialInfo.ApiClient.Tests
[InlineData(1142206, "Пальма", null)] [InlineData(1142206, "Пальма", null)]
[InlineData(1044982, "Шпион, который меня кинул", "The Spy Who Dumped Me")] [InlineData(1044982, "Шпион, который меня кинул", "The Spy Who Dumped Me")]
[InlineData(1445243, "Будь моим Кириллом", null)] [InlineData(1445243, "Будь моим Кириллом", null)]
[InlineData(251733, "Аватар", "Avatar")]
public async Task GetSingleFilm_ShouldParseFilm(int filmId, string nameRu, string nameEn) public async Task GetSingleFilm_ShouldParseFilm(int filmId, string nameRu, string nameEn)
{ {
using (_vcr.UseCassette($"{GetMethodName()}_{filmId}", RecordMode.NewEpisodes)) using (_vcr.UseCassette($"{GetMethodName()}_{filmId}", RecordMode.NewEpisodes))
@@ -116,5 +117,20 @@ namespace KinopoiskUnofficialInfo.ApiClient.Tests
Assert.Contains(res.Trailers, t => name.Equals(t.Name)); Assert.Contains(res.Trailers, t => name.Equals(t.Name));
} }
} }
[Theory]
[InlineData(948870)]
public async Task GetTrailers_ShouldReturnEmptyResponse(int filmId)
{
using (_vcr.UseCassette($"{GetMethodName()}_{filmId}", RecordMode.NewEpisodes))
{
var apiClient = new KinopoiskApiClient(ApiToken, _loggerFactory.CreateLogger<KinopoiskApiClient>(), _clientFactoryMock.Object);
var res = await apiClient.GetTrailers(filmId);
Assert.NotNull(res);
Assert.Empty(res.Trailers);
}
}
} }
} }
@@ -0,0 +1,47 @@
version: VCR.net 1.0.0
httpInteractions:
- request:
uri: https://kinopoiskapiunofficial.tech/api/v2.1/films/251733?append_to_response=BUDGET&append_to_response=REVIEW&append_to_response=RATING&append_to_response=POSTERS
method: GET
headers:
Accept:
- application/json
X-API-KEY:
- 85d30ae5-d875-4c5f-900d-8e37bb20625e
response:
status:
code: 200
message: ''
headers:
Server:
- nginx/1.18.0
- (Ubuntu)
Date:
- Sun, 23 May 2021 13:05:25 GMT
Transfer-Encoding:
- chunked
Connection:
- keep-alive
Vary:
- Origin
- Access-Control-Request-Method
- Access-Control-Request-Headers
X-Content-Type-Options:
- nosniff
X-XSS-Protection:
- 1; mode=block
Cache-Control:
- no-store, must-revalidate, no-cache, max-age=0
Pragma:
- no-cache
X-Frame-Options:
- DENY
Content-Type:
- application/json
Expires:
- 0
body:
encoding: ''
string: |-
{"data":{"filmId":251733,"nameRu":"Аватар","nameEn":"Avatar","webUrl":"http://www.kinopoisk.ru/film/251733/","posterUrl":"https://kinopoiskapiunofficial.tech/images/posters/kp/251733.jpg","posterUrlPreview":"https://kinopoiskapiunofficial.tech/images/posters/kp_small/251733.jpg","year":"2009","filmLength":"2:42","slogan":"Это новый мир","description":"Бывший морпех Джейк Салли прикован к инвалидному креслу. Несмотря на немощное тело, Джейк в душе по-прежнему остается воином. Он получает задание совершить путешествие в несколько световых лет к базе землян на планете Пандора, где корпорации добывают редкий минерал, имеющий огромное значение для выхода Земли из энергетического кризиса.","type":"FILM","ratingMpaa":"PG-13","ratingAgeLimits":12,"premiereRu":"2009-12-17","distributors":"Двадцатый Век Фокс СНГ","premiereWorld":"2009-12-10","premiereDigital":null,"premiereWorldCountry":"Великобритания","premiereDvd":"2010-04-22","premiereBluRay":"2010-04-29","distributorRelease":"Двадцатый Век Фокс СНГ","countries":[{"country":"США"}],"genres":[{"genre":"боевик"},{"genre":"драма"},{"genre":"фантастика"}],"facts":["Ещё до выпуска фильма, в эпизоде «Танцы с гномами» мультсериала «Южный парк», появилась сатира на историю создания и сюжет фильма.","События картины разворачиваются на Пандоре, спутнике со средой, похожей на земную, вращающемся по орбите планеты-гиганта Полифемуса в системе Альфа Центавра-А.","Майкл Бин претендовал на одну из ролей в фильме. Он несколько раз встречался с Джеймсом Кэмероном. Однако Джеймс не хотел, чтобы фильм ассоциировался у зрителей с «Чужими» (1986), т.к. Сигурни Уивер уже подписала контракт на съёмки.","Для фильма Кэмерон разработал специальную технологию, которая позволяла во время съёмок видеть на экране мониторов компьютерных персонажей вместе с живыми актерами.","Первая фраза «Аватара», которую слышали все земляне после прибытия на Пандору, — «Вы больше не в Канзасе!» — происходит от английской идиомы not in Kansas anymore — «больше не в привычной обстановке, не дома». Это выражение появилось в 1939 году, после выхода на экраны фильма «Волшебник страны Оз» (1939), когда Дороти, очутившись в стране Оз, произносит: «Toto, I’ve a feeling we’re not in Kansas anymore» («Тотошка, я чувствую, что мы больше не в Канзасе»).","Реальные декорации включают в себя Комнату связи, где установлены подобия саркофагов, при помощи которых сознание человека переносится в тело аватара, Биолабораторию – помещение для работы ученых и место хранения резервуаров с амниотической жидкостью, в которых находятся тела аватаров, достигшие состояния зрелости за время шестилетнего путешествия с Земли на Пандору; Центр управления, представляющий собой центральную нервную систему базы «Врата Ада», и военный бастион Armor Bay, где хранятся костюмы усиленной подвижности и вертолеты.","Джоди Фостер расcматривалась для роли доктора Грейс Августин.","Сэм Уортингтон был приглашен на кастинг по телефону. Тот кто звонил, не сказал ему ни одного слова о сюжете и даже не раскрыл имени режиссера. Сэм был разочарован, так как думал что это очеLine truncated
httpVersion: 1.1
@@ -0,0 +1,47 @@
version: VCR.net 1.0.0
httpInteractions:
- request:
uri: https://kinopoiskapiunofficial.tech/api/v2.1/films/948870/videos
method: GET
headers:
Accept:
- application/json
X-API-KEY:
- 85d30ae5-d875-4c5f-900d-8e37bb20625e
response:
status:
code: 404
message: ''
headers:
Server:
- nginx/1.18.0
- (Ubuntu)
Date:
- Sun, 23 May 2021 15:14:51 GMT
Transfer-Encoding:
- chunked
Connection:
- keep-alive
Vary:
- Origin
- Access-Control-Request-Method
- Access-Control-Request-Headers
X-Content-Type-Options:
- nosniff
X-XSS-Protection:
- 1; mode=block
Cache-Control:
- no-store, must-revalidate, no-cache, max-age=0
Pragma:
- no-cache
X-Frame-Options:
- DENY
Content-Type:
- application/json
Expires:
- 0
body:
encoding: ''
string: |-
{"trailers":[],"teasers":[]}
httpVersion: 1.1
@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
namespace KinopoiskUnofficialInfo.ApiClient
{
public class CachedKinopoiskApiClient : IKinopoiskApiClient
{
private readonly IKinopoiskApiClient _innerClient;
private readonly IMemoryCache _cache;
private readonly ILogger<CachedKinopoiskApiClient> _logger;
public CachedKinopoiskApiClient(IKinopoiskApiClient innerClient, IMemoryCache cache, ILogger<CachedKinopoiskApiClient> logger)
{
_innerClient = innerClient ?? throw new ArgumentNullException(nameof(innerClient));
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public CachedKinopoiskApiClient(string apiToken, ILogger<KinopoiskApiClient> innerLogger, IHttpClientFactory httpClientFactory, IMemoryCache cache, ILogger<CachedKinopoiskApiClient> logger)
: this(new KinopoiskApiClient(apiToken, innerLogger, httpClientFactory), cache, logger)
{
}
public Task<PersonResponse> GetPerson(int personId, CancellationToken? cancellationToken = null)
=> TryGetValue(GenerateKey(nameof(GetPerson), personId), c => c.GetPerson(personId, cancellationToken));
public Task<Film> GetSingleFilm(int filmId, CancellationToken? cancellationToken = null)
=> TryGetValue(GenerateKey(nameof(GetSingleFilm), filmId), c => c.GetSingleFilm(filmId, cancellationToken));
public Task<ICollection<StaffResponse>> GetStaff(int filmId, CancellationToken? cancellationToken = null)
=> TryGetValue(GenerateKey(nameof(GetStaff), filmId), c => c.GetStaff(filmId, cancellationToken));
public Task<VideoResponse> GetTrailers(int filmId, CancellationToken? cancellationToken = null)
=> TryGetValue(GenerateKey(nameof(GetTrailers), filmId), c => c.GetTrailers(filmId, cancellationToken));
public Task<FilmSearchResponse> SearchByKeyword(string keyword, int page = 1, CancellationToken? cancellationToken = null)
=> TryGetValue(GenerateKey(nameof(SearchByKeyword), keyword, page), c => c.SearchByKeyword(keyword, page, cancellationToken));
private static string GenerateKey(params object[] objects)
{
var key = string.Empty;
foreach (var obj in objects)
{
var objType = obj.GetType();
if (objType.IsPrimitive || objType == typeof(string))
{
key += obj + ";";
}
else
{
foreach (PropertyInfo propertyInfo in objType.GetProperties())
{
var currentValue = propertyInfo.GetValue(obj, null);
if (currentValue == null)
{
continue;
}
key += propertyInfo.Name + "=" + currentValue + ";";
}
}
}
return key;
}
private Task<T> TryGetValue<T>(string key, Func<IKinopoiskApiClient, Task<T>> resultFactory)
{
return _cache.GetOrCreateAsync(key, async entry =>
{
_logger.LogDebug($"Entry '{key}' not found in cache, requesting from server");
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1);
var result = await resultFactory.Invoke(_innerClient).ConfigureAwait(false);
return result;
});
}
}
}
@@ -60,6 +60,17 @@ namespace KinopoiskUnofficialInfo.ApiClient
=> Invoke((ct) => _apiClient.StaffAsync(personId, ct), cancellationToken); => Invoke((ct) => _apiClient.StaffAsync(personId, ct), cancellationToken);
public Task<VideoResponse> GetTrailers(int filmId, CancellationToken? cancellationToken = null) public Task<VideoResponse> GetTrailers(int filmId, CancellationToken? cancellationToken = null)
=> Invoke((ct) => _apiClient.VideosAsync(filmId, ct), cancellationToken); {
return Invoke(async (ct) => {
try {
return await _apiClient.VideosAsync(filmId, ct);
} catch (ApiException e)
{
if (e.StatusCode == 404)
return new VideoResponse();
throw;
}
}, cancellationToken);
}
} }
} }
@@ -5,6 +5,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging" Version="5.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
@@ -1,3 +1,4 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Newtonsoft.Json; using Newtonsoft.Json;
@@ -22,7 +23,7 @@ namespace KinopoiskUnofficialInfo.ApiClient
#pragma warning disable CS0618 #pragma warning disable CS0618
property.MemberConverter = null; property.MemberConverter = null;
#pragma warning restore CS0618 #pragma warning restore CS0618
property.Converter = new JsonProfessionKeyConverter(); property.Converter = new ProfessionKeyConverter();
} }
if (type == typeof(VideoResponse_trailers)) if (type == typeof(VideoResponse_trailers))
@@ -33,6 +34,17 @@ namespace KinopoiskUnofficialInfo.ApiClient
property.DefaultValue = -1; property.DefaultValue = -1;
} }
} }
if (type == typeof(Budget))
{
if (property.PropertyType == typeof(Int32))
{
#pragma warning disable CS0618
property.MemberConverter = null;
#pragma warning restore CS0618
property.Converter = new IntegerOverflowConverter();
}
}
} }
return list; return list;
} }
@@ -0,0 +1,26 @@
using System;
using Newtonsoft.Json;
namespace KinopoiskUnofficialInfo.ApiClient
{
public class IntegerOverflowConverter : JsonConverter
{
public override bool CanRead => true;
public override bool CanWrite => false;
public override bool CanConvert(System.Type objectType)
=> objectType == typeof(Int32);
public override object ReadJson(JsonReader reader, System.Type objectType, object existingValue, JsonSerializer serializer)
{
if (int.TryParse(Convert.ToString(reader.Value), out var result))
return result;
return -1;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}
@@ -4,7 +4,7 @@ using Newtonsoft.Json.Converters;
namespace KinopoiskUnofficialInfo.ApiClient namespace KinopoiskUnofficialInfo.ApiClient
{ {
public class JsonProfessionKeyConverter : StringEnumConverter public class ProfessionKeyConverter : StringEnumConverter
{ {
public override object ReadJson(JsonReader reader, System.Type objectType, object existingValue, JsonSerializer serializer) public override object ReadJson(JsonReader reader, System.Type objectType, object existingValue, JsonSerializer serializer)
{ {