diff --git a/UAKino/Controller.cs b/UAKino/Controller.cs new file mode 100644 index 0000000..811c04b --- /dev/null +++ b/UAKino/Controller.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Web; +using Microsoft.AspNetCore.Mvc; +using Shared; +using Shared.Engine; +using Shared.Models.Online.Settings; +using Shared.Models.Templates; +using UAKino.Models; + +namespace UAKino.Controllers +{ + public class Controller : BaseOnlineController + { + ProxyManager proxyManager; + + public Controller() + { + proxyManager = new ProxyManager(ModInit.UAKino); + } + + [HttpGet] + [Route("uakino")] + 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, bool rjson = false, string href = null) + { + var init = await loadKit(ModInit.UAKino); + if (!init.enable) + return Forbid(); + + var invoke = new UAKinoInvoke(init, hybridCache, OnLog, proxyManager); + + string itemUrl = href; + if (string.IsNullOrEmpty(itemUrl)) + { + var searchResults = await invoke.Search(title, original_title, serial); + if (searchResults == null || searchResults.Count == 0) + return OnError("uakino", proxyManager); + + if (searchResults.Count > 1) + { + var similar_tpl = new SimilarTpl(searchResults.Count); + foreach (var res in searchResults) + { + string link = $"{host}/uakino?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, string.Empty, string.Empty, link, res.Poster); + } + + return rjson ? Content(similar_tpl.ToJson(), "application/json; charset=utf-8") : Content(similar_tpl.ToHtml(), "text/html; charset=utf-8"); + } + + itemUrl = searchResults[0].Url; + } + + if (serial == 1) + { + var playlist = await invoke.GetPlaylist(itemUrl); + if (playlist == null || playlist.Count == 0) + return OnError("uakino", proxyManager); + + var voiceGroups = playlist + .GroupBy(p => string.IsNullOrEmpty(p.Voice) ? "Основне" : p.Voice) + .Select(g => (key: g.Key, episodes: g.ToList())) + .ToList(); + + if (voiceGroups.Count == 0) + return OnError("uakino", proxyManager); + + if (string.IsNullOrEmpty(t)) + t = voiceGroups.First().key; + + var voice_tpl = new VoiceTpl(); + foreach (var voice in voiceGroups) + { + string voiceLink = $"{host}/uakino?imdb_id={imdb_id}&kinopoisk_id={kinopoisk_id}&title={HttpUtility.UrlEncode(title)}&original_title={HttpUtility.UrlEncode(original_title)}&year={year}&serial=1&t={HttpUtility.UrlEncode(voice.key)}&href={HttpUtility.UrlEncode(itemUrl)}"; + voice_tpl.Append(voice.key, voice.key == t, voiceLink); + } + + var selected = voiceGroups.FirstOrDefault(v => v.key == t); + if (selected.episodes == null || selected.episodes.Count == 0) + return OnError("uakino", proxyManager); + + var episode_tpl = new EpisodeTpl(); + int index = 1; + foreach (var ep in selected.episodes.OrderBy(e => UAKinoInvoke.TryParseEpisodeNumber(e.Title) ?? int.MaxValue)) + { + int episodeNumber = UAKinoInvoke.TryParseEpisodeNumber(ep.Title) ?? index; + string episodeName = string.IsNullOrEmpty(ep.Title) ? $"Епізод {episodeNumber}" : ep.Title; + string callUrl = $"{host}/uakino/play?url={HttpUtility.UrlEncode(ep.Url)}&title={HttpUtility.UrlEncode(title ?? original_title)}"; + episode_tpl.Append(episodeName, title ?? original_title, "1", episodeNumber.ToString("D2"), accsArgs(callUrl), "call"); + index++; + } + + if (rjson) + return Content(episode_tpl.ToJson(voice_tpl), "application/json; charset=utf-8"); + + return Content(voice_tpl.ToHtml() + episode_tpl.ToHtml(), "text/html; charset=utf-8"); + } + else + { + string playerUrl = await invoke.GetPlayerUrl(itemUrl); + if (string.IsNullOrEmpty(playerUrl)) + { + var playlist = await invoke.GetPlaylist(itemUrl); + playerUrl = playlist?.FirstOrDefault()?.Url; + } + + if (string.IsNullOrEmpty(playerUrl)) + return OnError("uakino", proxyManager); + + var movie_tpl = new MovieTpl(title, original_title); + string callUrl = $"{host}/uakino/play?url={HttpUtility.UrlEncode(playerUrl)}&title={HttpUtility.UrlEncode(title ?? original_title)}"; + movie_tpl.Append(string.IsNullOrEmpty(title) ? "UAKino" : title, accsArgs(callUrl), "call"); + + return rjson ? Content(movie_tpl.ToJson(), "application/json; charset=utf-8") : Content(movie_tpl.ToHtml(), "text/html; charset=utf-8"); + } + } + + [HttpGet] + [Route("uakino/play")] + async public Task Play(string url, string title) + { + if (string.IsNullOrEmpty(url)) + return OnError("uakino", proxyManager); + + var init = await loadKit(ModInit.UAKino); + if (!init.enable) + return Forbid(); + + var invoke = new UAKinoInvoke(init, hybridCache, OnLog, proxyManager); + var result = await invoke.ParsePlayer(url); + if (result == null || string.IsNullOrEmpty(result.File)) + return OnError("uakino", proxyManager); + + string streamUrl = HostStreamProxy(init, accsArgs(result.File), proxy: proxyManager.Get()); + string jsonResult = $"{{\"method\":\"play\",\"url\":\"{streamUrl}\",\"title\":\"{title ?? ""}\"}}"; + return Content(jsonResult, "application/json; charset=utf-8"); + } + } +} diff --git a/UAKino/ModInit.cs b/UAKino/ModInit.cs new file mode 100644 index 0000000..3df537f --- /dev/null +++ b/UAKino/ModInit.cs @@ -0,0 +1,35 @@ +using Shared; +using Shared.Engine; +using Shared.Models.Online.Settings; +using Shared.Models.Module; + +namespace UAKino +{ + public class ModInit + { + public static OnlinesSettings UAKino; + + /// + /// модуль загружен + /// + public static void loaded(InitspaceModel initspace) + { + UAKino = new OnlinesSettings("UAKino", "https://uakino.best", streamproxy: false, useproxy: false) + { + displayname = "UAKino", + displayindex = 0, + proxy = new Shared.Models.Base.ProxySettings() + { + useAuth = true, + username = "", + password = "", + list = new string[] { "socks5://ip:port" } + } + }; + UAKino = ModuleInvoke.Conf("UAKino", UAKino).ToObject(); + + // Виводити "уточнити пошук" + AppInit.conf.online.with_search.Add("uakino"); + } + } +} diff --git a/UAKino/Models/UAKinoModels.cs b/UAKino/Models/UAKinoModels.cs new file mode 100644 index 0000000..4b2f6ea --- /dev/null +++ b/UAKino/Models/UAKinoModels.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; + +namespace UAKino.Models +{ + public class SearchResult + { + public string Title { get; set; } + public string Url { get; set; } + public string Poster { get; set; } + public string Season { get; set; } + } + + public class PlaylistItem + { + public string Title { get; set; } + public string Url { get; set; } + public string Voice { get; set; } + } + + public class SubtitleInfo + { + public string Lang { get; set; } + public string Url { get; set; } + } + + public class PlayerResult + { + public string File { get; set; } + public List Subtitles { get; set; } = new(); + } +} diff --git a/UAKino/OnlineApi.cs b/UAKino/OnlineApi.cs new file mode 100644 index 0000000..7404676 --- /dev/null +++ b/UAKino/OnlineApi.cs @@ -0,0 +1,25 @@ +using Shared.Models.Base; +using System.Collections.Generic; + +namespace UAKino +{ + public class OnlineApi + { + public static List<(string name, string url, string plugin, int index)> Events(string host, 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) + { + var online = new List<(string name, string url, string plugin, int index)>(); + + var init = ModInit.UAKino; + if (init.enable && !init.rip) + { + string url = init.overridehost; + if (string.IsNullOrEmpty(url)) + url = $"{host}/uakino"; + + online.Add((init.displayname, url, "uakino", init.displayindex)); + } + + return online; + } + } +} diff --git a/UAKino/UAKino.csproj b/UAKino/UAKino.csproj new file mode 100644 index 0000000..1fbe365 --- /dev/null +++ b/UAKino/UAKino.csproj @@ -0,0 +1,15 @@ + + + + net9.0 + library + true + + + + + ..\..\Shared.dll + + + + diff --git a/UAKino/UAKinoInvoke.cs b/UAKino/UAKinoInvoke.cs new file mode 100644 index 0000000..03bd315 --- /dev/null +++ b/UAKino/UAKinoInvoke.cs @@ -0,0 +1,438 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Web; +using HtmlAgilityPack; +using Shared; +using Shared.Engine; +using Shared.Models; +using Shared.Models.Online.Settings; +using UAKino.Models; + +namespace UAKino +{ + public class UAKinoInvoke + { + private const string PlaylistPath = "/engine/ajax/playlists.php"; + private const string PlaylistField = "playlist"; + private const string BlacklistRegex = "(/news/)|(/franchise/)"; + private readonly OnlinesSettings _init; + private readonly HybridCache _hybridCache; + private readonly Action _onLog; + private readonly ProxyManager _proxyManager; + + public UAKinoInvoke(OnlinesSettings init, HybridCache hybridCache, Action onLog, ProxyManager proxyManager) + { + _init = init; + _hybridCache = hybridCache; + _onLog = onLog; + _proxyManager = proxyManager; + } + + public async Task> Search(string title, string original_title, int serial) + { + var queries = new List(); + if (!string.IsNullOrEmpty(title)) + queries.Add(title); + if (!string.IsNullOrEmpty(original_title) && !queries.Contains(original_title)) + queries.Add(original_title); + + if (queries.Count == 0) + return null; + + string memKey = $"UAKino:search:{string.Join("|", queries)}:{serial}"; + if (_hybridCache.TryGetValue(memKey, out List cached)) + return cached; + + var results = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + + foreach (var query in queries) + { + try + { + string searchUrl = $"{_init.host}/index.php?do=search&subaction=search&story={HttpUtility.UrlEncode(query)}"; + var headers = new List() + { + new HeadersModel("User-Agent", "Mozilla/5.0"), + new HeadersModel("Referer", _init.host) + }; + + _onLog?.Invoke($"UAKino search: {searchUrl}"); + string html = await Http.Get(searchUrl, headers: headers, proxy: _proxyManager.Get()); + if (string.IsNullOrEmpty(html)) + continue; + + var doc = new HtmlDocument(); + doc.LoadHtml(html); + + var nodes = doc.DocumentNode.SelectNodes("//div[contains(@class,'movie-item') and contains(@class,'short-item')]"); + if (nodes == null) + continue; + + foreach (var node in nodes) + { + var titleNode = node.SelectSingleNode(".//a[contains(@class,'movie-title')] | .//a[contains(@class,'full-movie')]"); + string itemTitle = CleanText(titleNode?.InnerText); + string href = NormalizeUrl(titleNode?.GetAttributeValue("href", "")); + if (string.IsNullOrEmpty(itemTitle)) + { + var altTitle = node.SelectSingleNode(".//div[contains(@class,'full-movie-title')]"); + itemTitle = CleanText(altTitle?.InnerText); + } + + if (string.IsNullOrEmpty(itemTitle) || string.IsNullOrEmpty(href) || IsBlacklisted(href)) + continue; + + if (serial == 1 && !IsSeriesUrl(href)) + continue; + if (serial == 0 && !IsMovieUrl(href)) + continue; + + string seasonText = CleanText(node.SelectSingleNode(".//div[contains(@class,'full-season')]")?.InnerText); + if (!string.IsNullOrEmpty(seasonText) && !itemTitle.Contains(seasonText, StringComparison.OrdinalIgnoreCase)) + itemTitle = $"{itemTitle} ({seasonText})"; + + string poster = ExtractPoster(node); + + if (seen.Contains(href)) + continue; + seen.Add(href); + + results.Add(new SearchResult + { + Title = itemTitle, + Url = href, + Poster = poster, + Season = seasonText + }); + } + + if (results.Count > 0) + break; + } + catch (Exception ex) + { + _onLog?.Invoke($"UAKino search error: {ex.Message}"); + } + } + + if (results.Count > 0) + _hybridCache.Set(memKey, results, cacheTime(20, init: _init)); + + return results; + } + + public async Task> GetPlaylist(string href) + { + string newsId = ExtractNewsId(href); + if (string.IsNullOrEmpty(newsId)) + return null; + + string memKey = $"UAKino:playlist:{newsId}"; + if (_hybridCache.TryGetValue(memKey, out List cached)) + return cached; + + string url = BuildPlaylistUrl(newsId); + var headers = new List() + { + new HeadersModel("User-Agent", "Mozilla/5.0"), + new HeadersModel("Referer", href ?? _init.host), + new HeadersModel("X-Requested-With", "XMLHttpRequest") + }; + + try + { + _onLog?.Invoke($"UAKino playlist: {url}"); + string payload = await Http.Get(url, headers: headers, proxy: _proxyManager.Get()); + if (string.IsNullOrEmpty(payload)) + return null; + + using var document = JsonDocument.Parse(payload); + if (!document.RootElement.TryGetProperty("success", out var successProp) || !successProp.GetBoolean()) + return null; + + if (!document.RootElement.TryGetProperty("response", out var responseProp)) + return null; + + string html = responseProp.GetString(); + if (string.IsNullOrEmpty(html)) + return null; + + var items = ParsePlaylistHtml(html); + if (items.Count > 0) + _hybridCache.Set(memKey, items, cacheTime(10, init: _init)); + + return items; + } + catch (Exception ex) + { + _onLog?.Invoke($"UAKino playlist error: {ex.Message}"); + return null; + } + } + + public async Task GetPlayerUrl(string href) + { + if (string.IsNullOrEmpty(href)) + return null; + + var headers = new List() + { + new HeadersModel("User-Agent", "Mozilla/5.0"), + new HeadersModel("Referer", _init.host) + }; + + try + { + _onLog?.Invoke($"UAKino movie page: {href}"); + string html = await Http.Get(href, headers: headers, proxy: _proxyManager.Get()); + if (string.IsNullOrEmpty(html)) + return null; + + var doc = new HtmlDocument(); + doc.LoadHtml(html); + + var iframe = doc.DocumentNode.SelectSingleNode("//iframe[@id='pre']"); + if (iframe == null) + return null; + + string src = iframe.GetAttributeValue("src", ""); + if (string.IsNullOrEmpty(src)) + src = iframe.GetAttributeValue("data-src", ""); + + return NormalizeUrl(src); + } + catch (Exception ex) + { + _onLog?.Invoke($"UAKino player url error: {ex.Message}"); + return null; + } + } + + public async Task ParsePlayer(string url) + { + if (string.IsNullOrEmpty(url)) + return null; + + if (LooksLikeDirectStream(url)) + { + return new PlayerResult { File = url }; + } + + var headers = new List() + { + new HeadersModel("User-Agent", "Mozilla/5.0"), + new HeadersModel("Referer", _init.host) + }; + + try + { + _onLog?.Invoke($"UAKino parse player: {url}"); + string html = await Http.Get(url, headers: headers, proxy: _proxyManager.Get()); + if (string.IsNullOrEmpty(html)) + return null; + + string file = ExtractPlayerFile(html); + if (string.IsNullOrEmpty(file)) + return null; + + return new PlayerResult + { + File = NormalizeUrl(file), + Subtitles = ExtractSubtitles(html) + }; + } + catch (Exception ex) + { + _onLog?.Invoke($"UAKino parse player error: {ex.Message}"); + return null; + } + } + + private List ParsePlaylistHtml(string html) + { + var items = new List(); + var doc = new HtmlDocument(); + doc.LoadHtml(html); + + var nodes = doc.DocumentNode.SelectNodes("//li[@data-file]"); + if (nodes == null) + return items; + + foreach (var node in nodes) + { + string dataFile = node.GetAttributeValue("data-file", ""); + if (string.IsNullOrEmpty(dataFile)) + continue; + + string title = CleanText(node.InnerText); + string voice = node.GetAttributeValue("data-voice", ""); + + items.Add(new PlaylistItem + { + Title = string.IsNullOrEmpty(title) ? "Episode" : title, + Url = NormalizeUrl(dataFile), + Voice = voice + }); + } + + return items; + } + + private string BuildPlaylistUrl(string newsId) + { + long ts = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + return $"{_init.host}{PlaylistPath}?news_id={newsId}&xfield={PlaylistField}&time={ts}"; + } + + private static string ExtractNewsId(string href) + { + if (string.IsNullOrEmpty(href)) + return null; + + string tail = href.TrimEnd('/').Split('/').LastOrDefault(); + if (string.IsNullOrEmpty(tail)) + return null; + + string newsId = tail.Split('-')[0]; + return string.IsNullOrEmpty(newsId) ? null : newsId; + } + + private static string ExtractPlayerFile(string html) + { + var match = Regex.Match(html, "file\\s*:\\s*['\"]([^'\"]+)['\"]", RegexOptions.IgnoreCase); + if (match.Success) + { + string value = match.Groups[1].Value.Trim(); + if (!value.StartsWith("[", StringComparison.Ordinal)) + return value; + } + + var sourceMatch = Regex.Match(html, "]+src=['\"]([^'\"]+)['\"]", RegexOptions.IgnoreCase); + if (sourceMatch.Success) + return sourceMatch.Groups[1].Value; + + var m3u8Match = Regex.Match(html, "(https?://[^\"'\\s>]+\\.m3u8[^\"'\\s>]*)", RegexOptions.IgnoreCase); + if (m3u8Match.Success) + return m3u8Match.Groups[1].Value; + + return null; + } + + private List ExtractSubtitles(string html) + { + var subtitles = new List(); + var match = Regex.Match(html, "subtitle\\s*:\\s*['\"]([^'\"]+)['\"]", RegexOptions.IgnoreCase); + if (!match.Success) + return subtitles; + + string value = match.Groups[1].Value.Trim(); + if (string.IsNullOrEmpty(value)) + return subtitles; + + if (value.StartsWith("[", StringComparison.Ordinal) && value.Contains(']')) + { + int endIdx = value.LastIndexOf(']'); + string label = value.Substring(1, endIdx - 1).Trim(); + string url = value[(endIdx + 1)..].Trim(); + url = NormalizeUrl(url); + if (!string.IsNullOrEmpty(url)) + subtitles.Add(new SubtitleInfo { Lang = string.IsNullOrEmpty(label) ? "unknown" : label, Url = url }); + } + else if (value.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + subtitles.Add(new SubtitleInfo { Lang = "unknown", Url = value }); + } + + return subtitles; + } + + private string NormalizeUrl(string url) + { + if (string.IsNullOrEmpty(url)) + return string.Empty; + + if (url.StartsWith("//")) + return $"https:{url}"; + + if (url.StartsWith("/")) + return $"{_init.host}{url}"; + + return url; + } + + private static bool LooksLikeDirectStream(string url) + { + return url.Contains(".m3u8", StringComparison.OrdinalIgnoreCase) || url.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase); + } + + private static bool IsBlacklisted(string url) + { + return Regex.IsMatch(url ?? string.Empty, BlacklistRegex, RegexOptions.IgnoreCase); + } + + private static bool IsSeriesUrl(string url) + { + return url.Contains("/seriesss/") || url.Contains("/anime-series/") || url.Contains("/cartoonseries/"); + } + + private static bool IsMovieUrl(string url) + { + return url.Contains("/filmy/") || url.Contains("/anime-solo/") || url.Contains("/features/"); + } + + private string ExtractPoster(HtmlNode node) + { + var img = node.SelectSingleNode(".//img"); + if (img == null) + return string.Empty; + + string src = img.GetAttributeValue("src", ""); + if (string.IsNullOrEmpty(src)) + src = img.GetAttributeValue("data-src", ""); + + return NormalizeUrl(src); + } + + private static string CleanText(string value) + { + if (string.IsNullOrEmpty(value)) + return string.Empty; + + return HtmlEntity.DeEntitize(value).Trim(); + } + + private static int? ExtractEpisodeNumber(string title) + { + if (string.IsNullOrEmpty(title)) + return null; + + var match = Regex.Match(title, @"(\d+)"); + if (match.Success && int.TryParse(match.Groups[1].Value, out int number)) + return number; + + 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); + } + + public static int? TryParseEpisodeNumber(string title) + { + return ExtractEpisodeNumber(title); + } + } +} diff --git a/UAKino/manifest.json b/UAKino/manifest.json new file mode 100644 index 0000000..d4cb417 --- /dev/null +++ b/UAKino/manifest.json @@ -0,0 +1,6 @@ +{ + "enable": true, + "version": 2, + "initspace": "UAKino.ModInit", + "online": "UAKino.OnlineApi" +}