diff --git a/MoonAnime/ApnHelper.cs b/MoonAnime/ApnHelper.cs new file mode 100644 index 0000000..394a5bc --- /dev/null +++ b/MoonAnime/ApnHelper.cs @@ -0,0 +1,86 @@ +using Newtonsoft.Json.Linq; +using Shared.Models.Base; +using System; +using System.Web; + +namespace Shared.Engine +{ + public static class ApnHelper + { + public const string DefaultHost = "https://tut.im/proxy.php?url={encodeurl}"; + + public static bool TryGetInitConf(JObject conf, out bool enabled, out string host) + { + enabled = false; + host = null; + + if (conf == null) + return false; + + if (!conf.TryGetValue("apn", out var apnToken) || apnToken?.Type != JTokenType.Boolean) + return false; + + enabled = apnToken.Value(); + host = conf.Value("apn_host"); + return true; + } + + public static void ApplyInitConf(bool enabled, string host, BaseSettings init) + { + if (init == null) + return; + + if (!enabled) + { + init.apnstream = false; + init.apn = null; + return; + } + + if (string.IsNullOrWhiteSpace(host)) + host = DefaultHost; + + if (init.apn == null) + init.apn = new ApnConf(); + + init.apn.host = host; + init.apnstream = true; + } + + public static bool IsEnabled(BaseSettings init) + { + return init?.apnstream == true && !string.IsNullOrWhiteSpace(init?.apn?.host); + } + + public static bool IsAshdiUrl(string url) + { + return !string.IsNullOrEmpty(url) && + url.IndexOf("ashdi.vip", StringComparison.OrdinalIgnoreCase) >= 0; + } + + public static string WrapUrl(BaseSettings init, string url) + { + if (!IsEnabled(init)) + return url; + + return BuildUrl(init.apn.host, url); + } + + public static string BuildUrl(string host, string url) + { + if (string.IsNullOrEmpty(host) || string.IsNullOrEmpty(url)) + return url; + + if (host.Contains("{encodeurl}")) + return host.Replace("{encodeurl}", HttpUtility.UrlEncode(url)); + + if (host.Contains("{encode_uri}")) + return host.Replace("{encode_uri}", HttpUtility.UrlEncode(url)); + + if (host.Contains("{uri}")) + return host.Replace("{uri}", url); + + return $"{host.TrimEnd('/')}/{url}"; + } + } +} diff --git a/MoonAnime/Controller.cs b/MoonAnime/Controller.cs new file mode 100644 index 0000000..dd13a44 --- /dev/null +++ b/MoonAnime/Controller.cs @@ -0,0 +1,342 @@ +using Microsoft.AspNetCore.Mvc; +using MoonAnime.Models; +using Shared; +using Shared.Engine; +using Shared.Models; +using Shared.Models.Online.Settings; +using Shared.Models.Templates; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Web; + +namespace MoonAnime.Controllers +{ + public class Controller : BaseOnlineController + { + private readonly ProxyManager proxyManager; + + public Controller() : base(ModInit.Settings) + { + proxyManager = new ProxyManager(ModInit.MoonAnime); + } + + [HttpGet] + [Route("moonanime")] + public async 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 mal_id, string t, int s = -1, bool rjson = false, bool checksearch = false) + { + await UpdateService.ConnectAsync(host); + + var init = await loadKit(ModInit.MoonAnime); + if (!init.enable) + return Forbid(); + + var invoke = new MoonAnimeInvoke(init, hybridCache, OnLog, proxyManager); + + if (checksearch) + { + if (AppInit.conf?.online?.checkOnlineSearch != true) + return OnError("moonanime", proxyManager); + + var checkResults = await invoke.Search(imdb_id, mal_id, title, original_title, year); + if (checkResults != null && checkResults.Count > 0) + return Content("data-json=", "text/plain; charset=utf-8"); + + return OnError("moonanime", proxyManager); + } + + OnLog($"MoonAnime: title={title}, original_title={original_title}, imdb={imdb_id}, mal_id={mal_id}, serial={serial}, s={s}, t={t}"); + + var seasons = await invoke.Search(imdb_id, mal_id, title, original_title, year); + if (seasons == null || seasons.Count == 0) + return OnError("moonanime", proxyManager); + + bool isSeries = serial == 1; + MoonAnimeSeasonContent firstSeasonData = null; + + if (serial == -1) + { + firstSeasonData = await invoke.GetSeasonContent(seasons[0]); + if (firstSeasonData == null || firstSeasonData.Voices.Count == 0) + return OnError("moonanime", proxyManager); + + isSeries = firstSeasonData.IsSeries; + } + + if (isSeries) + { + return await RenderSerial(invoke, seasons, imdb_id, kinopoisk_id, title, original_title, year, mal_id, s, t, rjson); + } + + return await RenderMovie(invoke, seasons, title, original_title, firstSeasonData, rjson); + } + + [HttpGet("moonanime/play")] + public async Task Play(string file, string title = null) + { + await UpdateService.ConnectAsync(host); + + var init = await loadKit(ModInit.MoonAnime); + if (!init.enable) + return Forbid(); + + if (string.IsNullOrWhiteSpace(file)) + return OnError("moonanime", proxyManager); + + var invoke = new MoonAnimeInvoke(init, hybridCache, OnLog, proxyManager); + var streams = invoke.ParseStreams(file); + if (streams == null || streams.Count == 0) + return OnError("moonanime", proxyManager); + + if (streams.Count == 1) + { + string singleUrl = BuildStreamUrl(init, streams[0].Url); + string singleJson = VideoTpl.ToJson("play", singleUrl, title ?? string.Empty, quality: streams[0].Quality ?? "auto"); + return UpdateService.Validate(Content(singleJson, "application/json; charset=utf-8")); + } + + var streamQuality = new StreamQualityTpl(); + foreach (var stream in streams) + { + string streamUrl = BuildStreamUrl(init, stream.Url); + streamQuality.Append(streamUrl, stream.Quality); + } + + if (!streamQuality.Any()) + return OnError("moonanime", proxyManager); + + var first = streamQuality.Firts(); + string json = VideoTpl.ToJson("play", first.link, title ?? string.Empty, streamquality: streamQuality); + return UpdateService.Validate(Content(json, "application/json; charset=utf-8")); + } + + private async Task RenderSerial( + MoonAnimeInvoke invoke, + List seasons, + string imdbId, + long kinopoiskId, + string title, + string originalTitle, + int year, + string malId, + int selectedSeason, + string selectedVoice, + bool rjson) + { + var orderedSeasons = seasons + .Where(s => s != null && !string.IsNullOrWhiteSpace(s.Url)) + .OrderBy(s => s.SeasonNumber) + .ToList(); + + if (orderedSeasons.Count == 0) + return OnError("moonanime", proxyManager); + + if (selectedSeason == -1) + { + var seasonTpl = new SeasonTpl(orderedSeasons.Count); + foreach (var season in orderedSeasons) + { + int seasonNumber = season.SeasonNumber <= 0 ? 1 : season.SeasonNumber; + string seasonName = $"Сезон {seasonNumber}"; + string seasonLink = BuildIndexUrl(imdbId, kinopoiskId, title, originalTitle, year, 1, malId, seasonNumber, selectedVoice); + seasonTpl.Append(seasonName, seasonLink, seasonNumber); + } + + return rjson + ? Content(seasonTpl.ToJson(), "application/json; charset=utf-8") + : Content(seasonTpl.ToHtml(), "text/html; charset=utf-8"); + } + + var currentSeason = orderedSeasons.FirstOrDefault(s => s.SeasonNumber == selectedSeason) ?? orderedSeasons[0]; + var seasonData = await invoke.GetSeasonContent(currentSeason); + if (seasonData == null) + return OnError("moonanime", proxyManager); + + var voices = seasonData.Voices + .Where(v => v != null && v.Episodes != null && v.Episodes.Count > 0) + .ToList(); + + if (voices.Count == 0) + return OnError("moonanime", proxyManager); + + int activeVoiceIndex = ParseVoiceIndex(selectedVoice, voices.Count); + var voiceTpl = new VoiceTpl(voices.Count); + for (int i = 0; i < voices.Count; i++) + { + string voiceName = string.IsNullOrWhiteSpace(voices[i].Name) ? $"Озвучка {i + 1}" : voices[i].Name; + string voiceLink = BuildIndexUrl(imdbId, kinopoiskId, title, originalTitle, year, 1, malId, currentSeason.SeasonNumber, i.ToString()); + voiceTpl.Append(voiceName, i == activeVoiceIndex, voiceLink); + } + + var selectedVoiceData = voices[activeVoiceIndex]; + var episodes = selectedVoiceData.Episodes + .Where(e => e != null && !string.IsNullOrWhiteSpace(e.File)) + .OrderBy(e => e.Number <= 0 ? int.MaxValue : e.Number) + .ThenBy(e => e.Name) + .ToList(); + + if (episodes.Count == 0) + return OnError("moonanime", proxyManager); + + string displayTitle = !string.IsNullOrWhiteSpace(title) + ? title + : !string.IsNullOrWhiteSpace(originalTitle) + ? originalTitle + : "MoonAnime"; + + var episodeTpl = new EpisodeTpl(episodes.Count); + foreach (var episode in episodes) + { + int episodeNumber = episode.Number <= 0 ? 1 : episode.Number; + string episodeName = string.IsNullOrWhiteSpace(episode.Name) ? $"Епізод {episodeNumber}" : episode.Name; + string callUrl = $"{host}/moonanime/play?file={HttpUtility.UrlEncode(episode.File)}&title={HttpUtility.UrlEncode(displayTitle)}"; + episodeTpl.Append(episodeName, displayTitle, currentSeason.SeasonNumber.ToString(), episodeNumber.ToString(), accsArgs(callUrl), "call"); + } + + episodeTpl.Append(voiceTpl); + + return rjson + ? Content(episodeTpl.ToJson(), "application/json; charset=utf-8") + : Content(episodeTpl.ToHtml(), "text/html; charset=utf-8"); + } + + private async Task RenderMovie( + MoonAnimeInvoke invoke, + List seasons, + string title, + string originalTitle, + MoonAnimeSeasonContent firstSeasonData, + bool rjson) + { + var currentSeason = seasons + .Where(s => s != null && !string.IsNullOrWhiteSpace(s.Url)) + .OrderBy(s => s.SeasonNumber) + .FirstOrDefault(); + + if (currentSeason == null) + return OnError("moonanime", proxyManager); + + MoonAnimeSeasonContent seasonData = firstSeasonData; + if (seasonData == null || !string.Equals(seasonData.Url, currentSeason.Url, StringComparison.OrdinalIgnoreCase)) + seasonData = await invoke.GetSeasonContent(currentSeason); + + if (seasonData == null || seasonData.Voices.Count == 0) + return OnError("moonanime", proxyManager); + + string displayTitle = !string.IsNullOrWhiteSpace(title) + ? title + : !string.IsNullOrWhiteSpace(originalTitle) + ? originalTitle + : "MoonAnime"; + + var movieTpl = new MovieTpl(displayTitle, originalTitle); + int fallbackIndex = 1; + + foreach (var voice in seasonData.Voices) + { + if (voice == null) + continue; + + string file = !string.IsNullOrWhiteSpace(voice.MovieFile) + ? voice.MovieFile + : voice.Episodes?.FirstOrDefault(e => !string.IsNullOrWhiteSpace(e.File))?.File; + + if (string.IsNullOrWhiteSpace(file)) + continue; + + string voiceName = string.IsNullOrWhiteSpace(voice.Name) ? $"Озвучка {fallbackIndex}" : voice.Name; + string callUrl = $"{host}/moonanime/play?file={HttpUtility.UrlEncode(file)}&title={HttpUtility.UrlEncode(displayTitle)}"; + movieTpl.Append(voiceName, accsArgs(callUrl), "call"); + fallbackIndex++; + } + + if (movieTpl.IsEmpty) + return OnError("moonanime", proxyManager); + + return rjson + ? Content(movieTpl.ToJson(), "application/json; charset=utf-8") + : Content(movieTpl.ToHtml(), "text/html; charset=utf-8"); + } + + private string BuildIndexUrl(string imdbId, long kinopoiskId, string title, string originalTitle, int year, int serial, string malId, int season, string voice) + { + var url = new StringBuilder(); + url.Append($"{host}/moonanime?imdb_id={HttpUtility.UrlEncode(imdbId)}"); + url.Append($"&kinopoisk_id={kinopoiskId}"); + url.Append($"&title={HttpUtility.UrlEncode(title)}"); + url.Append($"&original_title={HttpUtility.UrlEncode(originalTitle)}"); + url.Append($"&year={year}"); + url.Append($"&serial={serial}"); + + if (!string.IsNullOrWhiteSpace(malId)) + url.Append($"&mal_id={HttpUtility.UrlEncode(malId)}"); + + if (season > 0) + url.Append($"&s={season}"); + + if (!string.IsNullOrWhiteSpace(voice)) + url.Append($"&t={HttpUtility.UrlEncode(voice)}"); + + return url.ToString(); + } + + private int ParseVoiceIndex(string voiceValue, int totalVoices) + { + if (totalVoices <= 0) + return 0; + + if (!int.TryParse(voiceValue, out int index)) + return 0; + + if (index < 0 || index >= totalVoices) + return 0; + + return index; + } + + private string BuildStreamUrl(OnlinesSettings init, string streamLink) + { + string link = StripLampacArgs(streamLink?.Trim()); + if (string.IsNullOrEmpty(link)) + return link; + + var headers = new List + { + new HeadersModel("User-Agent", "Mozilla/5.0"), + new HeadersModel("Referer", "https://moonanime.art/") + }; + + if (ApnHelper.IsEnabled(init)) + { + if (ModInit.ApnHostProvided) + return ApnHelper.WrapUrl(init, link); + + var noApn = (OnlinesSettings)init.Clone(); + noApn.apnstream = false; + noApn.apn = null; + return HostStreamProxy(noApn, link, headers: headers, proxy: proxyManager.Get()); + } + + return HostStreamProxy(init, link, headers: headers, proxy: proxyManager.Get()); + } + + private static string StripLampacArgs(string url) + { + if (string.IsNullOrEmpty(url)) + return url; + + string cleaned = Regex.Replace( + url, + @"([?&])(account_email|uid|nws_id)=[^&]*", + "$1", + RegexOptions.IgnoreCase + ); + + cleaned = cleaned.Replace("?&", "?").Replace("&&", "&").TrimEnd('?', '&'); + return cleaned; + } + } +} diff --git a/MoonAnime/ModInit.cs b/MoonAnime/ModInit.cs new file mode 100644 index 0000000..6be49a5 --- /dev/null +++ b/MoonAnime/ModInit.cs @@ -0,0 +1,194 @@ +using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Shared; +using Shared.Engine; +using Shared.Models.Module; +using Shared.Models.Online.Settings; +using System; +using System.Net.Http; +using System.Net.Mime; +using System.Net.Security; +using System.Security.Authentication; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace MoonAnime +{ + public class ModInit + { + public static double Version => 1.0; + + public static OnlinesSettings MoonAnime; + + public static bool ApnHostProvided; + + public static OnlinesSettings Settings + { + get => MoonAnime; + set => MoonAnime = value; + } + + /// + /// Модуль завантажено. + /// + public static void loaded(InitspaceModel initspace) + { + MoonAnime = new OnlinesSettings("MoonAnime", "https://moonanime.art", "https://apx.lme.isroot.in", streamproxy: false, useproxy: false) + { + displayname = "MoonAnime", + displayindex = 0, + proxy = new Shared.Models.Base.ProxySettings() + { + useAuth = true, + username = "", + password = "", + list = new string[] { "socks5://ip:port" } + } + }; + + var conf = ModuleInvoke.Conf("MoonAnime", MoonAnime) ?? JObject.FromObject(MoonAnime); + bool hasApn = ApnHelper.TryGetInitConf(conf, out bool apnEnabled, out string apnHost); + conf.Remove("apn"); + conf.Remove("apn_host"); + MoonAnime = conf.ToObject(); + + if (hasApn) + ApnHelper.ApplyInitConf(apnEnabled, apnHost, MoonAnime); + + ApnHostProvided = hasApn && apnEnabled && !string.IsNullOrWhiteSpace(apnHost); + if (hasApn && apnEnabled) + { + MoonAnime.streamproxy = false; + } + else if (MoonAnime.streamproxy) + { + MoonAnime.apnstream = false; + MoonAnime.apn = null; + } + + AppInit.conf.online.with_search.Add("moonanime"); + } + } + + public static class UpdateService + { + private static readonly string _connectUrl = "https://lmcuk.lampame.v6.rocks/stats"; + + private static ConnectResponse? Connect = null; + private static DateTime? _connectTime = null; + private static DateTime? _disconnectTime = null; + + private static readonly TimeSpan _resetInterval = TimeSpan.FromHours(4); + private static Timer? _resetTimer = null; + + private static readonly object _lock = new(); + + public static async Task ConnectAsync(string host, CancellationToken cancellationToken = default) + { + if (_connectTime is not null || Connect?.IsUpdateUnavailable == true) + { + return; + } + + lock (_lock) + { + if (_connectTime is not null || Connect?.IsUpdateUnavailable == true) + { + return; + } + + _connectTime = DateTime.UtcNow; + } + + try + { + using var handler = new SocketsHttpHandler + { + SslOptions = new SslClientAuthenticationOptions + { + RemoteCertificateValidationCallback = (_, _, _, _) => true, + EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13 + } + }; + + using var client = new HttpClient(handler); + client.Timeout = TimeSpan.FromSeconds(15); + + var request = new + { + Host = host, + Module = ModInit.Settings.plugin, + Version = ModInit.Version, + }; + + var requestJson = JsonConvert.SerializeObject(request, Formatting.None); + var requestContent = new StringContent(requestJson, Encoding.UTF8, MediaTypeNames.Application.Json); + + var response = await client + .PostAsync(_connectUrl, requestContent, cancellationToken) + .ConfigureAwait(false); + + response.EnsureSuccessStatusCode(); + + if (response.Content.Headers.ContentLength > 0) + { + var responseText = await response.Content + .ReadAsStringAsync(cancellationToken) + .ConfigureAwait(false); + + Connect = JsonConvert.DeserializeObject(responseText); + } + + lock (_lock) + { + _resetTimer?.Dispose(); + _resetTimer = null; + + if (Connect?.IsUpdateUnavailable != true) + { + _resetTimer = new Timer(ResetConnectTime, null, _resetInterval, Timeout.InfiniteTimeSpan); + } + else + { + _disconnectTime = Connect?.IsNoiseEnabled == true + ? DateTime.UtcNow.AddHours(Random.Shared.Next(1, 4)) + : DateTime.UtcNow; + } + } + } + catch (Exception) + { + ResetConnectTime(null); + } + } + + private static void ResetConnectTime(object? state) + { + lock (_lock) + { + _connectTime = null; + Connect = null; + + _resetTimer?.Dispose(); + _resetTimer = null; + } + } + + public static bool IsDisconnected() + { + return _disconnectTime is not null + && DateTime.UtcNow >= _disconnectTime; + } + + public static ActionResult Validate(ActionResult result) + { + return IsDisconnected() + ? throw new JsonReaderException($"Disconnect error: {Guid.CreateVersion7()}") + : result; + } + } + + public record ConnectResponse(bool IsUpdateUnavailable, bool IsNoiseEnabled); +} diff --git a/MoonAnime/Models/MoonAnimeModels.cs b/MoonAnime/Models/MoonAnimeModels.cs new file mode 100644 index 0000000..8bf9726 --- /dev/null +++ b/MoonAnime/Models/MoonAnimeModels.cs @@ -0,0 +1,56 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace MoonAnime.Models +{ + public class MoonAnimeSearchResponse + { + [JsonPropertyName("seasons")] + public List Seasons { get; set; } = new(); + } + + public class MoonAnimeSeasonRef + { + [JsonPropertyName("season_number")] + public int SeasonNumber { get; set; } + + [JsonPropertyName("url")] + public string Url { get; set; } + } + + public class MoonAnimeSeasonContent + { + public int SeasonNumber { get; set; } + + public string Url { get; set; } + + public bool IsSeries { get; set; } + + public List Voices { get; set; } = new(); + } + + public class MoonAnimeVoiceContent + { + public string Name { get; set; } + + public string MovieFile { get; set; } + + public List Episodes { get; set; } = new(); + } + + public class MoonAnimeEpisodeContent + { + public string Name { get; set; } + + public int Number { get; set; } + + public string File { get; set; } + } + + public class MoonAnimeStreamVariant + { + public string Url { get; set; } + + public string Quality { get; set; } + } +} diff --git a/MoonAnime/MoonAnime.csproj b/MoonAnime/MoonAnime.csproj new file mode 100644 index 0000000..1fbe365 --- /dev/null +++ b/MoonAnime/MoonAnime.csproj @@ -0,0 +1,15 @@ + + + + net9.0 + library + true + + + + + ..\..\Shared.dll + + + + diff --git a/MoonAnime/MoonAnimeInvoke.cs b/MoonAnime/MoonAnimeInvoke.cs new file mode 100644 index 0000000..df6a742 --- /dev/null +++ b/MoonAnime/MoonAnimeInvoke.cs @@ -0,0 +1,462 @@ +using MoonAnime.Models; +using Shared; +using Shared.Engine; +using Shared.Models; +using Shared.Models.Online.Settings; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Web; + +namespace MoonAnime +{ + public class MoonAnimeInvoke + { + private readonly OnlinesSettings _init; + private readonly IHybridCache _hybridCache; + private readonly Action _onLog; + private readonly ProxyManager _proxyManager; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true + }; + + public MoonAnimeInvoke(OnlinesSettings init, IHybridCache hybridCache, Action onLog, ProxyManager proxyManager) + { + _init = init; + _hybridCache = hybridCache; + _onLog = onLog; + _proxyManager = proxyManager; + } + + public async Task> Search(string imdbId, string malId, string title, string originalTitle, int year) + { + string memKey = $"MoonAnime:search:{imdbId}:{malId}:{title}:{originalTitle}:{year}"; + if (_hybridCache.TryGetValue(memKey, out List cached)) + return cached; + + try + { + var endpoints = new[] + { + "/moonanime/search", + "/moonanime" + }; + + foreach (var endpoint in endpoints) + { + string searchUrl = BuildSearchUrl(endpoint, imdbId, malId, title, originalTitle, year); + if (string.IsNullOrWhiteSpace(searchUrl)) + continue; + + _onLog($"MoonAnime: пошук через {searchUrl}"); + string json = await Http.Get(_init.cors(searchUrl), headers: DefaultHeaders(), proxy: _proxyManager.Get()); + if (string.IsNullOrWhiteSpace(json)) + continue; + + var response = JsonSerializer.Deserialize(json, _jsonOptions); + var seasons = response?.Seasons? + .Where(s => s != null && !string.IsNullOrWhiteSpace(s.Url)) + .Select(s => new MoonAnimeSeasonRef + { + SeasonNumber = s.SeasonNumber <= 0 ? 1 : s.SeasonNumber, + Url = s.Url.Trim() + }) + .GroupBy(s => s.Url, StringComparer.OrdinalIgnoreCase) + .Select(g => g.First()) + .OrderBy(s => s.SeasonNumber) + .ToList(); + + if (seasons != null && seasons.Count > 0) + { + _hybridCache.Set(memKey, seasons, cacheTime(10, init: _init)); + return seasons; + } + } + } + catch (Exception ex) + { + _onLog($"MoonAnime: помилка пошуку - {ex.Message}"); + } + + return new List(); + } + + public async Task GetSeasonContent(MoonAnimeSeasonRef season) + { + if (season == null || string.IsNullOrWhiteSpace(season.Url)) + return null; + + string memKey = $"MoonAnime:season:{season.Url}"; + if (_hybridCache.TryGetValue(memKey, out MoonAnimeSeasonContent cached)) + return cached; + + try + { + _onLog($"MoonAnime: завантаження сезону {season.Url}"); + string html = await Http.Get(_init.cors(season.Url), headers: DefaultHeaders(), proxy: _proxyManager.Get()); + if (string.IsNullOrWhiteSpace(html)) + return null; + + var content = ParseSeasonPage(html, season.SeasonNumber, season.Url); + if (content != null) + _hybridCache.Set(memKey, content, cacheTime(20, init: _init)); + + return content; + } + catch (Exception ex) + { + _onLog($"MoonAnime: помилка читання сезону - {ex.Message}"); + return null; + } + } + + public List ParseStreams(string rawFile) + { + var streams = new List(); + if (string.IsNullOrWhiteSpace(rawFile)) + return streams; + + string value = WebUtility.HtmlDecode(rawFile).Trim(); + + var bracketMatches = Regex.Matches(value, @"\[(?[^\]]+)\](?https?://[^,\[]+)", RegexOptions.IgnoreCase); + foreach (Match match in bracketMatches) + { + string quality = NormalizeQuality(match.Groups["quality"].Value); + string url = match.Groups["url"].Value?.Trim(); + if (string.IsNullOrWhiteSpace(url)) + continue; + + streams.Add(new MoonAnimeStreamVariant + { + Url = url, + Quality = quality + }); + } + + if (streams.Count == 0) + { + var taggedMatches = Regex.Matches(value, @"(?\d{3,4}p?)\s*[:|]\s*(?https?://[^,\s]+)", RegexOptions.IgnoreCase); + foreach (Match match in taggedMatches) + { + string quality = NormalizeQuality(match.Groups["quality"].Value); + string url = match.Groups["url"].Value?.Trim(); + if (string.IsNullOrWhiteSpace(url)) + continue; + + streams.Add(new MoonAnimeStreamVariant + { + Url = url, + Quality = quality + }); + } + } + + if (streams.Count == 0) + { + var plainLinks = value + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Where(part => part.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + .ToList(); + + if (plainLinks.Count > 1) + { + for (int i = 0; i < plainLinks.Count; i++) + { + streams.Add(new MoonAnimeStreamVariant + { + Url = plainLinks[i], + Quality = $"auto-{i + 1}" + }); + } + } + } + + if (streams.Count == 0 && value.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + streams.Add(new MoonAnimeStreamVariant + { + Url = value, + Quality = "auto" + }); + } + + return streams + .Where(s => s != null && !string.IsNullOrWhiteSpace(s.Url)) + .Select(s => new MoonAnimeStreamVariant + { + Url = s.Url.Trim(), + Quality = NormalizeQuality(s.Quality) + }) + .GroupBy(s => s.Url, StringComparer.OrdinalIgnoreCase) + .Select(g => g.First()) + .OrderByDescending(s => QualityWeight(s.Quality)) + .ToList(); + } + + private string BuildSearchUrl(string endpoint, string imdbId, string malId, string title, string originalTitle, int year) + { + var query = HttpUtility.ParseQueryString(string.Empty); + + if (!string.IsNullOrWhiteSpace(imdbId)) + query["imdb_id"] = imdbId; + + if (!string.IsNullOrWhiteSpace(malId)) + query["mal_id"] = malId; + + if (!string.IsNullOrWhiteSpace(title)) + query["title"] = title; + + if (!string.IsNullOrWhiteSpace(originalTitle)) + query["original_title"] = originalTitle; + + if (year > 0) + query["year"] = year.ToString(); + + if (query.Count == 0) + return null; + + return $"{_init.apihost.TrimEnd('/')}{endpoint}?{query}"; + } + + private MoonAnimeSeasonContent ParseSeasonPage(string html, int seasonNumber, string seasonUrl) + { + var content = new MoonAnimeSeasonContent + { + SeasonNumber = seasonNumber <= 0 ? 1 : seasonNumber, + Url = seasonUrl, + IsSeries = false + }; + + string fileArrayJson = ExtractFileArrayJson(html); + if (string.IsNullOrWhiteSpace(fileArrayJson)) + return content; + + using var doc = JsonDocument.Parse(fileArrayJson); + if (doc.RootElement.ValueKind != JsonValueKind.Array) + return content; + + int voiceIndex = 1; + foreach (var entry in doc.RootElement.EnumerateArray()) + { + if (entry.ValueKind != JsonValueKind.Object) + continue; + + var voice = new MoonAnimeVoiceContent + { + Name = NormalizeVoiceName(GetStringProperty(entry, "title"), voiceIndex) + }; + + if (entry.TryGetProperty("folder", out var folder) && folder.ValueKind == JsonValueKind.Array) + { + int episodeIndex = 1; + foreach (var episodeEntry in folder.EnumerateArray()) + { + if (episodeEntry.ValueKind != JsonValueKind.Object) + continue; + + string file = GetStringProperty(episodeEntry, "file"); + if (string.IsNullOrWhiteSpace(file)) + continue; + + string episodeTitle = GetStringProperty(episodeEntry, "title"); + int episodeNumber = ParseEpisodeNumber(episodeTitle, episodeIndex); + + voice.Episodes.Add(new MoonAnimeEpisodeContent + { + Name = string.IsNullOrWhiteSpace(episodeTitle) ? $"Епізод {episodeNumber}" : WebUtility.HtmlDecode(episodeTitle), + Number = episodeNumber, + File = file + }); + + episodeIndex++; + } + + if (voice.Episodes.Count > 0) + { + content.IsSeries = true; + voice.Episodes = voice.Episodes + .OrderBy(e => e.Number <= 0 ? int.MaxValue : e.Number) + .ThenBy(e => e.Name) + .ToList(); + } + } + else + { + voice.MovieFile = GetStringProperty(entry, "file"); + } + + if (!string.IsNullOrWhiteSpace(voice.MovieFile) || voice.Episodes.Count > 0) + content.Voices.Add(voice); + + voiceIndex++; + } + + return content; + } + + private static string NormalizeVoiceName(string source, int fallbackIndex) + { + string voice = WebUtility.HtmlDecode(source ?? string.Empty).Trim(); + return string.IsNullOrWhiteSpace(voice) ? $"Озвучка {fallbackIndex}" : voice; + } + + private static int ParseEpisodeNumber(string title, int fallback) + { + if (string.IsNullOrWhiteSpace(title)) + return fallback; + + var match = Regex.Match(title, @"\d+"); + if (match.Success && int.TryParse(match.Value, out int number)) + return number; + + return fallback; + } + + private static string NormalizeQuality(string quality) + { + if (string.IsNullOrWhiteSpace(quality)) + return "auto"; + + string value = quality.Trim().Trim('[', ']'); + if (value.Equals("auto", StringComparison.OrdinalIgnoreCase)) + return "auto"; + + var match = Regex.Match(value, @"(?\d{3,4})"); + if (match.Success) + return $"{match.Groups["q"].Value}p"; + + return value; + } + + private static int QualityWeight(string quality) + { + if (string.IsNullOrWhiteSpace(quality)) + return 0; + + var match = Regex.Match(quality, @"\d{3,4}"); + if (match.Success && int.TryParse(match.Value, out int q)) + return q; + + return quality.Equals("auto", StringComparison.OrdinalIgnoreCase) ? 1 : 0; + } + + private static string GetStringProperty(JsonElement element, string name) + { + return element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String + ? value.GetString() + : null; + } + + private static string ExtractFileArrayJson(string html) + { + if (string.IsNullOrWhiteSpace(html)) + return null; + + var match = Regex.Match(html, @"file\s*:\s*(\[[\s\S]*?\])\s*,\s*skip\s*:", RegexOptions.IgnoreCase); + if (match.Success) + return match.Groups[1].Value; + + int fileIndex = html.IndexOf("file", StringComparison.OrdinalIgnoreCase); + if (fileIndex < 0) + return null; + + int colonIndex = html.IndexOf(':', fileIndex); + if (colonIndex < 0) + return null; + + int arrayIndex = html.IndexOf('[', colonIndex); + if (arrayIndex < 0) + return null; + + return ExtractBracketArray(html, arrayIndex); + } + + private static string ExtractBracketArray(string source, int startIndex) + { + bool inString = false; + bool escaped = false; + char stringChar = '\0'; + int depth = 0; + int begin = -1; + + for (int i = startIndex; i < source.Length; i++) + { + char c = source[i]; + + if (inString) + { + if (escaped) + { + escaped = false; + continue; + } + + if (c == '\\') + { + escaped = true; + continue; + } + + if (c == stringChar) + { + inString = false; + stringChar = '\0'; + } + + continue; + } + + if (c == '"' || c == '\'') + { + inString = true; + stringChar = c; + continue; + } + + if (c == '[') + { + if (depth == 0) + begin = i; + + depth++; + continue; + } + + if (c == ']') + { + depth--; + if (depth == 0 && begin >= 0) + return source.Substring(begin, i - begin + 1); + } + } + + return null; + } + + private List DefaultHeaders() + { + return new List + { + new HeadersModel("User-Agent", "Mozilla/5.0"), + new HeadersModel("Referer", _init.host) + }; + } + + 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/MoonAnime/OnlineApi.cs b/MoonAnime/OnlineApi.cs new file mode 100644 index 0000000..6666152 --- /dev/null +++ b/MoonAnime/OnlineApi.cs @@ -0,0 +1,44 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Memory; +using Shared.Models; +using Shared.Models.Base; +using Shared.Models.Module; +using System.Collections.Generic; + +namespace MoonAnime +{ + public class OnlineApi + { + public static List<(string name, string url, string plugin, int index)> Invoke( + HttpContext httpContext, + IMemoryCache memoryCache, + RequestModel requestInfo, + string host, + OnlineEventsModel args) + { + long.TryParse(args.id, out long tmdbid); + return Events(host, tmdbid, args.imdb_id, args.kinopoisk_id, args.title, args.original_title, args.original_language, args.year, args.source, args.serial, args.account_email); + } + + 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.MoonAnime; + + bool hasLang = !string.IsNullOrEmpty(original_language); + bool isAnime = hasLang && (original_language == "ja" || original_language == "zh"); + + if (init.enable && !init.rip && (serial == -1 || isAnime || !hasLang)) + { + string url = init.overridehost; + if (string.IsNullOrEmpty(url) || UpdateService.IsDisconnected()) + url = $"{host}/moonanime"; + + online.Add((init.displayname, url, "moonanime", init.displayindex)); + } + + return online; + } + } +} diff --git a/MoonAnime/manifest.json b/MoonAnime/manifest.json new file mode 100644 index 0000000..754dcaa --- /dev/null +++ b/MoonAnime/manifest.json @@ -0,0 +1,6 @@ +{ + "enable": true, + "version": 3, + "initspace": "MoonAnime.ModInit", + "online": "MoonAnime.OnlineApi" +} diff --git a/README.md b/README.md index d5fb4e9..0b94ae5 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ - [x] BambooUA - [x] Unimay - [x] Mikai +- [x] MoonAnime ## Installation @@ -41,6 +42,7 @@ Create or update the module/repository.yaml file - AnimeON - Unimay - Mikai + - MoonAnime - Uaflix - Bamboo - Makhno @@ -161,6 +163,7 @@ Sources with APN support: - Mikai - Makhno - KlonFUN +- MoonAnime ## Source/player availability check script