diff --git a/.gitignore b/.gitignore index 7799ab9..8f4dd64 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,9 @@ /.idea/ /AIDocumentation/ -/Lampac/ +/LampaC/ +/BanderaBackend/ /Kinovezha/ /.clinerules/moduls.md /.clinerules/uaflix-optimization.md /.clinerules/ -/.qodo/ +/.qodo/ \ No newline at end of file diff --git a/AnimeON/AnimeONInvoke.cs b/AnimeON/AnimeONInvoke.cs index 4f89bfa..f268c43 100644 --- a/AnimeON/AnimeONInvoke.cs +++ b/AnimeON/AnimeONInvoke.cs @@ -150,6 +150,82 @@ namespace AnimeON return null; } + public async Task ParseAshdiPage(string url) + { + try + { + var headers = new List() + { + new HeadersModel("User-Agent", "Mozilla/5.0"), + new HeadersModel("Referer", _init.host) + }; + + _onLog($"AnimeON: using proxy {_proxyManager.CurrentProxyIp} for {url}"); + string html = await Http.Get(url, headers: headers, proxy: _proxyManager.Get()); + if (string.IsNullOrEmpty(html)) + return null; + + var match = System.Text.RegularExpressions.Regex.Match(html, @"file:\s*""([^""]+)"""); + if (match.Success) + { + return match.Groups[1].Value; + } + } + catch (Exception ex) + { + _onLog($"AnimeON ParseAshdiPage error: {ex.Message}"); + } + + return null; + } + + public async Task ResolveEpisodeStream(int episodeId) + { + try + { + string url = $"{_init.host}/api/player/{episodeId}/episode"; + _onLog($"AnimeON: using proxy {_proxyManager.CurrentProxyIp} for {url}"); + string json = await Http.Get(url, headers: new List() { new HeadersModel("User-Agent", "Mozilla/5.0"), new HeadersModel("Referer", _init.host) }, proxy: _proxyManager.Get()); + if (string.IsNullOrEmpty(json)) + return null; + + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + if (root.TryGetProperty("fileUrl", out var fileProp)) + { + string fileUrl = fileProp.GetString(); + if (!string.IsNullOrEmpty(fileUrl)) + return fileUrl; + } + + if (root.TryGetProperty("videoUrl", out var videoProp)) + { + string videoUrl = videoProp.GetString(); + return await ResolveVideoUrl(videoUrl); + } + } + catch (Exception ex) + { + _onLog($"AnimeON ResolveEpisodeStream error: {ex.Message}"); + } + + return null; + } + + public async Task ResolveVideoUrl(string url) + { + if (string.IsNullOrEmpty(url)) + return null; + + if (url.Contains("moonanime.art")) + return await ParseMoonAnimePage(url); + + if (url.Contains("ashdi.vip/vod")) + return await ParseAshdiPage(url); + + return url; + } + 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) @@ -230,4 +306,4 @@ namespace AnimeON } } } -} \ No newline at end of file +} diff --git a/AnimeON/Controller.cs b/AnimeON/Controller.cs index b17f787..b376cb1 100644 --- a/AnimeON/Controller.cs +++ b/AnimeON/Controller.cs @@ -99,18 +99,25 @@ namespace AnimeON.Controllers string episodeStr = ep.Number.ToString(); string streamLink = !string.IsNullOrEmpty(ep.Hls) ? ep.Hls : ep.VideoUrl; + bool needsResolve = selectedVoiceInfo.PlayerType == "moon" || selectedVoiceInfo.PlayerType == "ashdi"; + + if (string.IsNullOrEmpty(streamLink) && ep.EpisodeId > 0) + { + string callUrl = $"{host}/animeon/play?episode_id={ep.EpisodeId}"; + episode_tpl.Append(episodeName, title ?? original_title, seasonStr, episodeStr, accsArgs(callUrl), "call"); + continue; + } + if (string.IsNullOrEmpty(streamLink)) continue; - if (selectedVoiceInfo.PlayerType == "moon") + if (needsResolve || streamLink.Contains("moonanime.art") || streamLink.Contains("ashdi.vip/vod")) { - // method=call з accsArgs(callUrl) string callUrl = $"{host}/animeon/play?url={HttpUtility.UrlEncode(streamLink)}"; episode_tpl.Append(episodeName, title ?? original_title, seasonStr, episodeStr, accsArgs(callUrl), "call"); } else { - // Пряме відтворення через HostStreamProxy(init, accsArgs(streamLink)) string playUrl = HostStreamProxy(init, accsArgs(streamLink)); episode_tpl.Append(episodeName, title ?? original_title, seasonStr, episodeStr, playUrl); } @@ -158,7 +165,8 @@ namespace AnimeON.Controllers string translationName = $"[{player.Name}] {fundub.Fundub.Name}"; - if (player.Name?.ToLower() == "moon" && streamLink.Contains("moonanime.art/iframe/")) + bool needsResolve = player.Name?.ToLower() == "moon" || player.Name?.ToLower() == "ashdi"; + if (needsResolve || streamLink.Contains("moonanime.art/iframe/") || streamLink.Contains("ashdi.vip/vod")) { string callUrl = $"{host}/animeon/play?url={HttpUtility.UrlEncode(streamLink)}"; tpl.Append(translationName, accsArgs(callUrl), "call"); @@ -271,30 +279,40 @@ namespace AnimeON.Controllers } [HttpGet("animeon/play")] - public async Task Play(string url) + public async Task Play(string url, int episode_id = 0, string title = null) { - if (string.IsNullOrEmpty(url)) - { - OnLog("AnimeON Play: empty url"); - return OnError("animeon", proxyManager); - } - var init = await loadKit(ModInit.AnimeON); if (!init.enable) return Forbid(); var invoke = new AnimeONInvoke(init, hybridCache, OnLog, proxyManager); - OnLog($"AnimeON Play: url={url}"); - string streamLink = await invoke.ParseMoonAnimePage(url); + OnLog($"AnimeON Play: url={url}, episode_id={episode_id}"); - if (string.IsNullOrEmpty(streamLink)) + string streamLink = null; + if (episode_id > 0) { - OnLog("AnimeON Play: cannot extract stream from iframe"); + streamLink = await invoke.ResolveEpisodeStream(episode_id); + } + else if (!string.IsNullOrEmpty(url)) + { + streamLink = await invoke.ResolveVideoUrl(url); + } + else + { + OnLog("AnimeON Play: empty url"); return OnError("animeon", proxyManager); } - OnLog("AnimeON Play: redirect to proxied stream"); - return Redirect(HostStreamProxy(init, accsArgs(streamLink))); + if (string.IsNullOrEmpty(streamLink)) + { + OnLog("AnimeON Play: cannot extract stream"); + return OnError("animeon", proxyManager); + } + + string streamUrl = HostStreamProxy(init, accsArgs(streamLink)); + string jsonResult = $"{{\"method\":\"play\",\"url\":\"{streamUrl}\",\"title\":\"{title ?? string.Empty}\"}}"; + OnLog("AnimeON Play: return call JSON"); + return Content(jsonResult, "application/json; charset=utf-8"); } } } diff --git a/Bamboo/Bamboo.csproj b/Bamboo/Bamboo.csproj new file mode 100644 index 0000000..1fbe365 --- /dev/null +++ b/Bamboo/Bamboo.csproj @@ -0,0 +1,15 @@ + + + + net9.0 + library + true + + + + + ..\..\Shared.dll + + + + diff --git a/Bamboo/BambooInvoke.cs b/Bamboo/BambooInvoke.cs new file mode 100644 index 0000000..b8ada27 --- /dev/null +++ b/Bamboo/BambooInvoke.cs @@ -0,0 +1,324 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Web; +using Bamboo.Models; +using HtmlAgilityPack; +using Shared; +using Shared.Engine; +using Shared.Models; +using Shared.Models.Online.Settings; + +namespace Bamboo +{ + public class BambooInvoke + { + private readonly OnlinesSettings _init; + private readonly HybridCache _hybridCache; + private readonly Action _onLog; + private readonly ProxyManager _proxyManager; + + public BambooInvoke(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) + { + string query = !string.IsNullOrEmpty(title) ? title : original_title; + if (string.IsNullOrEmpty(query)) + return null; + + string memKey = $"Bamboo:search:{query}"; + if (_hybridCache.TryGetValue(memKey, out List cached)) + return cached; + + 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($"Bamboo search: {searchUrl}"); + string html = await Http.Get(searchUrl, headers: headers, proxy: _proxyManager.Get()); + if (string.IsNullOrEmpty(html)) + return null; + + var doc = new HtmlDocument(); + doc.LoadHtml(html); + + var results = new List(); + var nodes = doc.DocumentNode.SelectNodes("//li[contains(@class,'slide-item')]"); + if (nodes != null) + { + foreach (var node in nodes) + { + string itemTitle = CleanText(node.SelectSingleNode(".//h6")?.InnerText); + string href = ExtractHref(node); + string poster = ExtractPoster(node); + + if (string.IsNullOrEmpty(itemTitle) || string.IsNullOrEmpty(href)) + continue; + + results.Add(new SearchResult + { + Title = itemTitle, + Url = href, + Poster = poster + }); + } + } + + if (results.Count > 0) + _hybridCache.Set(memKey, results, cacheTime(20, init: _init)); + + return results; + } + catch (Exception ex) + { + _onLog?.Invoke($"Bamboo search error: {ex.Message}"); + return null; + } + } + + public async Task GetSeriesEpisodes(string href) + { + if (string.IsNullOrEmpty(href)) + return null; + + string memKey = $"Bamboo:series:{href}"; + if (_hybridCache.TryGetValue(memKey, out SeriesEpisodes cached)) + return cached; + + try + { + var headers = new List() + { + new HeadersModel("User-Agent", "Mozilla/5.0"), + new HeadersModel("Referer", _init.host) + }; + + _onLog?.Invoke($"Bamboo series 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 result = new SeriesEpisodes(); + bool foundBlocks = false; + + var blocks = doc.DocumentNode.SelectNodes("//div[contains(@class,'mt-4')]"); + if (blocks != null) + { + foreach (var block in blocks) + { + string header = CleanText(block.SelectSingleNode(".//h3[contains(@class,'my-4')]")?.InnerText); + var episodes = ParseEpisodeSpans(block); + if (episodes.Count == 0) + continue; + + foundBlocks = true; + if (!string.IsNullOrEmpty(header) && header.Contains("Субтитри", StringComparison.OrdinalIgnoreCase)) + { + result.Sub.AddRange(episodes); + } + else if (!string.IsNullOrEmpty(header) && header.Contains("Озвучення", StringComparison.OrdinalIgnoreCase)) + { + result.Dub.AddRange(episodes); + } + } + } + + if (!foundBlocks || (result.Sub.Count == 0 && result.Dub.Count == 0)) + { + var fallback = ParseEpisodeSpans(doc.DocumentNode); + if (fallback.Count > 0) + result.Dub.AddRange(fallback); + } + + if (result.Sub.Count == 0) + { + var fallback = ParseEpisodeSpans(doc.DocumentNode); + if (fallback.Count > 0) + result.Sub.AddRange(fallback); + } + + _hybridCache.Set(memKey, result, cacheTime(30, init: _init)); + return result; + } + catch (Exception ex) + { + _onLog?.Invoke($"Bamboo series error: {ex.Message}"); + return null; + } + } + + public async Task> GetMovieStreams(string href) + { + if (string.IsNullOrEmpty(href)) + return null; + + string memKey = $"Bamboo:movie:{href}"; + if (_hybridCache.TryGetValue(memKey, out List cached)) + return cached; + + try + { + var headers = new List() + { + new HeadersModel("User-Agent", "Mozilla/5.0"), + new HeadersModel("Referer", _init.host) + }; + + _onLog?.Invoke($"Bamboo 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 streams = new List(); + var nodes = doc.DocumentNode.SelectNodes("//span[contains(@class,'mr-3') and @data-file]"); + if (nodes != null) + { + foreach (var node in nodes) + { + string dataFile = node.GetAttributeValue("data-file", ""); + if (string.IsNullOrEmpty(dataFile)) + continue; + + string title = node.GetAttributeValue("data-title", ""); + title = string.IsNullOrEmpty(title) ? CleanText(node.InnerText) : title; + + streams.Add(new StreamInfo + { + Title = title, + Url = NormalizeUrl(dataFile) + }); + } + } + + if (streams.Count > 0) + _hybridCache.Set(memKey, streams, cacheTime(30, init: _init)); + + return streams; + } + catch (Exception ex) + { + _onLog?.Invoke($"Bamboo movie error: {ex.Message}"); + return null; + } + } + + private List ParseEpisodeSpans(HtmlNode scope) + { + var episodes = new List(); + var nodes = scope.SelectNodes(".//span[@data-file]"); + if (nodes == null) + return episodes; + + foreach (var node in nodes) + { + string dataFile = node.GetAttributeValue("data-file", ""); + if (string.IsNullOrEmpty(dataFile)) + continue; + + string title = node.GetAttributeValue("data-title", ""); + if (string.IsNullOrEmpty(title)) + title = CleanText(node.InnerText); + + int? episodeNum = ExtractEpisodeNumber(title); + + episodes.Add(new EpisodeInfo + { + Title = string.IsNullOrEmpty(title) ? "Episode" : title, + Url = NormalizeUrl(dataFile), + Episode = episodeNum + }); + } + + return episodes; + } + + private string ExtractHref(HtmlNode node) + { + var link = node.SelectSingleNode(".//a[contains(@class,'hover-buttons')]") + ?? node.SelectSingleNode(".//a[@href]"); + if (link == null) + return string.Empty; + + string href = link.GetAttributeValue("href", ""); + return NormalizeUrl(href); + } + + 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 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 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 value)) + return value; + + return null; + } + + private static string CleanText(string value) + { + if (string.IsNullOrEmpty(value)) + return string.Empty; + + return HtmlEntity.DeEntitize(value).Trim(); + } + + 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); + } + } +} diff --git a/Bamboo/Controller.cs b/Bamboo/Controller.cs new file mode 100644 index 0000000..34365af --- /dev/null +++ b/Bamboo/Controller.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Web; +using Bamboo.Models; +using Microsoft.AspNetCore.Mvc; +using Shared; +using Shared.Engine; +using Shared.Models; +using Shared.Models.Online.Settings; +using Shared.Models.Templates; + +namespace Bamboo.Controllers +{ + public class Controller : BaseOnlineController + { + ProxyManager proxyManager; + + public Controller() + { + proxyManager = new ProxyManager(ModInit.Bamboo); + } + + [HttpGet] + [Route("bamboo")] + 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, bool rjson = false, string href = null) + { + var init = await loadKit(ModInit.Bamboo); + if (!init.enable) + return Forbid(); + + var invoke = new BambooInvoke(init, hybridCache, OnLog, proxyManager); + + string itemUrl = href; + if (string.IsNullOrEmpty(itemUrl)) + { + var searchResults = await invoke.Search(title, original_title); + if (searchResults == null || searchResults.Count == 0) + return OnError("bamboo", proxyManager); + + if (searchResults.Count > 1) + { + var similar_tpl = new SimilarTpl(searchResults.Count); + foreach (var res in searchResults) + { + string link = $"{host}/bamboo?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 series = await invoke.GetSeriesEpisodes(itemUrl); + if (series == null || (series.Sub.Count == 0 && series.Dub.Count == 0)) + return OnError("bamboo", proxyManager); + + var voice_tpl = new VoiceTpl(); + var episode_tpl = new EpisodeTpl(); + + var availableVoices = new List<(string key, string name, List episodes)>(); + if (series.Sub.Count > 0) + availableVoices.Add(("sub", "Субтитри", series.Sub)); + if (series.Dub.Count > 0) + availableVoices.Add(("dub", "Озвучення", series.Dub)); + + if (string.IsNullOrEmpty(t)) + t = availableVoices.First().key; + + foreach (var voice in availableVoices) + { + string voiceLink = $"{host}/bamboo?imdb_id={imdb_id}&kinopoisk_id={kinopoisk_id}&title={HttpUtility.UrlEncode(title)}&original_title={HttpUtility.UrlEncode(original_title)}&year={year}&serial=1&t={voice.key}&href={HttpUtility.UrlEncode(itemUrl)}"; + voice_tpl.Append(voice.name, voice.key == t, voiceLink); + } + + var selected = availableVoices.FirstOrDefault(v => v.key == t); + if (selected.episodes == null || selected.episodes.Count == 0) + return OnError("bamboo", proxyManager); + + int index = 1; + foreach (var ep in selected.episodes.OrderBy(e => e.Episode ?? int.MaxValue)) + { + int episodeNumber = ep.Episode ?? index; + string episodeName = string.IsNullOrEmpty(ep.Title) ? $"Епізод {episodeNumber}" : ep.Title; + string streamUrl = HostStreamProxy(init, accsArgs(ep.Url)); + episode_tpl.Append(episodeName, title ?? original_title, "1", episodeNumber.ToString("D2"), streamUrl); + 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 + { + var streams = await invoke.GetMovieStreams(itemUrl); + if (streams == null || streams.Count == 0) + return OnError("bamboo", proxyManager); + + var movie_tpl = new MovieTpl(title, original_title); + for (int i = 0; i < streams.Count; i++) + { + var stream = streams[i]; + string label = !string.IsNullOrEmpty(stream.Title) ? stream.Title : $"Варіант {i + 1}"; + string streamUrl = HostStreamProxy(init, accsArgs(stream.Url)); + movie_tpl.Append(label, streamUrl); + } + + return rjson ? Content(movie_tpl.ToJson(), "application/json; charset=utf-8") : Content(movie_tpl.ToHtml(), "text/html; charset=utf-8"); + } + } + } +} diff --git a/Bamboo/ModInit.cs b/Bamboo/ModInit.cs new file mode 100644 index 0000000..d7994d5 --- /dev/null +++ b/Bamboo/ModInit.cs @@ -0,0 +1,35 @@ +using Shared; +using Shared.Engine; +using Shared.Models.Online.Settings; +using Shared.Models.Module; + +namespace Bamboo +{ + public class ModInit + { + public static OnlinesSettings Bamboo; + + /// + /// модуль загружен + /// + public static void loaded(InitspaceModel initspace) + { + Bamboo = new OnlinesSettings("Bamboo", "https://bambooua.com", streamproxy: false, useproxy: false) + { + displayname = "BambooUA", + displayindex = 0, + proxy = new Shared.Models.Base.ProxySettings() + { + useAuth = true, + username = "", + password = "", + list = new string[] { "socks5://ip:port" } + } + }; + Bamboo = ModuleInvoke.Conf("Bamboo", Bamboo).ToObject(); + + // Виводити "уточнити пошук" + AppInit.conf.online.with_search.Add("bamboo"); + } + } +} diff --git a/Bamboo/Models/BambooModels.cs b/Bamboo/Models/BambooModels.cs new file mode 100644 index 0000000..af99cb7 --- /dev/null +++ b/Bamboo/Models/BambooModels.cs @@ -0,0 +1,30 @@ +using System.Collections.Generic; + +namespace Bamboo.Models +{ + public class SearchResult + { + public string Title { get; set; } + public string Url { get; set; } + public string Poster { get; set; } + } + + public class EpisodeInfo + { + public string Title { get; set; } + public string Url { get; set; } + public int? Episode { get; set; } + } + + public class StreamInfo + { + public string Title { get; set; } + public string Url { get; set; } + } + + public class SeriesEpisodes + { + public List Sub { get; set; } = new(); + public List Dub { get; set; } = new(); + } +} diff --git a/Bamboo/OnlineApi.cs b/Bamboo/OnlineApi.cs new file mode 100644 index 0000000..5becaac --- /dev/null +++ b/Bamboo/OnlineApi.cs @@ -0,0 +1,25 @@ +using Shared.Models.Base; +using System.Collections.Generic; + +namespace Bamboo +{ + 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.Bamboo; + if (init.enable && !init.rip) + { + string url = init.overridehost; + if (string.IsNullOrEmpty(url)) + url = $"{host}/bamboo"; + + online.Add((init.displayname, url, "bamboo", init.displayindex)); + } + + return online; + } + } +} diff --git a/Bamboo/manifest.json b/Bamboo/manifest.json new file mode 100644 index 0000000..933863e --- /dev/null +++ b/Bamboo/manifest.json @@ -0,0 +1,6 @@ +{ + "enable": true, + "version": 2, + "initspace": "Bamboo.ModInit", + "online": "Bamboo.OnlineApi" +} diff --git a/README.md b/README.md index 2cefd2b..5b6002f 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,11 @@ # Ukraine online source for Lampac - [x] AnimeON -- [x] AniHUB -- [ ] BambooUA +- [x] [RIP] AniHUB +- [x] BambooUA - [x] CikavaIdeya -- [ ] KinoTron -- [ ] KinoVezha -- [ ] KlonTV +- [x] StarLight +- [x] UAKino - [x] UAFlix - [x] UATuTFun - [x] Unimay @@ -42,6 +41,9 @@ Create or update the module/repository.yaml file - CikavaIdeya - Uaflix - UaTUT + - Bamboo + - UAKino + - StarLight ``` branch - optional, default main @@ -67,4 +69,4 @@ modules - optional, if not specified, all modules from the repository will be in }, "displayindex": 1 } -``` \ No newline at end of file +``` diff --git a/StarLight/Controller.cs b/StarLight/Controller.cs new file mode 100644 index 0000000..7e1ce59 --- /dev/null +++ b/StarLight/Controller.cs @@ -0,0 +1,136 @@ +using System; +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 StarLight.Models; + +namespace StarLight.Controllers +{ + public class Controller : BaseOnlineController + { + ProxyManager proxyManager; + + public Controller() + { + proxyManager = new ProxyManager(ModInit.StarLight); + } + + [HttpGet] + [Route("starlight")] + 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, int s = -1, bool rjson = false, string href = null) + { + var init = await loadKit(ModInit.StarLight); + if (!init.enable) + return Forbid(); + + var invoke = new StarLightInvoke(init, hybridCache, OnLog, proxyManager); + + string itemUrl = href; + if (string.IsNullOrEmpty(itemUrl)) + { + var searchResults = await invoke.Search(title, original_title); + if (searchResults == null || searchResults.Count == 0) + return OnError("starlight", proxyManager); + + if (searchResults.Count > 1) + { + var similar_tpl = new SimilarTpl(searchResults.Count); + foreach (var res in searchResults) + { + string link = $"{host}/starlight?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.Href)}"; + similar_tpl.Append(res.Title, string.Empty, string.Empty, link, string.Empty); + } + + return rjson ? Content(similar_tpl.ToJson(), "application/json; charset=utf-8") : Content(similar_tpl.ToHtml(), "text/html; charset=utf-8"); + } + + itemUrl = searchResults[0].Href; + } + + var project = await invoke.GetProject(itemUrl); + if (project == null) + return OnError("starlight", proxyManager); + + if (serial == 1 && project.Seasons.Count > 0) + { + if (s == -1) + { + var season_tpl = new SeasonTpl(project.Seasons.Count); + for (int i = 0; i < project.Seasons.Count; i++) + { + var season = project.Seasons[i]; + string seasonName = string.IsNullOrEmpty(season.Title) ? $"Сезон {i + 1}" : season.Title; + string link = $"{host}/starlight?imdb_id={imdb_id}&kinopoisk_id={kinopoisk_id}&title={HttpUtility.UrlEncode(title)}&original_title={HttpUtility.UrlEncode(original_title)}&year={year}&serial=1&s={i}&href={HttpUtility.UrlEncode(itemUrl)}"; + season_tpl.Append(seasonName, link, i.ToString()); + } + + return rjson ? Content(season_tpl.ToJson(), "application/json; charset=utf-8") : Content(season_tpl.ToHtml(), "text/html; charset=utf-8"); + } + + if (s < 0 || s >= project.Seasons.Count) + return OnError("starlight", proxyManager); + + string seasonSlug = project.Seasons[s].Slug; + var episodes = invoke.GetEpisodes(project, seasonSlug); + if (episodes == null || episodes.Count == 0) + return OnError("starlight", proxyManager); + + var episode_tpl = new EpisodeTpl(); + int index = 1; + foreach (var ep in episodes) + { + if (string.IsNullOrEmpty(ep.Hash)) + continue; + + string episodeName = string.IsNullOrEmpty(ep.Title) ? $"Епізод {index}" : ep.Title; + string callUrl = $"{host}/starlight/play?hash={HttpUtility.UrlEncode(ep.Hash)}&title={HttpUtility.UrlEncode(title ?? original_title)}"; + episode_tpl.Append(episodeName, title ?? original_title, (s + 1).ToString(), index.ToString("D2"), accsArgs(callUrl), "call"); + index++; + } + + return rjson ? Content(episode_tpl.ToJson(), "application/json; charset=utf-8") : Content(episode_tpl.ToHtml(), "text/html; charset=utf-8"); + } + else + { + string hash = project.Hash; + if (string.IsNullOrEmpty(hash) && project.Episodes.Count > 0) + hash = project.Episodes.FirstOrDefault(e => !string.IsNullOrEmpty(e.Hash))?.Hash; + + if (string.IsNullOrEmpty(hash)) + return OnError("starlight", proxyManager); + + string callUrl = $"{host}/starlight/play?hash={HttpUtility.UrlEncode(hash)}&title={HttpUtility.UrlEncode(title ?? original_title)}"; + var movie_tpl = new MovieTpl(title, original_title, 1); + movie_tpl.Append(string.IsNullOrEmpty(title) ? "StarLight" : 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("starlight/play")] + async public Task Play(string hash, string title) + { + if (string.IsNullOrEmpty(hash)) + return OnError("starlight", proxyManager); + + var init = await loadKit(ModInit.StarLight); + if (!init.enable) + return Forbid(); + + var invoke = new StarLightInvoke(init, hybridCache, OnLog, proxyManager); + var result = await invoke.ResolveStream(hash); + if (result == null || string.IsNullOrEmpty(result.Stream)) + return OnError("starlight", proxyManager); + + string streamUrl = HostStreamProxy(init, accsArgs(result.Stream), proxy: proxyManager.Get()); + string jsonResult = $"{{\"method\":\"play\",\"url\":\"{streamUrl}\",\"title\":\"{title ?? result.Name ?? ""}\"}}"; + return Content(jsonResult, "application/json; charset=utf-8"); + } + } +} diff --git a/StarLight/ModInit.cs b/StarLight/ModInit.cs new file mode 100644 index 0000000..ac0df4b --- /dev/null +++ b/StarLight/ModInit.cs @@ -0,0 +1,35 @@ +using Shared; +using Shared.Engine; +using Shared.Models.Online.Settings; +using Shared.Models.Module; + +namespace StarLight +{ + public class ModInit + { + public static OnlinesSettings StarLight; + + /// + /// модуль загружен + /// + public static void loaded(InitspaceModel initspace) + { + StarLight = new OnlinesSettings("StarLight", "https://tp-back.starlight.digital", streamproxy: false, useproxy: false) + { + displayname = "StarLight", + displayindex = 0, + proxy = new Shared.Models.Base.ProxySettings() + { + useAuth = true, + username = "", + password = "", + list = new string[] { "socks5://ip:port" } + } + }; + StarLight = ModuleInvoke.Conf("StarLight", StarLight).ToObject(); + + // Виводити "уточнити пошук" + AppInit.conf.online.with_search.Add("starlight"); + } + } +} diff --git a/StarLight/Models/StarLightModels.cs b/StarLight/Models/StarLightModels.cs new file mode 100644 index 0000000..90142aa --- /dev/null +++ b/StarLight/Models/StarLightModels.cs @@ -0,0 +1,47 @@ +using System.Collections.Generic; + +namespace StarLight.Models +{ + public class SearchResult + { + public string Title { get; set; } + public string Type { get; set; } + public string Href { get; set; } + public string Channel { get; set; } + public string Project { get; set; } + } + + public class SeasonInfo + { + public string Title { get; set; } + public string Slug { get; set; } + } + + public class EpisodeInfo + { + public string Title { get; set; } + public string Hash { get; set; } + public string VideoSlug { get; set; } + public string Date { get; set; } + public string SeasonSlug { get; set; } + } + + public class ProjectInfo + { + public string Title { get; set; } + public string Description { get; set; } + public string Poster { get; set; } + public string Hash { get; set; } + public string Type { get; set; } + public string Channel { get; set; } + public List Seasons { get; set; } = new(); + public List Episodes { get; set; } = new(); + } + + public class StreamResult + { + public string Stream { get; set; } + public string Poster { get; set; } + public string Name { get; set; } + } +} diff --git a/StarLight/OnlineApi.cs b/StarLight/OnlineApi.cs new file mode 100644 index 0000000..ce3b4c3 --- /dev/null +++ b/StarLight/OnlineApi.cs @@ -0,0 +1,25 @@ +using Shared.Models.Base; +using System.Collections.Generic; + +namespace StarLight +{ + 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.StarLight; + if (init.enable && !init.rip) + { + string url = init.overridehost; + if (string.IsNullOrEmpty(url)) + url = $"{host}/starlight"; + + online.Add((init.displayname, url, "starlight", init.displayindex)); + } + + return online; + } + } +} diff --git a/StarLight/StarLight.csproj b/StarLight/StarLight.csproj new file mode 100644 index 0000000..1fbe365 --- /dev/null +++ b/StarLight/StarLight.csproj @@ -0,0 +1,15 @@ + + + + net9.0 + library + true + + + + + ..\..\Shared.dll + + + + diff --git a/StarLight/StarLightInvoke.cs b/StarLight/StarLightInvoke.cs new file mode 100644 index 0000000..771d853 --- /dev/null +++ b/StarLight/StarLightInvoke.cs @@ -0,0 +1,255 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Threading.Tasks; +using System.Web; +using Shared; +using Shared.Engine; +using Shared.Models; +using Shared.Models.Online.Settings; +using StarLight.Models; + +namespace StarLight +{ + public class StarLightInvoke + { + private const string PlayerApi = "https://vcms-api2.starlight.digital/player-api"; + private const string PlayerReferer = "https://teleportal.ua/"; + private const string Language = "ua"; + private readonly OnlinesSettings _init; + private readonly HybridCache _hybridCache; + private readonly Action _onLog; + private readonly ProxyManager _proxyManager; + + public StarLightInvoke(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) + { + string query = !string.IsNullOrEmpty(title) ? title : original_title; + if (string.IsNullOrEmpty(query)) + return null; + + string memKey = $"StarLight:search:{query}"; + if (_hybridCache.TryGetValue(memKey, out List cached)) + return cached; + + string url = $"{_init.host}/{Language}/live-search?q={HttpUtility.UrlEncode(query)}"; + var headers = new List() + { + new HeadersModel("User-Agent", "Mozilla/5.0"), + new HeadersModel("Referer", _init.host) + }; + + try + { + _onLog?.Invoke($"StarLight search: {url}"); + string payload = await Http.Get(url, headers: headers, proxy: _proxyManager.Get()); + if (string.IsNullOrEmpty(payload)) + return null; + + var results = new List(); + using var document = JsonDocument.Parse(payload); + if (document.RootElement.ValueKind == JsonValueKind.Array) + { + foreach (var item in document.RootElement.EnumerateArray()) + { + string typeSlug = item.TryGetProperty("typeSlug", out var typeProp) ? typeProp.GetString() : null; + string channelSlug = item.TryGetProperty("channelSlug", out var channelProp) ? channelProp.GetString() : null; + string projectSlug = item.TryGetProperty("projectSlug", out var projectProp) ? projectProp.GetString() : null; + if (string.IsNullOrEmpty(typeSlug) || string.IsNullOrEmpty(channelSlug) || string.IsNullOrEmpty(projectSlug)) + continue; + + string href = $"{_init.host}/{Language}/{typeSlug}/{channelSlug}/{projectSlug}"; + results.Add(new SearchResult + { + Title = item.TryGetProperty("title", out var titleProp) ? titleProp.GetString() : null, + Type = typeSlug, + Href = href, + Channel = channelSlug, + Project = projectSlug + }); + } + } + + if (results.Count > 0) + _hybridCache.Set(memKey, results, cacheTime(15, init: _init)); + + return results; + } + catch (Exception ex) + { + _onLog?.Invoke($"StarLight search error: {ex.Message}"); + return null; + } + } + + public async Task GetProject(string href) + { + if (string.IsNullOrEmpty(href)) + return null; + + string memKey = $"StarLight:project:{href}"; + if (_hybridCache.TryGetValue(memKey, out ProjectInfo cached)) + return cached; + + var headers = new List() + { + new HeadersModel("User-Agent", "Mozilla/5.0"), + new HeadersModel("Referer", _init.host) + }; + + try + { + _onLog?.Invoke($"StarLight project: {href}"); + string payload = await Http.Get(href, headers: headers, proxy: _proxyManager.Get()); + if (string.IsNullOrEmpty(payload)) + return null; + + using var document = JsonDocument.Parse(payload); + var root = document.RootElement; + + var project = new ProjectInfo + { + Title = root.TryGetProperty("title", out var titleProp) ? titleProp.GetString() : null, + Description = root.TryGetProperty("description", out var descProp) ? descProp.GetString() : null, + Poster = NormalizeImage(root.TryGetProperty("image", out var imageProp) ? imageProp.GetString() : null), + Hash = root.TryGetProperty("hash", out var hashProp) ? hashProp.GetString() : null, + Type = root.TryGetProperty("typeSlug", out var typeProp) ? typeProp.GetString() : null, + Channel = root.TryGetProperty("channelTitle", out var channelProp) ? channelProp.GetString() : null + }; + + if (root.TryGetProperty("seasonsGallery", out var seasonsProp) && seasonsProp.ValueKind == JsonValueKind.Array) + { + foreach (var season in seasonsProp.EnumerateArray()) + { + string seasonTitle = season.TryGetProperty("title", out var sTitle) ? sTitle.GetString() : null; + string seasonSlug = season.TryGetProperty("seasonSlug", out var sSlug) ? sSlug.GetString() : null; + project.Seasons.Add(new SeasonInfo { Title = seasonTitle, Slug = seasonSlug }); + + if (season.TryGetProperty("items", out var itemsProp) && itemsProp.ValueKind == JsonValueKind.Array) + { + foreach (var item in itemsProp.EnumerateArray()) + { + project.Episodes.Add(new EpisodeInfo + { + Title = item.TryGetProperty("title", out var eTitle) ? eTitle.GetString() : null, + Hash = item.TryGetProperty("hash", out var eHash) ? eHash.GetString() : null, + VideoSlug = item.TryGetProperty("videoSlug", out var eSlug) ? eSlug.GetString() : null, + Date = item.TryGetProperty("dateOfBroadcast", out var eDate) ? eDate.GetString() : (item.TryGetProperty("timeUploadVideo", out var eDate2) ? eDate2.GetString() : null), + SeasonSlug = seasonSlug + }); + } + } + } + } + + _hybridCache.Set(memKey, project, cacheTime(10, init: _init)); + return project; + } + catch (Exception ex) + { + _onLog?.Invoke($"StarLight project error: {ex.Message}"); + return null; + } + } + + public List GetEpisodes(ProjectInfo project, string seasonSlug) + { + if (project == null || project.Seasons.Count == 0) + return new List(); + + if (string.IsNullOrEmpty(seasonSlug)) + return project.Episodes; + + return project.Episodes.Where(e => e.SeasonSlug == seasonSlug).ToList(); + } + + public async Task ResolveStream(string hash) + { + if (string.IsNullOrEmpty(hash)) + return null; + + string url = $"{PlayerApi}/{hash}?referer={HttpUtility.UrlEncode(PlayerReferer)}&lang={Language}"; + var headers = new List() + { + new HeadersModel("User-Agent", "Mozilla/5.0"), + new HeadersModel("Referer", PlayerReferer) + }; + + try + { + _onLog?.Invoke($"StarLight stream: {url}"); + string payload = await Http.Get(url, headers: headers, proxy: _proxyManager.Get()); + if (string.IsNullOrEmpty(payload)) + return null; + + using var document = JsonDocument.Parse(payload); + var root = document.RootElement; + + string stream = null; + if (root.TryGetProperty("video", out var videoProp) && videoProp.ValueKind == JsonValueKind.Array) + { + var video = videoProp.EnumerateArray().FirstOrDefault(); + if (video.ValueKind != JsonValueKind.Undefined) + { + if (video.TryGetProperty("mediaHlsNoAdv", out var hlsNoAdv)) + stream = hlsNoAdv.GetString(); + if (string.IsNullOrEmpty(stream) && video.TryGetProperty("mediaHls", out var hls)) + stream = hls.GetString(); + if (string.IsNullOrEmpty(stream) && video.TryGetProperty("media", out var mediaProp) && mediaProp.ValueKind == JsonValueKind.Array) + { + var media = mediaProp.EnumerateArray().FirstOrDefault(); + if (media.TryGetProperty("url", out var mediaUrl)) + stream = mediaUrl.GetString(); + } + } + } + + if (string.IsNullOrEmpty(stream)) + return null; + + return new StreamResult + { + Stream = stream, + Poster = root.TryGetProperty("poster", out var posterProp) ? posterProp.GetString() : null, + Name = root.TryGetProperty("name", out var nameProp) ? nameProp.GetString() : null + }; + } + catch (Exception ex) + { + _onLog?.Invoke($"StarLight stream error: {ex.Message}"); + return null; + } + } + + private string NormalizeImage(string path) + { + if (string.IsNullOrEmpty(path)) + return string.Empty; + + if (path.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + return path; + + return $"{_init.host}{path}"; + } + + 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); + } + } +} diff --git a/StarLight/manifest.json b/StarLight/manifest.json new file mode 100644 index 0000000..1b214ae --- /dev/null +++ b/StarLight/manifest.json @@ -0,0 +1,6 @@ +{ + "enable": true, + "version": 2, + "initspace": "StarLight.ModInit", + "online": "StarLight.OnlineApi" +} 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" +}