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(); private readonly Dictionary _cache = new(); private TMDbClient _client; private async Task 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; } if (result.FirstAirDate != null) { node.Info.Info[ItemFields.Key_Year] = result.FirstAirDate.Value.Year.ToString(); } node.Info.Info[ItemFields.Key_Title] = result.Name; node.Info.Info[ItemFields.Key_TMDBID] = result.Id.ToString(); } }