105 lines
2.8 KiB
C#
105 lines
2.8 KiB
C#
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Net;
|
||
using System.Text.RegularExpressions;
|
||
using System.Threading.Tasks;
|
||
using Godot;
|
||
using Learn.Config;
|
||
using Learn.Models;
|
||
using Learn.Utils;
|
||
using TMDbLib.Client;
|
||
using TMDbLib.Objects.Search;
|
||
|
||
namespace Learn.Parsers;
|
||
|
||
public class TMDBParser(Configs configs) : ItemParser
|
||
{
|
||
private TMDBParserConfig config => configs.Get<TMDBParserConfig>();
|
||
|
||
private readonly Dictionary<string, SearchTv> _cache = new();
|
||
|
||
private TMDbClient _client;
|
||
|
||
private async Task<SearchTv> QueryTMDB(string title, int year)
|
||
{
|
||
if (string.IsNullOrEmpty(title)) return null;
|
||
|
||
if (_cache.TryGetValue(title, out var result))
|
||
{
|
||
return result;
|
||
}
|
||
|
||
var results = (await GetTMDbClient().SearchTvShowAsync(title, language: "zh-CN", firstAirDateYear:year)).Results;
|
||
result = results.FirstOrDefault();
|
||
_cache[title] = result;
|
||
return result;
|
||
}
|
||
|
||
private TMDbClient GetTMDbClient()
|
||
{
|
||
if (_client != null) return _client;
|
||
|
||
var apiKey = config.ApiKey;
|
||
var proxy = config.HttpProxy;
|
||
|
||
if (string.IsNullOrEmpty(proxy))
|
||
{
|
||
_client = new TMDbClient(apiKey);
|
||
}
|
||
else
|
||
{
|
||
_client = new TMDbClient(apiKey , proxy: new WebProxy(proxy));
|
||
}
|
||
|
||
return _client;
|
||
}
|
||
|
||
|
||
|
||
public async Task Parse(TreeNode node)
|
||
{
|
||
if (node.TryGetValue(ItemFields.Key_Title, out _, out _)) return;
|
||
|
||
if (!node.TryGetValue(ItemFields.Key_RawTitle, out var rawTitle, out _))
|
||
{
|
||
return;
|
||
}
|
||
|
||
if (string.IsNullOrEmpty(rawTitle))
|
||
{
|
||
return ;
|
||
}
|
||
|
||
int year = 0;
|
||
if (node.TryGetValue(ItemFields.Key_Year, out var yearStr, out _))
|
||
{
|
||
if (int.TryParse(yearStr, out var yearValue))
|
||
{
|
||
year = yearValue;
|
||
}
|
||
}
|
||
|
||
var result = await QueryTMDB(rawTitle, year);
|
||
if (result == null)
|
||
{
|
||
GD.PrintErr($"找不到对应的TV:{rawTitle}");
|
||
return;
|
||
}
|
||
|
||
var showInfo = await _client.GetTvShowAsync(result.Id, language: "zh-CN");
|
||
|
||
if (result.FirstAirDate != null)
|
||
{
|
||
node.Info.Info[ItemFields.Key_Year] = showInfo.FirstAirDate.Value.Year.ToString();
|
||
}
|
||
|
||
node.Info.Info[ItemFields.Key_Title] = showInfo.Name;
|
||
node.Info.Info[ItemFields.Key_TMDBID] = showInfo.Id.ToString();
|
||
node.Info.Info["SeasonInfo"] = string.Join(", ", showInfo.Seasons.Select(season => season.Name));
|
||
|
||
if (showInfo.Seasons.Count == 1)
|
||
{
|
||
node.Info.Info.TryAdd(ItemFields.Key_Season, "1");
|
||
}
|
||
}
|
||
} |