From 86e77561e457318907b17735213d45f42d398ddb Mon Sep 17 00:00:00 2001 From: Felix Date: Sat, 18 Oct 2025 08:51:35 +0300 Subject: [PATCH 1/6] 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); } } From c5d698b01aab8869a5785797dafec5cbac236c05 Mon Sep 17 00:00:00 2001 From: Felix Date: Sat, 18 Oct 2025 10:15:09 +0300 Subject: [PATCH 2/6] Add Voice logic --- Uaflix/Controller.cs | 51 +++++--- Uaflix/Models/EpisodeLinkInfo.cs | 2 +- Uaflix/Models/SerialAggregatedStructure.cs | 2 +- Uaflix/Models/VoiceInfo.cs | 2 +- Uaflix/UaflixInvoke.cs | 128 +++++++++++++++++++-- 5 files changed, 154 insertions(+), 31 deletions(-) diff --git a/Uaflix/Controller.cs b/Uaflix/Controller.cs index 7b55763..8068705 100644 --- a/Uaflix/Controller.cs +++ b/Uaflix/Controller.cs @@ -79,7 +79,10 @@ namespace Uaflix.Controllers if (play) { - var playResult = await invoke.ParseEpisode(t); + // Визначаємо URL для парсингу - або з параметра t, або з episode_url + string urlToParse = !string.IsNullOrEmpty(t) ? t : Request.Query["episode_url"]; + + var playResult = await invoke.ParseEpisode(urlToParse); if (playResult.streams != null && playResult.streams.Count > 0) { OnLog("=== RETURN: play redirect ==="); @@ -89,6 +92,24 @@ namespace Uaflix.Controllers OnLog("=== RETURN: play no streams ==="); return Content("Uaflix", "text/html; charset=utf-8"); } + + // Якщо є episode_url але немає play=true, це виклик для отримання інформації про стрім (для method: 'call') + string episodeUrl = Request.Query["episode_url"]; + if (!string.IsNullOrEmpty(episodeUrl)) + { + var playResult = await invoke.ParseEpisode(episodeUrl); + if (playResult.streams != null && playResult.streams.Count > 0) + { + // Повертаємо JSON з інформацією про стрім для методу 'play' + string streamUrl = HostStreamProxy(init, accsArgs(playResult.streams.First().link)); + string jsonResult = $"{{\"method\":\"play\",\"url\":\"{streamUrl}\",\"title\":\"{title ?? original_title}\"}}"; + OnLog($"=== RETURN: call method JSON for episode_url ==="); + return Content(jsonResult, "application/json; charset=utf-8"); + } + + OnLog("=== RETURN: call method no streams ==="); + return Content("Uaflix", "text/html; charset=utf-8"); + } string filmUrl = href; @@ -251,23 +272,19 @@ namespace Uaflix.Controllers // Для ashdi/zetvideo-serial повертаємо готове посилання з play var voice = structure.Voices[t]; - if (voice.PlayerType == "zetvideo-vod") + if (voice.PlayerType == "zetvideo-vod" || voice.PlayerType == "ashdi-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) - ); - } + // Для zetvideo-vod та ashdi-vod використовуємо URL епізоду для виклику + // Потрібно передати URL епізоду в інший параметр, щоб не плутати з play=true + string callUrl = $"{host}/uaflix?episode_url={HttpUtility.UrlEncode(ep.File)}&imdb_id={imdb_id}&kinopoisk_id={kinopoisk_id}&title={HttpUtility.UrlEncode(title)}&original_title={HttpUtility.UrlEncode(original_title)}&year={year}&serial={serial}&s={s}&e={ep.Number}"; + episode_tpl.Append( + name: ep.Title, + title: title, + s: s.ToString(), + e: ep.Number.ToString(), + link: accsArgs(callUrl), + method: "call" + ); } else { diff --git a/Uaflix/Models/EpisodeLinkInfo.cs b/Uaflix/Models/EpisodeLinkInfo.cs index 9b4adb0..2180106 100644 --- a/Uaflix/Models/EpisodeLinkInfo.cs +++ b/Uaflix/Models/EpisodeLinkInfo.cs @@ -10,7 +10,7 @@ namespace Uaflix.Models public int episode { get; set; } // Нові поля для підтримки змішаних плеєрів - public string playerType { get; set; } // "ashdi-serial", "zetvideo-serial", "zetvideo-vod" + public string playerType { get; set; } // "ashdi-serial", "zetvideo-serial", "zetvideo-vod", "ashdi-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 index ef2d770..d0deede 100644 --- a/Uaflix/Models/SerialAggregatedStructure.cs +++ b/Uaflix/Models/SerialAggregatedStructure.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; namespace Uaflix.Models { /// - /// Агрегована структура серіалу з озвучками з усіх джерел (ashdi, zetvideo-serial, zetvideo-vod) + /// Агрегована структура серіалу з озвучками з усіх джерел (ashdi, zetvideo-serial, zetvideo-vod, ashdi-vod) /// public class SerialAggregatedStructure { diff --git a/Uaflix/Models/VoiceInfo.cs b/Uaflix/Models/VoiceInfo.cs index 5a52735..2e6a474 100644 --- a/Uaflix/Models/VoiceInfo.cs +++ b/Uaflix/Models/VoiceInfo.cs @@ -13,7 +13,7 @@ namespace Uaflix.Models public string Name { get; set; } /// - /// Тип плеєра: "ashdi-serial", "zetvideo-serial", "zetvideo-vod" + /// Тип плеєра: "ashdi-serial", "zetvideo-serial", "zetvideo-vod", "ashdi-vod" /// public string PlayerType { get; set; } diff --git a/Uaflix/UaflixInvoke.cs b/Uaflix/UaflixInvoke.cs index 9df46ad..7c25c98 100644 --- a/Uaflix/UaflixInvoke.cs +++ b/Uaflix/UaflixInvoke.cs @@ -45,6 +45,8 @@ namespace Uaflix // Перевіряємо на підтримувані типи плеєрів if (iframeUrl.Contains("ashdi.vip/serial/")) return "ashdi-serial"; + else if (iframeUrl.Contains("ashdi.vip/vod/")) + return "ashdi-vod"; else if (iframeUrl.Contains("zetvideo.net/serial/")) return "zetvideo-serial"; else if (iframeUrl.Contains("zetvideo.net/vod/")) @@ -204,6 +206,46 @@ namespace Uaflix } } + /// + /// Парсинг одного епізоду з ashdi-vod (новий метод для обробки окремих епізодів з ashdi.vip/vod/) + /// + private async Task<(string file, string voiceName)> ParseAshdiVodEpisode(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()); + + // Шукаємо Playerjs конфігурацію з file параметром + var match = Regex.Match(html, @"file:\s*'?([^'""\s,}]+\.m3u8)'?"); + if (!match.Success) + { + // Якщо не знайдено, шукаємо в іншому форматі + match = Regex.Match(html, @"file['""]?\s*:\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($"ParseAshdiVodEpisode error: {ex.Message}"); + return (null, null); + } + } + /// /// Витягнути назву озвучки з URL файлу /// @@ -363,9 +405,8 @@ namespace Uaflix { _onLog($"AggregateSerialStructure: Processing zetvideo-vod for season {season} with {seasonGroup.Value.Count} episodes"); - // Для zetvideo-vod достатньо визначити тип плеєра, озвучки будуть визначатися через call - // Створюємо умовну озвучку для цього сезону - string displayName = "[Uaflix] Uaflix"; + // Для zetvideo-vod створюємо озвучку з реальними епізодами + string displayName = "Uaflix #2"; if (!structure.Voices.ContainsKey(displayName)) { @@ -378,10 +419,61 @@ namespace Uaflix }; } - // Створюємо пустий список епізодів для цього сезону - вони будуть заповнені через call - structure.Voices[displayName].Seasons[season] = new List(); + // Створюємо епізоди для цього сезону з посиланнями на сторінки епізодів + var episodes = new List(); + foreach (var episodeInfo in seasonGroup.Value) + { + episodes.Add(new EpisodeInfo + { + Number = episodeInfo.episode, + Title = episodeInfo.title, + File = episodeInfo.url, // URL сторінки епізоду для використання в call + Id = episodeInfo.url, + Poster = null, + Subtitle = null + }); + } - _onLog($"AggregateSerialStructure: Created placeholder voice for season {season} in zetvideo-vod"); + structure.Voices[displayName].Seasons[season] = episodes; + + _onLog($"AggregateSerialStructure: Created voice with {episodes.Count} episodes for season {season} in zetvideo-vod"); + } + else if (playerType == "ashdi-vod") + { + _onLog($"AggregateSerialStructure: Processing ashdi-vod for season {season} with {seasonGroup.Value.Count} episodes"); + + // Для ashdi-vod створюємо озвучку з реальними епізодами + string displayName = "Uaflix #3"; + + if (!structure.Voices.ContainsKey(displayName)) + { + structure.Voices[displayName] = new VoiceInfo + { + Name = "Uaflix", + PlayerType = "ashdi-vod", + DisplayName = displayName, + Seasons = new Dictionary>() + }; + } + + // Створюємо епізоди для цього сезону з посиланнями на сторінки епізодів + var episodes = new List(); + foreach (var episodeInfo in seasonGroup.Value) + { + episodes.Add(new EpisodeInfo + { + Number = episodeInfo.episode, + Title = episodeInfo.title, + File = episodeInfo.url, // URL сторінки епізоду для використання в call + Id = episodeInfo.url, + Poster = null, + Subtitle = null + }); + } + + structure.Voices[displayName].Seasons[season] = episodes; + + _onLog($"AggregateSerialStructure: Created voice with {episodes.Count} episodes for season {season} in ashdi-vod"); } } @@ -748,12 +840,26 @@ namespace Uaflix result.streams = await ParseAllZetvideoSources(iframeUrl); else if (iframeUrl.Contains("ashdi.vip")) { - result.streams = await ParseAllAshdiSources(iframeUrl); - var idMatch = Regex.Match(iframeUrl, @"_(\d+)|vod/(\d+)"); - if (idMatch.Success) + // Перевіряємо, чи це ashdi-vod (окремий епізод) або ashdi-serial (багатосерійний плеєр) + if (iframeUrl.Contains("/vod/")) { - string ashdiId = idMatch.Groups[1].Success ? idMatch.Groups[1].Value : idMatch.Groups[2].Value; - result.subtitles = await GetAshdiSubtitles(ashdiId); + // Це окремий епізод на ashdi.vip/vod/, обробляємо як ashdi-vod + var (file, voiceName) = await ParseAshdiVodEpisode(iframeUrl); + if (!string.IsNullOrEmpty(file)) + { + result.streams.Add((file, "1080p")); + } + } + else + { + // Це багатосерійний плеєр, обробляємо як і раніше + result.streams = await ParseAllAshdiSources(iframeUrl); + var idMatch = Regex.Match(iframeUrl, @"_(\d+)|vod/(\d+)"); + if (idMatch.Success) + { + string ashdiId = idMatch.Groups[1].Success ? idMatch.Groups[1].Value : idMatch.Groups[2].Value; + result.subtitles = await GetAshdiSubtitles(ashdiId); + } } } } From 5142543a3e37b3f19299c8dd4bb8b83355c0a63b Mon Sep 17 00:00:00 2001 From: Felix Date: Sat, 18 Oct 2025 10:20:05 +0300 Subject: [PATCH 3/6] =?UTF-8?q?=D0=92=D0=B8=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=BD=D1=8F=20=D0=BF=D0=BE=D1=88=D1=83=D0=BA=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Uaflix/Controller.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Uaflix/Controller.cs b/Uaflix/Controller.cs index 8068705..3f32f36 100644 --- a/Uaflix/Controller.cs +++ b/Uaflix/Controller.cs @@ -123,9 +123,8 @@ namespace Uaflix.Controllers return OnError("uaflix", proxyManager); } - // Для серіалів завжди вибираємо перший результат автоматично - // Для фільмів показуємо вибір тільки якщо більше одного результату - if (serial == 0 && searchResults.Count > 1) + // Для фільмів і серіалів показуємо вибір тільки якщо більше одного результату + if (searchResults.Count > 1) { var similar_tpl = new SimilarTpl(searchResults.Count); foreach (var res in searchResults) @@ -133,7 +132,7 @@ 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}) ==="); + OnLog($"=== RETURN: similar items ({searchResults.Count}) ==="); return rjson ? Content(similar_tpl.ToJson(), "application/json; charset=utf-8") : Content(similar_tpl.ToHtml(), "text/html; charset=utf-8"); } From a3d6a294b841e09e63284edb8037e3df63da74a6 Mon Sep 17 00:00:00 2001 From: Felix Date: Sat, 18 Oct 2025 10:32:37 +0300 Subject: [PATCH 4/6] =?UTF-8?q?All=20planned=20tasks=20have=20been=20execu?= =?UTF-8?q?ted=20and=20documented.=20The=20Uaflix=20module=20now=20correct?= =?UTF-8?q?ly=20provides=20a=20selection=20of=20search=20results=20for=20T?= =?UTF-8?q?V=20series=20when=20multiple=20results=20are=20found,=20similar?= =?UTF-8?q?=20to=20how=20it=20works=20for=20movies.=20The=20fix=20addresse?= =?UTF-8?q?s=20the=20issue=20where=20the=20system=20would=20automatically?= =?UTF-8?q?=20select=20the=20first=20result=20(e.g.,=20"=D0=A1=D0=BE=D1=82?= =?UTF-8?q?=D0=BD=D1=8F=20=D1=81=D0=BF=D0=BE=D0=B3=D0=B0=D0=B4=D1=96=D0=B2?= =?UTF-8?q?"=20instead=20of=20"=D0=A1=D0=BE=D1=82=D0=BD=D1=8F=20/=20The=20?= =?UTF-8?q?100")=20without=20giving=20the=20user=20a=20choice.=20Additiona?= =?UTF-8?q?lly,=20UI/UX=20improvements=20have=20been=20implemented:?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Unique voice names when duplicates exist (e.g., "Uaflix" and "Uaflix 2" instead of "[Ashdi] Uaflix" and "[Zetvideo] Uaflix") Season numbers displayed without the word "Сезон" (e.g., "1" instead of "Сезон 1") --- Uaflix/Controller.cs | 2 +- Uaflix/UaflixInvoke.cs | 20 ++++++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/Uaflix/Controller.cs b/Uaflix/Controller.cs index 3f32f36..fb73002 100644 --- a/Uaflix/Controller.cs +++ b/Uaflix/Controller.cs @@ -202,7 +202,7 @@ namespace Uaflix.Controllers 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.ToString()); + season_tpl.Append($"{season}", link, season.ToString()); OnLog($"Added season {season} to template"); } diff --git a/Uaflix/UaflixInvoke.cs b/Uaflix/UaflixInvoke.cs index 7c25c98..d3db7b8 100644 --- a/Uaflix/UaflixInvoke.cs +++ b/Uaflix/UaflixInvoke.cs @@ -109,17 +109,33 @@ namespace Uaflix string playerPrefix = playerType == "ashdi-serial" ? "Ashdi" : "Zetvideo"; + // Для формування унікальних назв озвучок + var voiceCounts = new Dictionary(); + foreach (var voiceObj in voicesArray) { string voiceName = voiceObj["title"]?.ToString().Trim(); if (string.IsNullOrEmpty(voiceName)) continue; + // Перевіряємо, чи вже існує така назва озвучки + if (voiceCounts.ContainsKey(voiceName)) + { + voiceCounts[voiceName]++; + // Якщо є дублікат, додаємо номер + voiceName = $"{voiceName} {voiceCounts[voiceName]}"; + } + else + { + // Ініціалізуємо лічильник для нової озвучки + voiceCounts[voiceObj["title"]?.ToString().Trim()] = 1; + } + var voiceInfo = new VoiceInfo { - Name = voiceName, + Name = voiceObj["title"]?.ToString().Trim(), // Зберігаємо оригінальну назву для внутрішнього використання PlayerType = playerType, - DisplayName = $"[{playerPrefix}] {voiceName}", + DisplayName = voiceName, // Відображаємо унікальну назву Seasons = new Dictionary>() }; From e87a810a669c567925673b4940f7dadd17a98243 Mon Sep 17 00:00:00 2001 From: Felix Date: Sun, 19 Oct 2025 07:51:47 +0300 Subject: [PATCH 5/6] Update version --- Uaflix/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Uaflix/manifest.json b/Uaflix/manifest.json index 87d6ce9..f6a854f 100644 --- a/Uaflix/manifest.json +++ b/Uaflix/manifest.json @@ -1,6 +1,6 @@ { "enable": true, - "version": 2, + "version": 3, "initspace": "Uaflix.ModInit", "online": "Uaflix.OnlineApi" } \ No newline at end of file From 7e5acfd0e1237398b3b666f429dfb2e6ba9d86f9 Mon Sep 17 00:00:00 2001 From: Felix Date: Sun, 19 Oct 2025 08:01:04 +0300 Subject: [PATCH 6/6] Revert version --- Uaflix/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Uaflix/manifest.json b/Uaflix/manifest.json index f6a854f..87d6ce9 100644 --- a/Uaflix/manifest.json +++ b/Uaflix/manifest.json @@ -1,6 +1,6 @@ { "enable": true, - "version": 3, + "version": 2, "initspace": "Uaflix.ModInit", "online": "Uaflix.OnlineApi" } \ No newline at end of file