From 86e77561e457318907b17735213d45f42d398ddb Mon Sep 17 00:00:00 2001 From: Felix Date: Sat, 18 Oct 2025 08:51:35 +0300 Subject: [PATCH] Add Voice logic --- Uaflix/Controller.cs | 257 +++++++++- Uaflix/ModInit.cs | 6 +- Uaflix/Models/EpisodeLinkInfo.cs | 4 + Uaflix/Models/SerialAggregatedStructure.cs | 31 ++ Uaflix/Models/VoiceInfo.cs | 71 +++ Uaflix/UaflixInvoke.cs | 520 +++++++++++++++++++-- 6 files changed, 834 insertions(+), 55 deletions(-) create mode 100644 Uaflix/Models/SerialAggregatedStructure.cs create mode 100644 Uaflix/Models/VoiceInfo.cs diff --git a/Uaflix/Controller.cs b/Uaflix/Controller.cs index 266398a..7b55763 100644 --- a/Uaflix/Controller.cs +++ b/Uaflix/Controller.cs @@ -28,20 +28,65 @@ namespace Uaflix.Controllers [HttpGet] [Route("uaflix")] - async public Task Index(long id, string imdb_id, long kinopoisk_id, string title, string original_title, string original_language, int year, string source, int serial, string account_email, string t, int s = -1, int e = -1, bool play = false, bool rjson = false, string href = null) + async public Task Index(long id, string imdb_id, long kinopoisk_id, string title, string original_title, string original_language, int year, string source, int serial, string account_email, string t, int s = -1, int e = -1, bool play = false, bool rjson = false, string href = null, bool checksearch = false) { var init = await loadKit(ModInit.UaFlix); if (await IsBadInitialization(init)) return Forbid(); + OnLog($"=== UAFLIX INDEX START ==="); + OnLog($"Uaflix Index: title={title}, serial={serial}, s={s}, play={play}, href={href}, checksearch={checksearch}"); + OnLog($"Uaflix Index: kinopoisk_id={kinopoisk_id}, imdb_id={imdb_id}, id={id}"); + OnLog($"Uaflix Index: year={year}, source={source}, t={t}, e={e}, rjson={rjson}"); + var invoke = new UaflixInvoke(init, hybridCache, OnLog, proxyManager); + // Обробка параметра checksearch - повертаємо спеціальну відповідь для валідації + if (checksearch) + { + try + { + string filmTitle = !string.IsNullOrEmpty(title) ? title : original_title; + string searchUrl = $"{init.host}/index.php?do=search&subaction=search&story={System.Web.HttpUtility.UrlEncode(filmTitle)}"; + var headers = new List() { new HeadersModel("User-Agent", "Mozilla/5.0"), new HeadersModel("Referer", init.host) }; + + var searchHtml = await Http.Get(searchUrl, headers: headers, proxy: proxyManager.Get(), timeoutSeconds: 10); + + // Швидка перевірка наявності результатів без повного парсингу + if (!string.IsNullOrEmpty(searchHtml) && + (searchHtml.Contains("sres-wrap") || searchHtml.Contains("sres-item") || searchHtml.Contains("search-results"))) + { + // Якщо знайдено контент, повертаємо "data-json=" для валідації + OnLog("checksearch: Content found, returning validation response"); + OnLog("=== RETURN: checksearch validation (data-json=) ==="); + return Content("data-json=", "text/plain; charset=utf-8"); + } + else + { + // Якщо нічого не знайдено, повертаємо OnError + OnLog("checksearch: No content found"); + OnLog("=== RETURN: checksearch OnError ==="); + return OnError("uaflix", proxyManager); + } + } + catch (Exception ex) + { + OnLog($"checksearch error: {ex.Message}"); + OnLog("=== RETURN: checksearch exception OnError ==="); + return OnError("uaflix", proxyManager); + } + } + if (play) { var playResult = await invoke.ParseEpisode(t); if (playResult.streams != null && playResult.streams.Count > 0) + { + OnLog("=== RETURN: play redirect ==="); return Redirect(HostStreamProxy(init, accsArgs(playResult.streams.First().link))); - + } + + OnLog("=== RETURN: play no streams ==="); return Content("Uaflix", "text/html; charset=utf-8"); } @@ -51,9 +96,15 @@ namespace Uaflix.Controllers { var searchResults = await invoke.Search(imdb_id, kinopoisk_id, title, original_title, year, title); if (searchResults == null || searchResults.Count == 0) - return Content("Uaflix", "text/html; charset=utf-8"); - - if (searchResults.Count > 1) + { + OnLog("No search results found"); + OnLog("=== RETURN: no search results OnError ==="); + return OnError("uaflix", proxyManager); + } + + // Для серіалів завжди вибираємо перший результат автоматично + // Для фільмів показуємо вибір тільки якщо більше одного результату + if (serial == 0 && searchResults.Count > 1) { var similar_tpl = new SimilarTpl(searchResults.Count); foreach (var res in searchResults) @@ -61,49 +112,207 @@ namespace Uaflix.Controllers string link = $"{host}/uaflix?imdb_id={imdb_id}&kinopoisk_id={kinopoisk_id}&title={HttpUtility.UrlEncode(title)}&original_title={HttpUtility.UrlEncode(original_title)}&year={year}&serial={serial}&href={HttpUtility.UrlEncode(res.Url)}"; similar_tpl.Append(res.Title, res.Year.ToString(), string.Empty, link, res.PosterUrl); } + OnLog($"=== RETURN: similar movies ({searchResults.Count}) ==="); return rjson ? Content(similar_tpl.ToJson(), "application/json; charset=utf-8") : Content(similar_tpl.ToHtml(), "text/html; charset=utf-8"); } filmUrl = searchResults[0].Url; + OnLog($"Auto-selected first search result: {filmUrl}"); } if (serial == 1) { - var paginationInfo = await invoke.GetPaginationInfo(filmUrl); - if (paginationInfo == null || paginationInfo.Episodes == null) - return Content("Uaflix", "text/html; charset=utf-8"); - - if (s == -1) // Выбор сезона + // Агрегуємо всі озвучки з усіх плеєрів + var structure = await invoke.AggregateSerialStructure(filmUrl); + if (structure == null || !structure.Voices.Any()) { - var seasons = paginationInfo.Episodes.Select(se => se.season).Distinct().OrderBy(se => se); - var season_tpl = new SeasonTpl(seasons.Count()); - - foreach (var season in seasons) + OnLog("No voices found in aggregated structure"); + OnLog("=== RETURN: no voices OnError ==="); + return OnError("uaflix", proxyManager); + } + + OnLog($"Structure aggregated successfully: {structure.Voices.Count} voices, URL: {filmUrl}"); + foreach (var voice in structure.Voices) + { + OnLog($"Voice: {voice.Key}, Type: {voice.Value.PlayerType}, Seasons: {voice.Value.Seasons.Count}"); + foreach (var season in voice.Value.Seasons) + { + OnLog($" Season {season.Key}: {season.Value.Count} episodes"); + } + } + + // s == -1: Вибір сезону + if (s == -1) + { + var allSeasons = structure.Voices + .SelectMany(v => v.Value.Seasons.Keys) + .Distinct() + .OrderBy(sn => sn) + .ToList(); + + OnLog($"Found {allSeasons.Count} seasons in structure: {string.Join(", ", allSeasons)}"); + + // Перевіряємо чи сезони містять валідні епізоди з файлами + var seasonsWithValidEpisodes = allSeasons.Where(season => + structure.Voices.Values.Any(v => + v.Seasons.ContainsKey(season) && + v.Seasons[season].Any(ep => !string.IsNullOrEmpty(ep.File)) + ) + ).ToList(); + + OnLog($"Seasons with valid episodes: {seasonsWithValidEpisodes.Count}"); + foreach (var season in allSeasons) + { + var episodesInSeason = structure.Voices.Values + .Where(v => v.Seasons.ContainsKey(season)) + .SelectMany(v => v.Seasons[season]) + .Where(ep => !string.IsNullOrEmpty(ep.File)) + .ToList(); + OnLog($"Season {season}: {episodesInSeason.Count} valid episodes"); + } + + if (!seasonsWithValidEpisodes.Any()) + { + OnLog("No seasons with valid episodes found in structure"); + OnLog("=== RETURN: no valid seasons OnError ==="); + return OnError("uaflix", proxyManager); + } + + var season_tpl = new SeasonTpl(seasonsWithValidEpisodes.Count); + foreach (var season in seasonsWithValidEpisodes) { string link = $"{host}/uaflix?imdb_id={imdb_id}&kinopoisk_id={kinopoisk_id}&title={HttpUtility.UrlEncode(title)}&original_title={HttpUtility.UrlEncode(original_title)}&year={year}&serial=1&s={season}&href={HttpUtility.UrlEncode(filmUrl)}"; - season_tpl.Append($"Сезон {season}", link, $"{season}"); + season_tpl.Append($"Сезон {season}", link, season.ToString()); + OnLog($"Added season {season} to template"); } - return rjson ? Content(season_tpl.ToJson(), "application/json; charset=utf-8") : Content(season_tpl.ToHtml(), "text/html; charset=utf-8"); + + OnLog($"Returning season template with {seasonsWithValidEpisodes.Count} seasons"); + + var htmlContent = rjson ? season_tpl.ToJson() : season_tpl.ToHtml(); + OnLog($"Season template response length: {htmlContent.Length}"); + OnLog($"Season template HTML (first 300): {htmlContent.Substring(0, Math.Min(300, htmlContent.Length))}"); + OnLog($"=== RETURN: season template ({seasonsWithValidEpisodes.Count} seasons) ==="); + + return Content(htmlContent, rjson ? "application/json; charset=utf-8" : "text/html; charset=utf-8"); } - else // Выбор эпизода + // s >= 0: Показуємо озвучки + епізоди + else if (s >= 0) { - var episodes = paginationInfo.Episodes.Where(ep => ep.season == s).OrderBy(ep => ep.episode).ToList(); - var episode_tpl = new EpisodeTpl(); - foreach(var ep in episodes) + var voicesForSeason = structure.Voices + .Where(v => v.Value.Seasons.ContainsKey(s)) + .Select(v => new { DisplayName = v.Key, Info = v.Value }) + .ToList(); + + if (!voicesForSeason.Any()) { - string link = $"{host}/uaflix?t={HttpUtility.UrlEncode(ep.url)}&play=true"; - episode_tpl.Append(ep.title, title, ep.season.ToString(), ep.episode.ToString(), accsArgs(link)); + OnLog($"No voices found for season {s}"); + OnLog("=== RETURN: no voices for season OnError ==="); + return OnError("uaflix", proxyManager); + } + + // Автоматично вибираємо першу озвучку якщо не вказана + if (string.IsNullOrEmpty(t)) + { + t = voicesForSeason[0].DisplayName; + OnLog($"Auto-selected first voice: {t}"); + } + + // Створюємо VoiceTpl з усіма озвучками + var voice_tpl = new VoiceTpl(); + foreach (var voice in voicesForSeason) + { + string voiceLink = $"{host}/uaflix?imdb_id={imdb_id}&kinopoisk_id={kinopoisk_id}&title={HttpUtility.UrlEncode(title)}&original_title={HttpUtility.UrlEncode(original_title)}&year={year}&serial=1&s={s}&t={HttpUtility.UrlEncode(voice.DisplayName)}&href={HttpUtility.UrlEncode(filmUrl)}"; + bool isActive = voice.DisplayName == t; + voice_tpl.Append(voice.DisplayName, isActive, voiceLink); + } + OnLog($"Created VoiceTpl with {voicesForSeason.Count} voices, active: {t}"); + + // Відображення епізодів для вибраної озвучки + if (!structure.Voices.ContainsKey(t)) + { + OnLog($"Voice '{t}' not found in structure"); + OnLog("=== RETURN: voice not found OnError ==="); + return OnError("uaflix", proxyManager); + } + + if (!structure.Voices[t].Seasons.ContainsKey(s)) + { + OnLog($"Season {s} not found for voice '{t}'"); + OnLog("=== RETURN: season not found for voice OnError ==="); + return OnError("uaflix", proxyManager); + } + + var episodes = structure.Voices[t].Seasons[s]; + var episode_tpl = new EpisodeTpl(); + + foreach (var ep in episodes) + { + // Для zetvideo-vod повертаємо URL епізоду з методом call + // Для ashdi/zetvideo-serial повертаємо готове посилання з play + var voice = structure.Voices[t]; + + if (voice.PlayerType == "zetvideo-vod") + { + // Знайти URL епізоду зі структури AllEpisodes + var episodeInfo = structure.AllEpisodes + .FirstOrDefault(e => e.season == s && e.episode == ep.Number); + + if (episodeInfo != null) + { + string callUrl = $"{host}/uaflix?t={HttpUtility.UrlEncode(episodeInfo.url)}&play=true"; + episode_tpl.Append( + name: ep.Title, + title: title, + s: s.ToString(), + e: ep.Number.ToString(), + link: accsArgs(callUrl) + ); + } + } + else + { + // Для багатосерійних плеєрів (ashdi-serial, zetvideo-serial) - пряме відтворення + string playUrl = HostStreamProxy(init, accsArgs(ep.File)); + episode_tpl.Append( + name: ep.Title, + title: title, + s: s.ToString(), + e: ep.Number.ToString(), + link: playUrl + ); + } + } + + OnLog($"Created EpisodeTpl with {episodes.Count} episodes"); + + // Повертаємо VoiceTpl + EpisodeTpl разом + if (rjson) + { + OnLog($"=== RETURN: episode template with voices JSON ({episodes.Count} episodes) ==="); + return Content(episode_tpl.ToJson(voice_tpl), "application/json; charset=utf-8"); + } + else + { + OnLog($"=== RETURN: voice + episode template HTML ({episodes.Count} episodes) ==="); + return Content(voice_tpl.ToHtml() + episode_tpl.ToHtml(), "text/html; charset=utf-8"); } - return rjson ? Content(episode_tpl.ToJson(), "application/json; charset=utf-8") : Content(episode_tpl.ToHtml(), "text/html; charset=utf-8"); } + + // Fallback: якщо жоден з умов не виконався + OnLog($"Fallback: s={s}, t={t}"); + OnLog("=== RETURN: fallback OnError ==="); + return OnError("uaflix", proxyManager); } - else // Фильм + else // Фільм { string link = $"{host}/uaflix?t={HttpUtility.UrlEncode(filmUrl)}&play=true"; var tpl = new MovieTpl(title, original_title, 1); tpl.Append(title, accsArgs(link), method: "play"); + OnLog("=== RETURN: movie template ==="); return rjson ? Content(tpl.ToJson(), "application/json; charset=utf-8") : Content(tpl.ToHtml(), "text/html; charset=utf-8"); } } + } } + diff --git a/Uaflix/ModInit.cs b/Uaflix/ModInit.cs index 9f8c99a..506f76b 100644 --- a/Uaflix/ModInit.cs +++ b/Uaflix/ModInit.cs @@ -29,10 +29,12 @@ namespace Uaflix username = "a", password = "a", list = new string[] { "socks5://IP:PORT" } - } + }, + // Note: OnlinesSettings не має властивості additional, використовуємо інший підхід }; + UaFlix = ModuleInvoke.Conf("Uaflix", UaFlix).ToObject(); - + // Виводити "уточнити пошук" AppInit.conf.online.with_search.Add("uaflix"); } diff --git a/Uaflix/Models/EpisodeLinkInfo.cs b/Uaflix/Models/EpisodeLinkInfo.cs index 4cd5986..9b4adb0 100644 --- a/Uaflix/Models/EpisodeLinkInfo.cs +++ b/Uaflix/Models/EpisodeLinkInfo.cs @@ -8,5 +8,9 @@ namespace Uaflix.Models public string title { get; set; } public int season { get; set; } public int episode { get; set; } + + // Нові поля для підтримки змішаних плеєрів + public string playerType { get; set; } // "ashdi-serial", "zetvideo-serial", "zetvideo-vod" + public string iframeUrl { get; set; } // URL iframe для цього епізоду } } \ No newline at end of file diff --git a/Uaflix/Models/SerialAggregatedStructure.cs b/Uaflix/Models/SerialAggregatedStructure.cs new file mode 100644 index 0000000..ef2d770 --- /dev/null +++ b/Uaflix/Models/SerialAggregatedStructure.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; + +namespace Uaflix.Models +{ + /// + /// Агрегована структура серіалу з озвучками з усіх джерел (ashdi, zetvideo-serial, zetvideo-vod) + /// + public class SerialAggregatedStructure + { + /// + /// URL головної сторінки серіалу + /// + public string SerialUrl { get; set; } + + /// + /// Словник озвучок: ключ - displayName озвучки (наприклад, "[Ashdi] DniproFilm"), значення - VoiceInfo + /// + public Dictionary Voices { get; set; } + + /// + /// Список всіх епізодів серіалу (використовується для zetvideo-vod) + /// + public List AllEpisodes { get; set; } + + public SerialAggregatedStructure() + { + Voices = new Dictionary(); + AllEpisodes = new List(); + } + } +} \ No newline at end of file diff --git a/Uaflix/Models/VoiceInfo.cs b/Uaflix/Models/VoiceInfo.cs new file mode 100644 index 0000000..5a52735 --- /dev/null +++ b/Uaflix/Models/VoiceInfo.cs @@ -0,0 +1,71 @@ +using System.Collections.Generic; + +namespace Uaflix.Models +{ + /// + /// Модель для зберігання інформації про озвучку серіалу + /// + public class VoiceInfo + { + /// + /// Назва озвучки без префіксу (наприклад, "DniproFilm") + /// + public string Name { get; set; } + + /// + /// Тип плеєра: "ashdi-serial", "zetvideo-serial", "zetvideo-vod" + /// + public string PlayerType { get; set; } + + /// + /// Назва для відображення з префіксом плеєра (наприклад, "[Ashdi] DniproFilm") + /// + public string DisplayName { get; set; } + + /// + /// Словник сезонів: ключ - номер сезону, значення - список епізодів + /// + public Dictionary> Seasons { get; set; } + + public VoiceInfo() + { + Seasons = new Dictionary>(); + } + } + + /// + /// Модель для зберігання інформації про окремий епізод + /// + public class EpisodeInfo + { + /// + /// Номер епізоду + /// + public int Number { get; set; } + + /// + /// Назва епізоду + /// + public string Title { get; set; } + + /// + /// Пряме посилання на відео файл (m3u8) + /// + public string File { get; set; } + + /// + /// ID епізоду у плеєрі + /// + public string Id { get; set; } + + /// + /// URL постера епізоду + /// + public string Poster { get; set; } + + /// + /// Субтитри у форматі Playerjs + /// + public string Subtitle { get; set; } + } +} \ No newline at end of file diff --git a/Uaflix/UaflixInvoke.cs b/Uaflix/UaflixInvoke.cs index 011389a..9df46ad 100644 --- a/Uaflix/UaflixInvoke.cs +++ b/Uaflix/UaflixInvoke.cs @@ -12,6 +12,8 @@ using Uaflix.Models; using System.Linq; using Shared.Models.Templates; using System.Net; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; namespace Uaflix { @@ -29,6 +31,409 @@ namespace Uaflix _onLog = onLog; _proxyManager = proxyManager; } + + #region Методи для визначення та парсингу різних типів плеєрів + + /// + /// Визначити тип плеєра з URL iframe + /// + private string DeterminePlayerType(string iframeUrl) + { + if (string.IsNullOrEmpty(iframeUrl)) + return null; + + // Перевіряємо на підтримувані типи плеєрів + if (iframeUrl.Contains("ashdi.vip/serial/")) + return "ashdi-serial"; + else if (iframeUrl.Contains("zetvideo.net/serial/")) + return "zetvideo-serial"; + else if (iframeUrl.Contains("zetvideo.net/vod/")) + return "zetvideo-vod"; + + // Перевіряємо на небажані типи плеєрів (трейлери, реклама тощо) + if (iframeUrl.Contains("youtube.com/embed/") || + iframeUrl.Contains("youtu.be/") || + iframeUrl.Contains("vimeo.com/") || + iframeUrl.Contains("dailymotion.com/")) + return "trailer"; // Ігноруємо відеохостинги з трейлерами + + return null; + } + + /// + /// Парсинг багатосерійного плеєра (ashdi-serial або zetvideo-serial) + /// + private async Task> ParseMultiEpisodePlayer(string iframeUrl, string playerType) + { + string referer = "https://uafix.net/"; + + var headers = new List() + { + new HeadersModel("User-Agent", "Mozilla/5.0"), + new HeadersModel("Referer", referer) + }; + + try + { + // Для ashdi видаляємо параметри season та episode для отримання всіх озвучок + string requestUrl = iframeUrl; + if (playerType == "ashdi-serial" && iframeUrl.Contains("ashdi.vip/serial/")) + { + // Витягуємо базовий URL без параметрів + var baseUrlMatch = Regex.Match(iframeUrl, @"(https://ashdi\.vip/serial/\d+)"); + if (baseUrlMatch.Success) + { + requestUrl = baseUrlMatch.Groups[1].Value; + _onLog($"ParseMultiEpisodePlayer: Using base ashdi URL without parameters: {requestUrl}"); + } + } + + string html = await Http.Get(requestUrl, headers: headers, proxy: _proxyManager.Get()); + + // Знайти JSON у new Playerjs({file:'...'}) + var match = Regex.Match(html, @"file:'(\[.+?\])'", RegexOptions.Singleline); + if (!match.Success) + { + _onLog($"ParseMultiEpisodePlayer: JSON not found in iframe {iframeUrl}"); + return new List(); + } + + string jsonStr = match.Groups[1].Value + .Replace("\\'", "'") + .Replace("\\\"", "\""); + + var voicesArray = JsonConvert.DeserializeObject>(jsonStr); + var voices = new List(); + + string playerPrefix = playerType == "ashdi-serial" ? "Ashdi" : "Zetvideo"; + + foreach (var voiceObj in voicesArray) + { + string voiceName = voiceObj["title"]?.ToString().Trim(); + if (string.IsNullOrEmpty(voiceName)) + continue; + + var voiceInfo = new VoiceInfo + { + Name = voiceName, + PlayerType = playerType, + DisplayName = $"[{playerPrefix}] {voiceName}", + Seasons = new Dictionary>() + }; + + var seasons = voiceObj["folder"] as JArray; + if (seasons != null) + { + foreach (var seasonObj in seasons) + { + string seasonTitle = seasonObj["title"]?.ToString(); + var seasonMatch = Regex.Match(seasonTitle, @"Сезон\s+(\d+)", RegexOptions.IgnoreCase); + + if (!seasonMatch.Success) + continue; + + int seasonNumber = int.Parse(seasonMatch.Groups[1].Value); + var episodes = new List(); + var episodesArray = seasonObj["folder"] as JArray; + + if (episodesArray != null) + { + int episodeNum = 1; + foreach (var epObj in episodesArray) + { + episodes.Add(new EpisodeInfo + { + Number = episodeNum++, + Title = epObj["title"]?.ToString(), + File = epObj["file"]?.ToString(), + Id = epObj["id"]?.ToString(), + Poster = epObj["poster"]?.ToString(), + Subtitle = epObj["subtitle"]?.ToString() + }); + } + } + + voiceInfo.Seasons[seasonNumber] = episodes; + } + } + + voices.Add(voiceInfo); + } + + _onLog($"ParseMultiEpisodePlayer: Found {voices.Count} voices in {playerType}"); + return voices; + } + catch (Exception ex) + { + _onLog($"ParseMultiEpisodePlayer error: {ex.Message}"); + return new List(); + } + } + + /// + /// Парсинг одного епізоду з zetvideo-vod + /// + private async Task<(string file, string voiceName)> ParseSingleEpisodePlayer(string iframeUrl) + { + var headers = new List() + { + new HeadersModel("User-Agent", "Mozilla/5.0"), + new HeadersModel("Referer", "https://uafix.net/") + }; + + try + { + string html = await Http.Get(iframeUrl, headers: headers, proxy: _proxyManager.Get()); + + // Знайти file:"url" + var match = Regex.Match(html, @"file:\s*""([^""]+\.m3u8)"""); + if (!match.Success) + return (null, null); + + string fileUrl = match.Groups[1].Value; + + // Визначити озвучку з URL + string voiceName = ExtractVoiceFromUrl(fileUrl); + + return (fileUrl, voiceName); + } + catch (Exception ex) + { + _onLog($"ParseSingleEpisodePlayer error: {ex.Message}"); + return (null, null); + } + } + + /// + /// Витягнути назву озвучки з URL файлу + /// + private string ExtractVoiceFromUrl(string fileUrl) + { + if (string.IsNullOrEmpty(fileUrl)) + return "Невідомо"; + + if (fileUrl.Contains("uaflix")) + return "Uaflix"; + else if (fileUrl.Contains("dniprofilm")) + return "DniproFilm"; + else if (fileUrl.Contains("newstudio")) + return "NewStudio"; + + return "Невідомо"; + } + + #endregion + + #region Агрегація структури серіалу з усіх джерел + + /// + /// Агрегує озвучки з усіх епізодів серіалу (ashdi, zetvideo-serial, zetvideo-vod) + /// + public async Task AggregateSerialStructure(string serialUrl) + { + string memKey = $"UaFlix:aggregated:{serialUrl}"; + if (_hybridCache.TryGetValue(memKey, out SerialAggregatedStructure cached)) + { + _onLog($"AggregateSerialStructure: Using cached structure for {serialUrl}"); + return cached; + } + + try + { + // Edge Case 1: Перевірка валідності URL + if (string.IsNullOrEmpty(serialUrl) || !Uri.IsWellFormedUriString(serialUrl, UriKind.Absolute)) + { + _onLog($"AggregateSerialStructure: Invalid URL: {serialUrl}"); + return null; + } + + // Отримати список всіх епізодів + var paginationInfo = await GetPaginationInfo(serialUrl); + if (paginationInfo?.Episodes == null || !paginationInfo.Episodes.Any()) + { + _onLog($"AggregateSerialStructure: No episodes found for {serialUrl}"); + return null; + } + + var structure = new SerialAggregatedStructure + { + SerialUrl = serialUrl, + Voices = new Dictionary(), + AllEpisodes = paginationInfo.Episodes + }; + + // Групуємо епізоди по сезонах + var episodesBySeason = paginationInfo.Episodes + .GroupBy(e => e.season) + .ToDictionary(g => g.Key, g => g.ToList()); + + _onLog($"AggregateSerialStructure: Processing {episodesBySeason.Count} seasons"); + + // Для кожного сезону беремо перший епізод та визначаємо тип плеєра + foreach (var seasonGroup in episodesBySeason) + { + int season = seasonGroup.Key; + var firstEpisode = seasonGroup.Value.First(); + + _onLog($"AggregateSerialStructure: Processing season {season}, first episode: {firstEpisode.url}"); + + // Отримати HTML епізоду та знайти iframe + var headers = new List() { + new HeadersModel("User-Agent", "Mozilla/5.0"), + new HeadersModel("Referer", _init.host) + }; + + string html = await Http.Get(firstEpisode.url, headers: headers, proxy: _proxyManager.Get()); + + var doc = new HtmlDocument(); + doc.LoadHtml(html); + var iframe = doc.DocumentNode.SelectSingleNode("//div[contains(@class, 'video-box')]//iframe"); + + if (iframe == null) + { + _onLog($"AggregateSerialStructure: No iframe found for season {season}"); + continue; + } + + string iframeUrl = iframe.GetAttributeValue("src", "").Replace("&", "&"); + if (iframeUrl.StartsWith("//")) + iframeUrl = "https:" + iframeUrl; + + // Edge Case 2: Перевірка валідності iframe URL + if (string.IsNullOrEmpty(iframeUrl)) + { + _onLog($"AggregateSerialStructure: Empty iframe URL for season {season}"); + continue; + } + + string playerType = DeterminePlayerType(iframeUrl); + _onLog($"AggregateSerialStructure: Season {season} has playerType: {playerType}"); + + // Edge Case 3: Невідомий тип плеєра або YouTube трейлер + if (string.IsNullOrEmpty(playerType)) + { + _onLog($"AggregateSerialStructure: Unknown player type for iframe {iframeUrl} in season {season}"); + continue; + } + + // Ігноруємо трейлери та небажані відеохостинги + if (playerType == "trailer") + { + _onLog($"AggregateSerialStructure: Ignoring trailer/video host for iframe {iframeUrl} in season {season}"); + continue; + } + + if (playerType == "ashdi-serial" || playerType == "zetvideo-serial") + { + // Парсимо багатосерійний плеєр + var voices = await ParseMultiEpisodePlayer(iframeUrl, playerType); + + // Edge Case 4: Порожній результат парсингу + if (voices == null || !voices.Any()) + { + _onLog($"AggregateSerialStructure: No voices found in {playerType} for season {season}"); + continue; + } + + foreach (var voice in voices) + { + // Edge Case 5: Перевірка валідності озвучки + if (voice == null || string.IsNullOrEmpty(voice.DisplayName)) + { + _onLog($"AggregateSerialStructure: Invalid voice data in season {season}"); + continue; + } + + // Додаємо або об'єднуємо з існуючою озвучкою + if (!structure.Voices.ContainsKey(voice.DisplayName)) + { + structure.Voices[voice.DisplayName] = voice; + } + else + { + // Об'єднуємо сезони + foreach (var seasonEpisodes in voice.Seasons) + { + structure.Voices[voice.DisplayName].Seasons[seasonEpisodes.Key] = seasonEpisodes.Value; + } + } + } + } + else if (playerType == "zetvideo-vod") + { + _onLog($"AggregateSerialStructure: Processing zetvideo-vod for season {season} with {seasonGroup.Value.Count} episodes"); + + // Для zetvideo-vod достатньо визначити тип плеєра, озвучки будуть визначатися через call + // Створюємо умовну озвучку для цього сезону + string displayName = "[Uaflix] Uaflix"; + + if (!structure.Voices.ContainsKey(displayName)) + { + structure.Voices[displayName] = new VoiceInfo + { + Name = "Uaflix", + PlayerType = "zetvideo-vod", + DisplayName = displayName, + Seasons = new Dictionary>() + }; + } + + // Створюємо пустий список епізодів для цього сезону - вони будуть заповнені через call + structure.Voices[displayName].Seasons[season] = new List(); + + _onLog($"AggregateSerialStructure: Created placeholder voice for season {season} in zetvideo-vod"); + } + } + + // Edge Case 8: Перевірка наявності озвучок після агрегації + if (!structure.Voices.Any()) + { + _onLog($"AggregateSerialStructure: No voices found after aggregation for {serialUrl}"); + return null; + } + + // Edge Case 9: Перевірка наявності епізодів у озвучках + bool hasEpisodes = structure.Voices.Values.Any(v => v.Seasons.Values.Any(s => s.Any())); + if (!hasEpisodes) + { + _onLog($"AggregateSerialStructure: No episodes found in any voice for {serialUrl}"); + _onLog($"AggregateSerialStructure: Voices count: {structure.Voices.Count}"); + foreach (var voice in structure.Voices) + { + _onLog($" Voice {voice.Key}: {voice.Value.Seasons.Sum(s => s.Value.Count)} total episodes"); + } + return null; + } + + _hybridCache.Set(memKey, structure, cacheTime(40)); + _onLog($"AggregateSerialStructure: Cached structure with {structure.Voices.Count} total voices"); + + // Детальне логування структури для діагностики + foreach (var voice in structure.Voices) + { + _onLog($" Voice: {voice.Key} ({voice.Value.PlayerType}) - Seasons: {voice.Value.Seasons.Count}"); + foreach (var season in voice.Value.Seasons) + { + _onLog($" Season {season.Key}: {season.Value.Count} episodes"); + foreach (var episode in season.Value.Take(3)) // Показуємо тільки перші 3 епізоди + { + _onLog($" Episode {episode.Number}: {episode.Title} - {episode.File}"); + } + if (season.Value.Count > 3) + _onLog($" ... and {season.Value.Count - 3} more episodes"); + } + } + + return structure; + } + catch (Exception ex) + { + _onLog($"AggregateSerialStructure error: {ex.Message}"); + return null; + } + } + + #endregion public async Task> Search(string imdb_id, long kinopoisk_id, string title, string original_title, int year, string search_query) { @@ -46,36 +451,70 @@ namespace Uaflix var doc = new HtmlDocument(); doc.LoadHtml(searchHtml); - var filmNodes = doc.DocumentNode.SelectNodes("//a[contains(@class, 'sres-wrap')]"); - if (filmNodes == null) return null; + // Спробуємо різні селектори для пошуку результатів + var filmNodes = doc.DocumentNode.SelectNodes("//a[contains(@class, 'sres-wrap')]") ?? + doc.DocumentNode.SelectNodes("//div[contains(@class, 'sres-item')]//a") ?? + doc.DocumentNode.SelectNodes("//div[contains(@class, 'search-result')]//a") ?? + doc.DocumentNode.SelectNodes("//a[contains(@href, '/serials/') or contains(@href, '/films/')]"); + + if (filmNodes == null || filmNodes.Count == 0) + { + _onLog($"Search: No search results found with any selector for query: {filmTitle}"); + return null; + } res = new List(); foreach (var filmNode in filmNodes) { - var h2Node = filmNode.SelectSingleNode(".//h2"); - if (h2Node == null) continue; - - string filmUrl = filmNode.GetAttributeValue("href", ""); - if (string.IsNullOrEmpty(filmUrl)) continue; - - if (!filmUrl.StartsWith("http")) - filmUrl = _init.host + filmUrl; - - var descNode = filmNode.SelectSingleNode(".//div[contains(@class, 'sres-desc')]"); - int.TryParse(Regex.Match(descNode?.InnerText ?? "", @"\d{4}").Value, out int filmYear); - - var posterNode = filmNode.SelectSingleNode(".//img"); - string posterUrl = posterNode?.GetAttributeValue("src", ""); - if (!string.IsNullOrEmpty(posterUrl) && !posterUrl.StartsWith("http")) - posterUrl = _init.host + posterUrl; - - res.Add(new SearchResult + try { - Title = h2Node.InnerText.Trim(), - Url = filmUrl, - Year = filmYear, - PosterUrl = posterUrl - }); + var h2Node = filmNode.SelectSingleNode(".//h2") ?? filmNode.SelectSingleNode(".//h3"); + if (h2Node == null) continue; + + string filmUrl = filmNode.GetAttributeValue("href", ""); + if (string.IsNullOrEmpty(filmUrl)) continue; + + if (!filmUrl.StartsWith("http")) + filmUrl = _init.host + filmUrl; + + // Спробуємо різні способи отримати рік + int filmYear = 0; + var descNode = filmNode.SelectSingleNode(".//div[contains(@class, 'sres-desc')]") ?? + filmNode.SelectSingleNode(".//span[contains(@class, 'year')]") ?? + filmNode.SelectSingleNode(".//*[contains(text(), '20')]"); + + if (descNode != null) + { + string yearText = descNode.InnerText ?? ""; + var yearMatch = Regex.Match(yearText, @"(?:19|20)\d{2}"); + if (yearMatch.Success) + int.TryParse(yearMatch.Value, out filmYear); + } + + // Спробуємо різні селектори для постера + var posterNode = filmNode.SelectSingleNode(".//img[@src]") ?? + filmNode.SelectSingleNode(".//img[@data-src]") ?? + filmNode.SelectSingleNode(".//div[contains(@class, 'poster')]//img"); + + string posterUrl = posterNode?.GetAttributeValue("src", "") ?? posterNode?.GetAttributeValue("data-src", ""); + if (!string.IsNullOrEmpty(posterUrl) && !posterUrl.StartsWith("http")) + posterUrl = _init.host + posterUrl; + + res.Add(new SearchResult + { + Title = h2Node.InnerText.Trim(), + Url = filmUrl, + Year = filmYear, + PosterUrl = posterUrl + }); + + _onLog($"Search: Found result - {h2Node.InnerText.Trim()}, URL: {filmUrl}"); + } + catch (Exception ex) + { + _onLog($"Search: Error processing film node: {ex.Message}"); + continue; + } } if (res.Count > 0) @@ -297,7 +736,14 @@ namespace Uaflix result.ashdi_url = iframeUrl; return result; } - + + // Ігноруємо YouTube трейлери + if (iframeUrl.Contains("youtube.com/embed/")) + { + _onLog($"ParseEpisode: Ignoring YouTube trailer iframe: {iframeUrl}"); + return result; + } + if (iframeUrl.Contains("zetvideo.net")) result.streams = await ParseAllZetvideoSources(iframeUrl); else if (iframeUrl.Contains("ashdi.vip")) @@ -370,7 +816,7 @@ namespace Uaflix } return result; } - + async Task GetAshdiSubtitles(string id) { var html = await Http.Get($"https://ashdi.vip/vod/{id}", headers: new List() { new HeadersModel("User-Agent", "Mozilla/5.0"), new HeadersModel("Referer", "https://ashdi.vip/") }, proxy: _proxyManager.Get()); @@ -389,15 +835,31 @@ namespace Uaflix } return null; } + public static TimeSpan cacheTime(int multiaccess, int home = 5, int mikrotik = 2, OnlinesSettings init = null, int rhub = -1) { if (init != null && init.rhub && rhub != -1) return TimeSpan.FromMinutes(rhub); - + int ctime = AppInit.conf.mikrotik ? mikrotik : AppInit.conf.multiaccess ? init != null && init.cache_time > 0 ? init.cache_time : multiaccess : home; if (ctime > multiaccess) ctime = multiaccess; - + + return TimeSpan.FromMinutes(ctime); + } + + /// + /// Оновлений метод кешування згідно стандарту Lampac + /// + public static TimeSpan GetCacheTime(OnlinesSettings init, int multiaccess = 20, int home = 5, int mikrotik = 2, int rhub = -1) + { + if (init != null && init.rhub && rhub != -1) + return TimeSpan.FromMinutes(rhub); + + int ctime = AppInit.conf.mikrotik ? mikrotik : AppInit.conf.multiaccess ? init != null && init.cache_time > 0 ? init.cache_time : multiaccess : home; + if (init != null && ctime > init.cache_time && init.cache_time > 0) + ctime = init.cache_time; + return TimeSpan.FromMinutes(ctime); } }