refactor; add command system

This commit is contained in:
Laura Hausmann 2019-12-13 11:18:08 +01:00
parent bce56bdc53
commit 69108e7e21
Signed by: zotan
GPG key ID: 5EC1D38FFC321311
2 changed files with 328 additions and 198 deletions

View file

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using TdLib;
using static telegram.tgcli;
@ -6,181 +7,302 @@ using static telegram.Util;
namespace telegram
{
public class Command
public abstract class Command
{
public static void ParseCommand(string command)
public string ShortTrigger;
public string Shortcut;
public string Description;
public int ParamCount;
public abstract void Handler(List<string> inputParams);
protected Command(string shortTrigger, string shortcut, string description, int paramCount)
{
while (true)
ShortTrigger = shortTrigger;
Shortcut = shortcut;
Description = description;
ParamCount = paramCount;
}
}
public static class CommandManager
{
public static List<Command> Commands = new List<Command>
{
new ClearCommand(),
new CloseCommand(),
new EditCommand(),
new HistoryCommand(),
new OpenCommand(),
new UnreadsCommand(),
new CloseUnreadCommand(),
new HelpCommand()
};
public static void HandleCommand(string input)
{
var split = input.Split(" ").ToList();
var trigger = split.First();
var command = Commands.Find(p => p.ShortTrigger == trigger || p.Shortcut == trigger);
if (command == null)
{
var split = command.Split(" ");
if (split[0].Equals("open") || split[0].Equals("o"))
{
if (split.Length < 2) return;
//TODO Console.WriteLine("do something");
return;
}
var query = command.Substring(split[0].Length);
var chatId = SearchChatId(query);
if (chatId == 0) return;
currentChatId = 0;
currentChatUserId = 0;
currentUserRead = false;
var chat = GetChat(chatId);
if (chat.Type is TdApi.ChatType.ChatTypePrivate privChat)
{
currentChatUserId = privChat.UserId;
}
currentChatId = chat.Id;
prefix = $"[{chat.Title}";
lock (@lock)
{
messageQueue.Add($"{Ansi.Yellow}[tgcli] Opening chat: {chat.Title}");
messageQueue.Add($"{Ansi.Yellow}" + $"[tgcli] You have {chat.UnreadCount} unread message" + $"{(chat.UnreadCount == 1 ? "." : "s.")}");
while (GetHistory(chatId, 50).Count == 1)
{
GetHistory(chatId, 10);
}
if (chat.UnreadCount >= 5)
{
var capped = chat.UnreadCount > 50;
GetHistory(chatId, capped ? 50 : chat.UnreadCount).ForEach(AddMessageToQueue);
if (capped) messageQueue.Add($"{Ansi.Yellow}[tgcli] " + $"Showing 50 of {chat.UnreadCount} unread messages.");
}
else if (chat.UnreadCount > 0)
{
var unreads = GetHistory(chatId, chat.UnreadCount);
var rest = GetHistory(chatId, 5 - unreads.Count, unreads.First().Id);
rest.ForEach(AddMessageToQueue);
messageQueue.Add($"{Ansi.Yellow}[tgcli] ---UNREAD---");
unreads.ForEach(AddMessageToQueue);
}
else
{
GetHistory(chatId).ForEach(AddMessageToQueue);
}
}
var history = GetHistory(currentChatId, 50);
if (history.Count != 0)
MarkRead(chat.Id, history.First().Id);
var last = history.LastOrDefault(p => p.IsOutgoing);
if (last == null)
{
currentUserRead = true;
return;
}
lastMessage = last;
currentUserRead = IsMessageRead(last.ChatId, last.Id);
}
else if (split[0].Equals("cu") || split[0].Equals("closeunread"))
{
if (currentChatId == 0) return;
MarkUnread(currentChatId);
command = "close";
continue;
}
else if (split[0].Equals("close") || split[0].Equals("c"))
{
if (split.Length != 1 || currentChatId == 0) return;
currentChatId = 0;
currentChatUserId = 0;
currentUserRead = false;
lastMessage = null;
prefix = "[tgcli";
lock (@lock)
{
messageQueue.Add($"{Ansi.Yellow}[tgcli] Closing chat.");
var count = missedMessages.Count;
if (count == 0) return;
messageQueue.Add($"{Ansi.Yellow}" + $"[tgcli] You have {count} missed message" + $"{(count == 1 ? "." : "s.")}");
messageQueue.AddRange(missedMessages);
missedMessages.Clear();
}
}
else if (split[0].Equals("history") || split[0].Equals("h"))
{
if (split.Length != 1 && split.Length != 2 || currentChatId == 0)
{
lock (@lock) messageQueue.Add($"{Ansi.Red}[tgcli] " + "No chat selected. Select a chat with /open <query>");
return;
}
var history = split.Length > 1 && int.TryParse(split[1], out var limit)
? GetHistory(currentChatId, limit)
: GetHistory(currentChatId);
lock (@lock)
{
messageQueue.Add($"{Ansi.Yellow}[tgcli] Last {history.Count} messages in " + $"{GetChat(currentChatId).Title}");
}
foreach (var msg in history)
{
AddMessageToQueue(msg);
}
}
else if (split[0].Equals("clear") || split[0].Equals("cl"))
{
lock (@lock)
{
Console.Clear();
}
}
else if (split[0].Equals("quit") || split[0].Equals("q"))
{
quitting = true;
}
else if (split[0].Equals("unreads") || split[0].Equals("u"))
{
var unreads = GetUnreadChats(split.Length == 2 && split[1].Equals("all"));
lock (@lock)
{
messageQueue.Add($"{Ansi.Yellow}[tgcli] You have {unreads.Count} unread chats.");
unreads.ForEach(chat =>
{
string line;
if (chat.UnreadCount == 0)
line = $"{Ansi.Bold}{Ansi.Yellow}[M] {chat.Title}";
else
line = $"{Ansi.Bold}{Ansi.Green}[{chat.UnreadCount}] {chat.Title}";
messageQueue.Add(line);
});
}
}
else if (split[0].Equals("edit") || split[0].Equals("e"))
{
if (currentChatId == 0) return;
if (split.Length == 1)
{
currentInputLine = "/e " + ((TdApi.MessageContent.MessageText) lastMessage?.Content)?.Text?.Text;
return;
}
if (lastMessage == null)
{
//try to find last message
var history = GetHistory(currentChatId, 50);
var last = history.LastOrDefault(p => p.IsOutgoing);
if (last == null) return;
lastMessage = last;
}
var message = command.Substring(split[0].Length);
if (string.IsNullOrWhiteSpace(message))
return;
EditMessage(message, lastMessage);
}
break;
split.RemoveAt(0);
if (command.ParamCount == -1)
{
command.Handler(split);
}
else if (split.Count == command.ParamCount)
{
command.Handler(split);
}
else
{
//TODO Console.WriteLine("do something");
}
}
}
public class OpenCommand : Command
{
public OpenCommand() : base("o", "^O", "opens a chat", -1)
{
}
public override void Handler(List<string> inputParams)
{
var query = inputParams.Aggregate((current, param) => current + " " + param).Trim();
var chatId = SearchChatId(query);
if (chatId == 0) return;
currentChatId = 0;
currentChatUserId = 0;
currentUserRead = false;
var chat = GetChat(chatId);
if (chat.Type is TdApi.ChatType.ChatTypePrivate privChat)
{
currentChatUserId = privChat.UserId;
}
currentChatId = chat.Id;
prefix = $"[{chat.Title}";
lock (@lock)
{
messageQueue.Add($"{Ansi.Yellow}[tgcli] Opening chat: {chat.Title}");
messageQueue.Add($"{Ansi.Yellow}" + $"[tgcli] You have {chat.UnreadCount} unread message" +
$"{(chat.UnreadCount == 1 ? "." : "s.")}");
while (GetHistory(chatId, 50).Count == 1)
{
GetHistory(chatId, 10);
}
if (chat.UnreadCount >= 5)
{
var capped = chat.UnreadCount > 50;
GetHistory(chatId, capped ? 50 : chat.UnreadCount).ForEach(AddMessageToQueue);
if (capped)
messageQueue.Add(
$"{Ansi.Yellow}[tgcli] " + $"Showing 50 of {chat.UnreadCount} unread messages.");
}
else if (chat.UnreadCount > 0)
{
var unreads = GetHistory(chatId, chat.UnreadCount);
var rest = GetHistory(chatId, 5 - unreads.Count, unreads.First().Id);
rest.ForEach(AddMessageToQueue);
messageQueue.Add($"{Ansi.Yellow}[tgcli] ---UNREAD---");
unreads.ForEach(AddMessageToQueue);
}
else
{
GetHistory(chatId).ForEach(AddMessageToQueue);
}
}
var history = GetHistory(currentChatId, 50);
if (history.Count != 0)
MarkRead(chat.Id, history.First().Id);
var last = history.LastOrDefault(p => p.IsOutgoing);
if (last == null)
{
currentUserRead = true;
return;
}
lastMessage = last;
currentUserRead = IsMessageRead(last.ChatId, last.Id);
}
}
public class CloseUnreadCommand : Command
{
public CloseUnreadCommand() : base("cu", "", "closes a chat, marking it as unread", 0)
{
}
public override void Handler(List<string> inputParams)
{
if (currentChatId == 0) return; //TODO: do something
MarkUnread(currentChatId);
CommandManager.HandleCommand("close");
}
}
public class CloseCommand : Command
{
public CloseCommand() : base("c", "^E", "closes a chat", 0)
{
}
public override void Handler(List<string> inputParams)
{
if (currentChatId == 0) return; //TODO: do something
currentChatId = 0;
currentChatUserId = 0;
currentUserRead = false;
lastMessage = null;
prefix = "[tgcli";
lock (@lock)
{
messageQueue.Add($"{Ansi.Yellow}[tgcli] Closing chat.");
var count = missedMessages.Count;
if (count == 0) return;
messageQueue.Add($"{Ansi.Yellow}" + $"[tgcli] You have {count} missed message" +
$"{(count == 1 ? "." : "s.")}");
messageQueue.AddRange(missedMessages);
missedMessages.Clear();
}
}
}
public class HistoryCommand : Command
{
public HistoryCommand() : base("h", "", "shows chat history", -1)
{
}
public override void Handler(List<string> inputParams)
{
if (currentChatId == 0) return; //TODO: do something
var history = inputParams.Count == 1 && int.TryParse(inputParams[0], out var limit)
? GetHistory(currentChatId, limit)
: GetHistory(currentChatId);
lock (@lock)
{
messageQueue.Add($"{Ansi.Yellow}[tgcli] Last {history.Count} messages in " +
$"{GetChat(currentChatId).Title}");
}
foreach (var msg in history)
{
AddMessageToQueue(msg);
}
}
}
public class ClearCommand : Command
{
public ClearCommand() : base("cl", "^L", "clears console", 0)
{
}
public override void Handler(List<string> inputParams)
{
lock (@lock)
{
Console.Clear();
}
}
}
public class UnreadsCommand : Command
{
public UnreadsCommand() : base("u", "^U", "displays unread chat", -1)
{
}
public override void Handler(List<string> inputParams)
{
var unreads = GetUnreadChats(inputParams.Count == 1 && inputParams[0].Equals("all"));
lock (@lock)
{
messageQueue.Add($"{Ansi.Yellow}[tgcli] You have {unreads.Count} unread chats.");
unreads.ForEach(chat =>
{
string line;
if (chat.UnreadCount == 0)
line = $"{Ansi.Bold}{Ansi.Yellow}[M] {chat.Title}";
else
line = $"{Ansi.Bold}{Ansi.Green}[{chat.UnreadCount}] {chat.Title}";
messageQueue.Add(line);
});
}
}
}
public class HelpCommand : Command
{
public HelpCommand() : base("help", "", "lists all commands", 0)
{
}
public override void Handler(List<string> inputParams)
{
lock (@lock)
{
messageQueue.Add($"{Ansi.Yellow}[tgcli] Listing {CommandManager.Commands.Count} commands:");
CommandManager.Commands.ForEach(command =>
{
if (string.IsNullOrWhiteSpace(command.Shortcut))
{
messageQueue.Add($"{Ansi.Yellow}/{command.ShortTrigger}: {command.Description}");
return;
}
messageQueue.Add(
$"{Ansi.Yellow}/{command.ShortTrigger} [{command.Shortcut}]: {command.Description}");
});
}
}
}
public class EditCommand : Command
{
public EditCommand() : base("e", "", "edits last message", -1)
{
}
public override void Handler(List<string> inputParams)
{
var message = inputParams.Aggregate((current, param) => current + " " + param).Trim();
if (currentChatId == 0) return; //TODO do something
if (message.Length == 0)
{
currentInputLine = "/e " + ((TdApi.MessageContent.MessageText) lastMessage?.Content)?.Text?.Text;
return;
}
if (lastMessage == null)
{
//try to find last message
var history = GetHistory(currentChatId, 50);
var last = history.LastOrDefault(p => p.IsOutgoing);
if (last == null) return; //TODO do something
lastMessage = last;
}
if (string.IsNullOrWhiteSpace(message))
return;
EditMessage(message, lastMessage);
}
}
}

View file

@ -6,13 +6,17 @@ using System.Threading;
using System.Threading.Tasks;
using Td = TdLib;
using static telegram.Util;
using static telegram.CommandManager;
// ReSharper disable SwitchStatementMissingSomeEnumCasesNoDefault
namespace telegram
{
/*
* TODO:
* make the command system not shit (classes & manager & /help etc)
* commands: more shortcuts!
* commands: usage!
* make commands & keybinds more consistent (maybe configurable?)
* reply to x messages ago
* cap length & truncate extremely long chat names!
* replace emoji on send & un-replace on edit, two-way dictionary!!
@ -31,7 +35,7 @@ namespace telegram
* publish AUR package
* maybe cursor input nav (cmd+del, left/right, up for last inputs, etc)
*/
// ReSharper disable once InconsistentNaming
public static class tgcli
{
@ -66,7 +70,7 @@ namespace telegram
MaxFileSize = 10000000
}
});
client.Send(new Td.TdApi.SetLogVerbosityLevel
{
NewVerbosityLevel = 2
@ -128,6 +132,7 @@ namespace telegram
currentUserRead = true;
ScreenUpdate();
}
break;
case Td.TdApi.Update.UpdateConnectionState state:
switch (state.State)
@ -149,7 +154,7 @@ namespace telegram
messageQueue.Add($"{Ansi.Yellow}[tgcli] Connected.");
Task.Run(() =>
{
Command.ParseCommand("u");
HandleCommand("u");
connectionState = "Ready";
ScreenUpdate();
});
@ -168,6 +173,7 @@ namespace telegram
ScreenUpdate();
break;
}
break;
}
}
@ -184,16 +190,16 @@ namespace telegram
var status = GetFormattedStatus(currentUserRead);
Console.Write(prefix
+ (connectionState == "Ready" ? "" : $" | {connectionState}")
+ (currentChatUserId != 0 ? status : "]") + " > " + currentInputLine);
+ (currentChatUserId != 0 ? status : "]") + " > " + currentInputLine);
}
}
private static void OnKeyPressed(ConsoleKeyInfo key)
{
switch (key.Key)
{
case ConsoleKey.Enter when connectionState != "Ready":
lock(@lock)
lock (@lock)
messageQueue.Add($"{Ansi.Red}[tgcli] " +
"Connection unstable. Check your network connection and try again.");
ScreenUpdate();
@ -202,13 +208,13 @@ namespace telegram
{
var command = currentInputLine.Substring(1);
currentInputLine = "";
Command.ParseCommand(command);
HandleCommand(command);
ScreenUpdate();
return;
}
case ConsoleKey.Enter when currentChatId == 0:
{
lock(@lock)
lock (@lock)
messageQueue.Add($"{Ansi.Red}[tgcli] " +
"No chat selected. Select a chat with /open <query>");
ScreenUpdate();
@ -231,6 +237,7 @@ namespace telegram
ScreenUpdate();
return;
}
currentInputLine = currentInputLine.Substring(0, currentInputLine.Length - 1);
ScreenUpdate();
break;
@ -243,19 +250,19 @@ namespace telegram
ScreenUpdate();
return;
case ConsoleKey.D when key.Modifiers.HasFlag(ConsoleModifiers.Control):
Command.ParseCommand("q");
HandleCommand("q");
ScreenUpdate();
return;
case ConsoleKey.Q when key.Modifiers.HasFlag(ConsoleModifiers.Control):
Command.ParseCommand("q");
HandleCommand("q");
ScreenUpdate();
return;
case ConsoleKey.E when key.Modifiers.HasFlag(ConsoleModifiers.Control):
Command.ParseCommand("c");
HandleCommand("c");
ScreenUpdate();
return;
case ConsoleKey.U when key.Modifiers.HasFlag(ConsoleModifiers.Control):
Command.ParseCommand("u");
HandleCommand("u");
ScreenUpdate();
return;
case ConsoleKey.O when key.Modifiers.HasFlag(ConsoleModifiers.Control):
@ -264,7 +271,7 @@ namespace telegram
ScreenUpdate();
return;
case ConsoleKey.L when key.Modifiers.HasFlag(ConsoleModifiers.Control):
Command.ParseCommand("cl");
HandleCommand("cl");
ScreenUpdate();
return;
}
@ -362,7 +369,7 @@ namespace telegram
Td.TdApi.Message replyMessage;
var msgPrefix = $"{Ansi.Bold}{Ansi.Green}[{time}] {Ansi.Cyan}{chat.Title} " +
$"{(isPrivate || isChannel ? "" : $"{Ansi.Yellow}{username} ")}";
$"{(isPrivate || isChannel ? "" : $"{Ansi.Yellow}{username} ")}";
var finalOutput = msgPrefix;
var indent = new string(' ', GetActualStringWidth(msgPrefix));
@ -380,7 +387,7 @@ namespace telegram
//ignored; reply to deleted msg
}
}
var rest = $"{text}{(msg.EditDate == 0 ? "" : $"{Ansi.Yellow}*")}";
var lines = rest.Split("\n").ToList();
if (!isReply)
@ -388,11 +395,12 @@ namespace telegram
finalOutput += arrows + lines.First();
lines.RemoveAt(0);
}
lines.ForEach(l => finalOutput += "\n" + indent + arrows + l);
return finalOutput;
}
public static string FormatMessageReply(Td.TdApi.Message msg, string origPrefix)
{
string text;
@ -408,15 +416,15 @@ namespace telegram
var isPrivate = chat.Type is Td.TdApi.ChatType.ChatTypePrivate;
var finalOutput = "";
var replyPrefix = $"{origPrefix}{Ansi.Yellow}Re: {Ansi.Bold}{Ansi.Green}[{time}] {Ansi.Cyan}{chat.Title} " +
$"{(isPrivate || isChannel ? "" : $"{Ansi.Yellow}{username} ")}";
$"{(isPrivate || isChannel ? "" : $"{Ansi.Yellow}{username} ")}";
var indent = new string(' ', GetActualStringWidth(replyPrefix));
var arrows = $"{(msg.IsOutgoing ? $"{Ansi.Blue}»»»" : $"{Ansi.Magenta}«««")} ";
var rest = $"{text}{(msg.EditDate == 0 ? "" : $"{Ansi.Yellow}*")}";
finalOutput += replyPrefix;
var lines = rest.Split("\n").ToList();
finalOutput += arrows + lines.First();
lines.RemoveAt(0);
@ -424,7 +432,7 @@ namespace telegram
return finalOutput;
}
private static string FormatMessage(Td.TdApi.Update.UpdateMessageContent msg)
{
string text;
@ -458,28 +466,28 @@ namespace telegram
return;
var formattedMessage = FormatMessage(msg);
if (currentChatId != 0 && msg.ChatId != currentChatId)
lock (@lock)
missedMessages.Add(formattedMessage);
else
lock (@lock)
messageQueue.Add(formattedMessage);
if (msg.ChatId == currentChatId)
MarkRead(msg.ChatId, msg.Id);
ScreenUpdate();
}
public static void AddMessageToQueue(Td.TdApi.Update.UpdateMessageContent msg)
{
//handle muted
if (GetChat(msg.ChatId).NotificationSettings.MuteFor > 0 && currentChatId != msg.ChatId
if (GetChat(msg.ChatId).NotificationSettings.MuteFor > 0 && currentChatId != msg.ChatId
|| GetMessage(msg.ChatId, msg.MessageId).EditDate == 0)
return;
var formattedMessage = FormatMessage(msg);
if (currentChatId != 0 && msg.ChatId != currentChatId)
lock (@lock)
missedMessages.Add(formattedMessage);