using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Shared;
namespace Lampac.Controllers
{
public class WebLogController : BaseController
{
[HttpGet]
[AllowAnonymous]
[Route("weblog")]
public ActionResult WebLog(string token, string pattern, string receive = "http")
{
if (!AppInit.conf.weblog.enable)
return Content("Включите weblog в init.conf\n\n\"weblog\": {\n \"enable\": true\n}", contentType: "text/plain; charset=utf-8");
if (!string.IsNullOrEmpty(AppInit.conf.weblog.token) && token != AppInit.conf.weblog.token)
return Content("Используйте /weblog?token=my_key\n\n\"weblog\": {\n \"enable\": true,\n \"token\": \"my_key\"\n}", contentType: "text/plain; charset=utf-8");
string html = $@"
weblog
";
return Content(html, "text/html; charset=utf-8");
}
static string nwsCode(string token) => $@"
const client = new NativeWsClient(""/nws"", {{
autoReconnect: true,
reconnectDelay: 2000,
onOpen: function () {{
send('WebSocket connected');
outageReported = false;
client.invoke('RegistryWebLog', '{token}');
}},
onClose: function () {{
reportOutageOnce('Connection closed');
}},
onError: function (err) {{
reportOutageOnce('Connection error: ' + (err && err.message ? err.message : String(err)));
}}
}});
client.on('Receive', function (message, e) {{
if (receive === e) send(message);
}});
client.connect();
";
static string signalCode(string token) => $@"
const hubConnection = new signalR.HubConnectionBuilder()
.withUrl('/ws')
.build();
let reconnectAttempts = 0;
const maxReconnectAttempts = 150; // 5 minutes
const reconnectDelay = 2000; // 2 seconds
function startConnection() {{
hubConnection.start()
.then(function () {{
if (reconnectAttempts != 0)
send('WebSocket connected');
reconnectAttempts = 0; // Reset counter on successful connection
hubConnection.invoke('RegistryWebLog', '{token}');
}})
.catch(function (err) {{
console.log(`${{err.toString()}}\n\nAttempting to reconnect (${{reconnectAttempts}}/${{maxReconnectAttempts}})...`);
attemptReconnect();
}});
}}
function attemptReconnect() {{
if (reconnectAttempts < maxReconnectAttempts) {{
reconnectAttempts++;
setTimeout(function() {{
startConnection();
}}, reconnectDelay);
}} else {{
send('Max reconnection attempts reached. Please refresh the page.');
}}
}}
hubConnection.on('Receive', function(message, e) {{
if(receive === e) send(message);
}});
hubConnection.onclose(function(err) {{
if (err) {{
send('Connection closed due to error: ' + err.toString());
}} else {{
send('Connection closed');
}}
attemptReconnect();
}});
startConnection();
";
}
}