mirror of
https://github.com/lampame/lampac-ukraine.git
synced 2026-04-16 17:32:20 +00:00
commit
7fdd0d8b30
@ -28,20 +28,86 @@ namespace Uaflix.Controllers
|
|||||||
|
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
[Route("uaflix")]
|
[Route("uaflix")]
|
||||||
async public Task<ActionResult> 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<ActionResult> 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);
|
var init = await loadKit(ModInit.UaFlix);
|
||||||
if (await IsBadInitialization(init))
|
if (await IsBadInitialization(init))
|
||||||
return Forbid();
|
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);
|
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<HeadersModel>() { 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)
|
if (play)
|
||||||
{
|
{
|
||||||
var playResult = await invoke.ParseEpisode(t);
|
// Визначаємо URL для парсингу - або з параметра t, або з episode_url
|
||||||
if (playResult.streams != null && playResult.streams.Count > 0)
|
string urlToParse = !string.IsNullOrEmpty(t) ? t : Request.Query["episode_url"];
|
||||||
return Redirect(HostStreamProxy(init, accsArgs(playResult.streams.First().link)));
|
|
||||||
|
|
||||||
|
var playResult = await invoke.ParseEpisode(urlToParse);
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Якщо є 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");
|
return Content("Uaflix", "text/html; charset=utf-8");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -51,8 +117,13 @@ namespace Uaflix.Controllers
|
|||||||
{
|
{
|
||||||
var searchResults = await invoke.Search(imdb_id, kinopoisk_id, title, original_title, year, title);
|
var searchResults = await invoke.Search(imdb_id, kinopoisk_id, title, original_title, year, title);
|
||||||
if (searchResults == null || searchResults.Count == 0)
|
if (searchResults == null || searchResults.Count == 0)
|
||||||
return Content("Uaflix", "text/html; charset=utf-8");
|
{
|
||||||
|
OnLog("No search results found");
|
||||||
|
OnLog("=== RETURN: no search results OnError ===");
|
||||||
|
return OnError("uaflix", proxyManager);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Для фільмів і серіалів показуємо вибір тільки якщо більше одного результату
|
||||||
if (searchResults.Count > 1)
|
if (searchResults.Count > 1)
|
||||||
{
|
{
|
||||||
var similar_tpl = new SimilarTpl(searchResults.Count);
|
var similar_tpl = new SimilarTpl(searchResults.Count);
|
||||||
@ -61,49 +132,203 @@ 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)}";
|
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);
|
similar_tpl.Append(res.Title, res.Year.ToString(), string.Empty, link, res.PosterUrl);
|
||||||
}
|
}
|
||||||
|
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");
|
return rjson ? Content(similar_tpl.ToJson(), "application/json; charset=utf-8") : Content(similar_tpl.ToHtml(), "text/html; charset=utf-8");
|
||||||
}
|
}
|
||||||
|
|
||||||
filmUrl = searchResults[0].Url;
|
filmUrl = searchResults[0].Url;
|
||||||
|
OnLog($"Auto-selected first search result: {filmUrl}");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (serial == 1)
|
if (serial == 1)
|
||||||
{
|
{
|
||||||
var paginationInfo = await invoke.GetPaginationInfo(filmUrl);
|
// Агрегуємо всі озвучки з усіх плеєрів
|
||||||
if (paginationInfo == null || paginationInfo.Episodes == null)
|
var structure = await invoke.AggregateSerialStructure(filmUrl);
|
||||||
return Content("Uaflix", "text/html; charset=utf-8");
|
if (structure == null || !structure.Voices.Any())
|
||||||
|
|
||||||
if (s == -1) // Выбор сезона
|
|
||||||
{
|
{
|
||||||
var seasons = paginationInfo.Episodes.Select(se => se.season).Distinct().OrderBy(se => se);
|
OnLog("No voices found in aggregated structure");
|
||||||
var season_tpl = new SeasonTpl(seasons.Count());
|
OnLog("=== RETURN: no voices OnError ===");
|
||||||
|
return OnError("uaflix", proxyManager);
|
||||||
|
}
|
||||||
|
|
||||||
foreach (var season in seasons)
|
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)}";
|
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 voicesForSeason = structure.Voices
|
||||||
var episode_tpl = new EpisodeTpl();
|
.Where(v => v.Value.Seasons.ContainsKey(s))
|
||||||
foreach(var ep in episodes)
|
.Select(v => new { DisplayName = v.Key, Info = v.Value })
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
if (!voicesForSeason.Any())
|
||||||
{
|
{
|
||||||
string link = $"{host}/uaflix?t={HttpUtility.UrlEncode(ep.url)}&play=true";
|
OnLog($"No voices found for season {s}");
|
||||||
episode_tpl.Append(ep.title, title, ep.season.ToString(), ep.episode.ToString(), accsArgs(link));
|
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" || voice.PlayerType == "ashdi-vod")
|
||||||
|
{
|
||||||
|
// Для 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
|
||||||
|
{
|
||||||
|
// Для багатосерійних плеєрів (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";
|
string link = $"{host}/uaflix?t={HttpUtility.UrlEncode(filmUrl)}&play=true";
|
||||||
var tpl = new MovieTpl(title, original_title, 1);
|
var tpl = new MovieTpl(title, original_title, 1);
|
||||||
tpl.Append(title, accsArgs(link), method: "play");
|
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");
|
return rjson ? Content(tpl.ToJson(), "application/json; charset=utf-8") : Content(tpl.ToHtml(), "text/html; charset=utf-8");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -29,8 +29,10 @@ namespace Uaflix
|
|||||||
username = "a",
|
username = "a",
|
||||||
password = "a",
|
password = "a",
|
||||||
list = new string[] { "socks5://IP:PORT" }
|
list = new string[] { "socks5://IP:PORT" }
|
||||||
}
|
},
|
||||||
|
// Note: OnlinesSettings не має властивості additional, використовуємо інший підхід
|
||||||
};
|
};
|
||||||
|
|
||||||
UaFlix = ModuleInvoke.Conf("Uaflix", UaFlix).ToObject<OnlinesSettings>();
|
UaFlix = ModuleInvoke.Conf("Uaflix", UaFlix).ToObject<OnlinesSettings>();
|
||||||
|
|
||||||
// Виводити "уточнити пошук"
|
// Виводити "уточнити пошук"
|
||||||
|
|||||||
@ -8,5 +8,9 @@ namespace Uaflix.Models
|
|||||||
public string title { get; set; }
|
public string title { get; set; }
|
||||||
public int season { get; set; }
|
public int season { get; set; }
|
||||||
public int episode { get; set; }
|
public int episode { get; set; }
|
||||||
|
|
||||||
|
// Нові поля для підтримки змішаних плеєрів
|
||||||
|
public string playerType { get; set; } // "ashdi-serial", "zetvideo-serial", "zetvideo-vod", "ashdi-vod"
|
||||||
|
public string iframeUrl { get; set; } // URL iframe для цього епізоду
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
31
Uaflix/Models/SerialAggregatedStructure.cs
Normal file
31
Uaflix/Models/SerialAggregatedStructure.cs
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace Uaflix.Models
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Агрегована структура серіалу з озвучками з усіх джерел (ashdi, zetvideo-serial, zetvideo-vod, ashdi-vod)
|
||||||
|
/// </summary>
|
||||||
|
public class SerialAggregatedStructure
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// URL головної сторінки серіалу
|
||||||
|
/// </summary>
|
||||||
|
public string SerialUrl { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Словник озвучок: ключ - displayName озвучки (наприклад, "[Ashdi] DniproFilm"), значення - VoiceInfo
|
||||||
|
/// </summary>
|
||||||
|
public Dictionary<string, VoiceInfo> Voices { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Список всіх епізодів серіалу (використовується для zetvideo-vod)
|
||||||
|
/// </summary>
|
||||||
|
public List<EpisodeLinkInfo> AllEpisodes { get; set; }
|
||||||
|
|
||||||
|
public SerialAggregatedStructure()
|
||||||
|
{
|
||||||
|
Voices = new Dictionary<string, VoiceInfo>();
|
||||||
|
AllEpisodes = new List<EpisodeLinkInfo>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
71
Uaflix/Models/VoiceInfo.cs
Normal file
71
Uaflix/Models/VoiceInfo.cs
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace Uaflix.Models
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Модель для зберігання інформації про озвучку серіалу
|
||||||
|
/// </summary>
|
||||||
|
public class VoiceInfo
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Назва озвучки без префіксу (наприклад, "DniproFilm")
|
||||||
|
/// </summary>
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Тип плеєра: "ashdi-serial", "zetvideo-serial", "zetvideo-vod", "ashdi-vod"
|
||||||
|
/// </summary>
|
||||||
|
public string PlayerType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Назва для відображення з префіксом плеєра (наприклад, "[Ashdi] DniproFilm")
|
||||||
|
/// </summary>
|
||||||
|
public string DisplayName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Словник сезонів: ключ - номер сезону, значення - список епізодів
|
||||||
|
/// </summary>
|
||||||
|
public Dictionary<int, List<EpisodeInfo>> Seasons { get; set; }
|
||||||
|
|
||||||
|
public VoiceInfo()
|
||||||
|
{
|
||||||
|
Seasons = new Dictionary<int, List<EpisodeInfo>>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Модель для зберігання інформації про окремий епізод
|
||||||
|
/// </summary>
|
||||||
|
public class EpisodeInfo
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Номер епізоду
|
||||||
|
/// </summary>
|
||||||
|
public int Number { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Назва епізоду
|
||||||
|
/// </summary>
|
||||||
|
public string Title { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Пряме посилання на відео файл (m3u8)
|
||||||
|
/// </summary>
|
||||||
|
public string File { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ID епізоду у плеєрі
|
||||||
|
/// </summary>
|
||||||
|
public string Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// URL постера епізоду
|
||||||
|
/// </summary>
|
||||||
|
public string Poster { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Субтитри у форматі Playerjs
|
||||||
|
/// </summary>
|
||||||
|
public string Subtitle { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -12,6 +12,8 @@ using Uaflix.Models;
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
using Shared.Models.Templates;
|
using Shared.Models.Templates;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
|
||||||
namespace Uaflix
|
namespace Uaflix
|
||||||
{
|
{
|
||||||
@ -30,6 +32,517 @@ namespace Uaflix
|
|||||||
_proxyManager = proxyManager;
|
_proxyManager = proxyManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#region Методи для визначення та парсингу різних типів плеєрів
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Визначити тип плеєра з URL iframe
|
||||||
|
/// </summary>
|
||||||
|
private string DeterminePlayerType(string iframeUrl)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(iframeUrl))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
// Перевіряємо на підтримувані типи плеєрів
|
||||||
|
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/"))
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Парсинг багатосерійного плеєра (ashdi-serial або zetvideo-serial)
|
||||||
|
/// </summary>
|
||||||
|
private async Task<List<VoiceInfo>> ParseMultiEpisodePlayer(string iframeUrl, string playerType)
|
||||||
|
{
|
||||||
|
string referer = "https://uafix.net/";
|
||||||
|
|
||||||
|
var headers = new List<HeadersModel>()
|
||||||
|
{
|
||||||
|
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<VoiceInfo>();
|
||||||
|
}
|
||||||
|
|
||||||
|
string jsonStr = match.Groups[1].Value
|
||||||
|
.Replace("\\'", "'")
|
||||||
|
.Replace("\\\"", "\"");
|
||||||
|
|
||||||
|
var voicesArray = JsonConvert.DeserializeObject<List<JObject>>(jsonStr);
|
||||||
|
var voices = new List<VoiceInfo>();
|
||||||
|
|
||||||
|
string playerPrefix = playerType == "ashdi-serial" ? "Ashdi" : "Zetvideo";
|
||||||
|
|
||||||
|
// Для формування унікальних назв озвучок
|
||||||
|
var voiceCounts = new Dictionary<string, int>();
|
||||||
|
|
||||||
|
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 = voiceObj["title"]?.ToString().Trim(), // Зберігаємо оригінальну назву для внутрішнього використання
|
||||||
|
PlayerType = playerType,
|
||||||
|
DisplayName = voiceName, // Відображаємо унікальну назву
|
||||||
|
Seasons = new Dictionary<int, List<EpisodeInfo>>()
|
||||||
|
};
|
||||||
|
|
||||||
|
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<EpisodeInfo>();
|
||||||
|
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<VoiceInfo>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Парсинг одного епізоду з zetvideo-vod
|
||||||
|
/// </summary>
|
||||||
|
private async Task<(string file, string voiceName)> ParseSingleEpisodePlayer(string iframeUrl)
|
||||||
|
{
|
||||||
|
var headers = new List<HeadersModel>()
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Парсинг одного епізоду з ashdi-vod (новий метод для обробки окремих епізодів з ashdi.vip/vod/)
|
||||||
|
/// </summary>
|
||||||
|
private async Task<(string file, string voiceName)> ParseAshdiVodEpisode(string iframeUrl)
|
||||||
|
{
|
||||||
|
var headers = new List<HeadersModel>()
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Витягнути назву озвучки з URL файлу
|
||||||
|
/// </summary>
|
||||||
|
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 Агрегація структури серіалу з усіх джерел
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Агрегує озвучки з усіх епізодів серіалу (ashdi, zetvideo-serial, zetvideo-vod)
|
||||||
|
/// </summary>
|
||||||
|
public async Task<SerialAggregatedStructure> 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<string, VoiceInfo>(),
|
||||||
|
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<HeadersModel>() {
|
||||||
|
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 створюємо озвучку з реальними епізодами
|
||||||
|
string displayName = "Uaflix #2";
|
||||||
|
|
||||||
|
if (!structure.Voices.ContainsKey(displayName))
|
||||||
|
{
|
||||||
|
structure.Voices[displayName] = new VoiceInfo
|
||||||
|
{
|
||||||
|
Name = "Uaflix",
|
||||||
|
PlayerType = "zetvideo-vod",
|
||||||
|
DisplayName = displayName,
|
||||||
|
Seasons = new Dictionary<int, List<EpisodeInfo>>()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Створюємо епізоди для цього сезону з посиланнями на сторінки епізодів
|
||||||
|
var episodes = new List<EpisodeInfo>();
|
||||||
|
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 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<int, List<EpisodeInfo>>()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Створюємо епізоди для цього сезону з посиланнями на сторінки епізодів
|
||||||
|
var episodes = new List<EpisodeInfo>();
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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<List<SearchResult>> Search(string imdb_id, long kinopoisk_id, string title, string original_title, int year, string search_query)
|
public async Task<List<SearchResult>> Search(string imdb_id, long kinopoisk_id, string title, string original_title, int year, string search_query)
|
||||||
{
|
{
|
||||||
string memKey = $"UaFlix:search:{kinopoisk_id}:{imdb_id}:{search_query}";
|
string memKey = $"UaFlix:search:{kinopoisk_id}:{imdb_id}:{search_query}";
|
||||||
@ -46,36 +559,70 @@ namespace Uaflix
|
|||||||
var doc = new HtmlDocument();
|
var doc = new HtmlDocument();
|
||||||
doc.LoadHtml(searchHtml);
|
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<SearchResult>();
|
res = new List<SearchResult>();
|
||||||
foreach (var filmNode in filmNodes)
|
foreach (var filmNode in filmNodes)
|
||||||
{
|
{
|
||||||
var h2Node = filmNode.SelectSingleNode(".//h2");
|
try
|
||||||
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
|
|
||||||
{
|
{
|
||||||
Title = h2Node.InnerText.Trim(),
|
var h2Node = filmNode.SelectSingleNode(".//h2") ?? filmNode.SelectSingleNode(".//h3");
|
||||||
Url = filmUrl,
|
if (h2Node == null) continue;
|
||||||
Year = filmYear,
|
|
||||||
PosterUrl = posterUrl
|
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)
|
if (res.Count > 0)
|
||||||
@ -298,16 +845,37 @@ namespace Uaflix
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ігноруємо YouTube трейлери
|
||||||
|
if (iframeUrl.Contains("youtube.com/embed/"))
|
||||||
|
{
|
||||||
|
_onLog($"ParseEpisode: Ignoring YouTube trailer iframe: {iframeUrl}");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
if (iframeUrl.Contains("zetvideo.net"))
|
if (iframeUrl.Contains("zetvideo.net"))
|
||||||
result.streams = await ParseAllZetvideoSources(iframeUrl);
|
result.streams = await ParseAllZetvideoSources(iframeUrl);
|
||||||
else if (iframeUrl.Contains("ashdi.vip"))
|
else if (iframeUrl.Contains("ashdi.vip"))
|
||||||
{
|
{
|
||||||
result.streams = await ParseAllAshdiSources(iframeUrl);
|
// Перевіряємо, чи це ashdi-vod (окремий епізод) або ashdi-serial (багатосерійний плеєр)
|
||||||
var idMatch = Regex.Match(iframeUrl, @"_(\d+)|vod/(\d+)");
|
if (iframeUrl.Contains("/vod/"))
|
||||||
if (idMatch.Success)
|
|
||||||
{
|
{
|
||||||
string ashdiId = idMatch.Groups[1].Success ? idMatch.Groups[1].Value : idMatch.Groups[2].Value;
|
// Це окремий епізод на ashdi.vip/vod/, обробляємо як ashdi-vod
|
||||||
result.subtitles = await GetAshdiSubtitles(ashdiId);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -389,6 +957,7 @@ namespace Uaflix
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static TimeSpan cacheTime(int multiaccess, int home = 5, int mikrotik = 2, OnlinesSettings init = null, int rhub = -1)
|
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)
|
if (init != null && init.rhub && rhub != -1)
|
||||||
@ -400,5 +969,20 @@ namespace Uaflix
|
|||||||
|
|
||||||
return TimeSpan.FromMinutes(ctime);
|
return TimeSpan.FromMinutes(ctime);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Оновлений метод кешування згідно стандарту Lampac
|
||||||
|
/// </summary>
|
||||||
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user