Skip to content

Commit

Permalink
IRC: Authorization via nickserv. Bugfixes for search
Browse files Browse the repository at this point in the history
  • Loading branch information
LaineZ committed Nov 25, 2023
1 parent 5b2c3ac commit d580530
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 31 deletions.
5 changes: 5 additions & 0 deletions fs24bot3/Backend/Basic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,9 @@ public async void Process()
}
}
}

public Task<bool> EnsureAuthorization(User user)
{
throw new NotImplementedException();
}
}
12 changes: 6 additions & 6 deletions fs24bot3/Backend/IMessagingClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ public interface IMessagingClient
public Bot BotContext { get; }

public Dictionary<string, string> Fmt { get; }

public void SetupNick(string nickname) { }
public void JoinChannel(string name)
{
Expand All @@ -28,13 +27,14 @@ public void PartChannel(string name)
throw new NotImplementedException();
}

public Task SendMessage(string channel, string message)
{
throw new NotImplementedException();
}

public Task SendMessage(string channel, string message);
public void Process()
{
BotContext.ProccessInfinite();
}

public Task<bool> EnsureAuthorization(User user)
{
return Task.FromResult(true);
}
}
67 changes: 56 additions & 11 deletions fs24bot3/Backend/IRC.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public Irc()
Log.Warning("IRC backend was unable to find configuration file, I will create it for you");
File.WriteAllText(ConfigPath, Toml.FromModel(Config));
}

Fmt = new Dictionary<string, string>
{
// add irc colors
Expand All @@ -98,15 +98,15 @@ public Irc()

SetupNick(Config.Name);

BotClient = new Client(new NetIRC.User(Name, "Sopli IRC 3.0"),
BotClient = new Client(new NetIRC.User(Name, "Sopli IRC 3.0"),
new TcpClientConnection(Config.Network, Config.Port));

BotClient.RawDataReceived += Client_OnRawDataReceived;
BotClient.IRCMessageParsed += Client_OnIRCMessageParsed;
BotClient.RegistrationCompleted += Client_OnRegister;
}


private async void Client_OnIRCMessageParsed(Client client, ParsedIRCMessage message)
{
if (message.IRCCommand == IRCCommand.PRIVMSG)
Expand All @@ -129,7 +129,7 @@ private async void Client_OnIRCMessageParsed(Client client, ParsedIRCMessage mes

if (message.NumericReply == IRCNumericReply.ERR_NICKNAMEINUSE)
{
SetupNick(Name + new Random().Next(int.MinValue, int.MaxValue));
SetupNick(Name + new Random().Next(int.MinValue, int.MaxValue));
}

if (message.NumericReply == IRCNumericReply.ERR_PASSWDMISMATCH)
Expand All @@ -140,8 +140,8 @@ private async void Client_OnIRCMessageParsed(Client client, ParsedIRCMessage mes
if (message.IRCCommand == IRCCommand.KICK && message.Parameters[1] == Name)
{
Log.Warning("I've got kick from {0} rejoining...", message.Prefix);
await client.SendRaw("JOIN " + message.Parameters[0]);
await SendMessage(message.Parameters[0], "За что?");
await client.SendRaw("JOIN " + message.Parameters[0]);
await SendMessage(message.Parameters[0], "За что?");
}
}

Expand All @@ -168,14 +168,14 @@ public async void JoinChannel(string name)
{
await BotClient.SendRaw("JOIN " + name);
}

public async void PartChannel(string name)
{
await BotClient.SendRaw("PART " + name);
}

public void Process()
{
{
Log.Information("Connecting to: {0}:{1}", Config.Network, Config.Port);
Task.Run(() => BotClient.ConnectAsync());
BotContext.ProccessInfinite();
Expand Down Expand Up @@ -211,11 +211,56 @@ await BotClient.SendAsync(new PrivMsgMessage(channel, $"Слишком жест

if (count > 4)
{
string link = await InternetServicesHelper.UploadToTrashbin(MessageHelper.StripIRC(message),
string link = await InternetServicesHelper.UploadToTrashbin(MessageHelper.StripIRC(message),
"addplain");
await BotClient.SendAsync(new PrivMsgMessage(channel, "Полный вывод: " + link));
return;
}
}
}


/// <summary>
/// Ensures authorization in IRC
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public async Task<bool> EnsureAuthorization(Core.User user)
{
var tcs = new TaskCompletionSource<bool>();
ParsedIRCMessageHandler messageHandler = null;

// ACC returns parsable information about a user's
// login status. Note that on many networks, /whois
// shows similar information faster and more reliably.
// ACC also returns the unique entity ID of the given account.
// The answer is in the form <nick> [-> account] ACC <digit> <EID>,
// where <digit> is one of the following:
// 0 - account or user does not exist
// 1 - account exists but user is not logged in
// 2 - user is not logged in but recognized (see ACCESS)
// 3 - user is logged in
// If the account is omitted the user's nick is used and
// the " -> account" portion of the reply is omitted.
// Account * means the account the user is logged in with.
// example:
// Totoro ACC 1 AAAAAXXX

messageHandler = (client, message) =>
{
if (message.Prefix.From == "NickServ")
{
var split = message.Trailing.Split(" ");

tcs.SetResult(split[2] == "3");

BotClient.IRCMessageParsed -= messageHandler;
}
};

BotClient.IRCMessageParsed += messageHandler;

await SendMessage("NickServ", $"ACC {user.Username}");
return await tcs.Task;
}
}
4 changes: 3 additions & 1 deletion fs24bot3/Bot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,10 @@ public async Task ExecuteCommand(MessageGeneric message, string prefix)

PProfiler.BeginMeasure("command");

var auth = await Client.EnsureAuthorization(message.Sender);

var result =
await Service.ExecuteAsync(output, new CommandProcessor.CustomCommandContext(this, in message));
await Service.ExecuteAsync(output, new CommandProcessor.CustomCommandContext(this, in message, auth));

switch (result)
{
Expand Down
2 changes: 1 addition & 1 deletion fs24bot3/Checks/CheckAdmin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public override ValueTask<CheckResult> CheckAsync(CommandContext _)

try
{
return context.User.GetUserInfo().Admin > 1 || ConfigurationProvider.Config.Backend == Models.Backend.Basic
return (context.User.GetUserInfo().Admin > 1 && context.IsAuthorizedAction) || ConfigurationProvider.Config.Backend == Models.Backend.Basic
? CheckResult.Successful
: CheckResult.Failed("Эта команда только для админов!");
}
Expand Down
4 changes: 2 additions & 2 deletions fs24bot3/Checks/FullAccount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ public override ValueTask<CheckResult> CheckAsync(CommandContext _)
{
var context = _ as CommandProcessor.CustomCommandContext;

return !context.FromBridge && !context.User.UserIsIgnored() && context.User != null
return !context.FromBridge && !context.User.UserIsIgnored() && context.User != null && context.IsAuthorizedAction
? CheckResult.Successful
: CheckResult.Failed("Эта команда требует аккаунт пользователя fs24_bot!");
: CheckResult.Failed("Эта команда требует аккаунт fs24_bot и авторизацию через NickServ!");
}

public override string ToString()
Expand Down
13 changes: 4 additions & 9 deletions fs24bot3/Commands/NetstalkingCommandsModule.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
using fs24bot3.Core;
using fs24bot3.Helpers;
using fs24bot3.Helpers;
using fs24bot3.Models;
using fs24bot3.QmmandsProcessors;
using Newtonsoft.Json;
using Qmmands;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
Expand All @@ -17,11 +13,7 @@ public sealed class NetstalkingCommandsModule : ModuleBase<CommandProcessor.Cust

private static readonly string[] SearxUrls =
{
"https://search.mdosch.de/",
"https://search.neet.works/",
"https://search.sapti.me/",
"https://search.trom.tf/",
"https://search.unlocked.link/",
"https://searx.dresden.network/",
"https://searx.mastodontech.de/",
"https://searx.mxchange.org/",
Expand All @@ -36,6 +28,9 @@ public sealed class NetstalkingCommandsModule : ModuleBase<CommandProcessor.Cust
"https://searx.zapashcanon.fr/",
"https://searxng.nicfab.eu/",
"https://suche.tromdienste.de/",
"https://search.mdosch.de/",
"https://search.neet.works/",
"https://search.sapti.me/"
};

public CommandService Service { get; set; }
Expand Down
5 changes: 4 additions & 1 deletion fs24bot3/QmmandsProcessors/CommandProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@ public sealed class CustomCommandContext : CommandContext

public HttpTools HttpTools { get; }
public InternetServicesHelper ServicesHelper { get; }
public bool IsAuthorizedAction { get; }


// Pass your service provider to the base command context.
public CustomCommandContext(Bot bot, in MessageGeneric message, IServiceProvider provider = null) : base(provider)
public CustomCommandContext(Bot bot, in MessageGeneric message, bool authorized, IServiceProvider provider = null) : base(provider)
{
BotCtx = bot;
Channel = message.Target;
Expand All @@ -34,6 +36,7 @@ public CustomCommandContext(Bot bot, in MessageGeneric message, IServiceProvider
HttpTools = new HttpTools();
ServicesHelper = new InternetServicesHelper(HttpTools);
User = message.Sender;
IsAuthorizedAction = authorized;
}

public async Task SendMessage(string channel, string message)
Expand Down

0 comments on commit d580530

Please sign in to comment.