[CHANGE] Add account dialog
This commit is contained in:
@@ -1,4 +1,3 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using DotBased.Monads;
|
||||
using HtmlAgilityPack;
|
||||
|
||||
@@ -6,34 +5,60 @@ namespace Manager.YouTube.Parsers;
|
||||
|
||||
public static class HtmlParser
|
||||
{
|
||||
public static Result<string> GetJsonFromScriptFunction(string html, string functionName)
|
||||
public static Result<(string, string)> GetStateJson(string html)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(html))
|
||||
{
|
||||
return ResultError.Fail("html cannot be empty!");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(functionName))
|
||||
{
|
||||
return ResultError.Fail("No function names provided!");
|
||||
}
|
||||
|
||||
var htmlDocument = new HtmlDocument();
|
||||
htmlDocument.LoadHtml(html);
|
||||
|
||||
var scriptNode = htmlDocument.DocumentNode.SelectSingleNode($"//script[contains(., '{functionName}')]");
|
||||
if (string.IsNullOrWhiteSpace(scriptNode.InnerText))
|
||||
return ResultError.Fail($"Could not find {functionName} in html script nodes!");
|
||||
|
||||
var regexPattern = $@"{Regex.Escape(functionName)}\(([^)]+)\);";
|
||||
var match = Regex.Match(scriptNode.InnerText, regexPattern);
|
||||
|
||||
if (match.Success)
|
||||
const string setFunction = "ytcfg.set({";
|
||||
var scriptNode = htmlDocument.DocumentNode.SelectSingleNode($"//script[contains(., '{setFunction}')]");
|
||||
if (string.IsNullOrWhiteSpace(scriptNode.InnerText))
|
||||
return ResultError.Fail($"Could not find {setFunction} in html script nodes!");
|
||||
|
||||
var json = ExtractJson(scriptNode.InnerText, "ytcfg.set(");
|
||||
var jsonText = ExtractJson(scriptNode.InnerText, "setMessage(");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(json) || string.IsNullOrWhiteSpace(jsonText))
|
||||
{
|
||||
var jsonString = match.Groups[1].Value.Trim();
|
||||
return jsonString;
|
||||
return ResultError.Fail($"Could not find {setFunction} in html script nodes!");
|
||||
}
|
||||
|
||||
return ResultError.Fail($"Unable to parse {functionName} JSON!");
|
||||
return (json, jsonText);
|
||||
}
|
||||
|
||||
static string? ExtractJson(string input, string marker)
|
||||
{
|
||||
var start = input.IndexOf(marker, StringComparison.Ordinal);
|
||||
if (start < 0) return null;
|
||||
|
||||
start += marker.Length;
|
||||
|
||||
// Skip until first '{'
|
||||
while (start < input.Length && input[start] != '{')
|
||||
start++;
|
||||
|
||||
if (start >= input.Length) return null;
|
||||
|
||||
var depth = 0;
|
||||
var i = start;
|
||||
|
||||
for (; i < input.Length; i++)
|
||||
{
|
||||
if (input[i] == '{') depth++;
|
||||
else if (input[i] == '}')
|
||||
{
|
||||
depth--;
|
||||
if (depth != 0) continue;
|
||||
i++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return input[start..i];
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user