fix history for limit >100, improve newline input, redo codestyle

This commit is contained in:
Laura Hausmann 2019-12-15 15:03:20 +01:00
parent 132334bedd
commit 93eda081db
Signed by: zotan
GPG key ID: 5EC1D38FFC321311
3 changed files with 1538 additions and 1904 deletions

File diff suppressed because it is too large Load diff

View file

@ -6,604 +6,448 @@ using NeoSmart.Unicode;
using static TdLib.TdApi; using static TdLib.TdApi;
using static telegram.tgcli; using static telegram.tgcli;
namespace telegram namespace telegram {
{ public class Util {
public class Util public static class Ansi {
{ public const string ResetAll = "\x1B[0m";
public static class Ansi public const string Red = "\x1b[31m";
{ public const string Green = "\x1b[32m";
public const string ResetAll = "\x1B[0m"; public const string Yellow = "\x1b[33m";
public const string Red = "\x1b[31m"; public const string Blue = "\x1b[34m";
public const string Green = "\x1b[32m"; public const string Magenta = "\x1b[35m";
public const string Yellow = "\x1b[33m"; public const string Cyan = "\x1b[36m";
public const string Blue = "\x1b[34m"; public const string Bold = "\x1b[1m";
public const string Magenta = "\x1b[35m"; public const string BoldOff = "\x1b[22m";
public const string Cyan = "\x1b[36m"; }
public const string Bold = "\x1b[1m";
public const string BoldOff = "\x1b[22m";
}
public static User GetUser(int uid) public static User GetUser(int uid) {
{ try {
try var uinfo = client.ExecuteAsync(new GetUser {UserId = uid}).Result;
{ return uinfo;
var uinfo = client.ExecuteAsync(new GetUser }
{ catch {
UserId = uid var user = new User();
}).Result; user.FirstName = "null";
return uinfo; user.LastName = "null";
} return user;
catch }
{ }
var user = new User();
user.FirstName = "null";
user.LastName = "null";
return user;
}
}
public static Chat GetChat(long chatId) public static Chat GetChat(long chatId) {
{ try {
try return client.ExecuteAsync(new GetChat {ChatId = chatId}).Result;
{ }
return client.ExecuteAsync(new GetChat catch {
{ return null;
ChatId = chatId }
}).Result; }
}
catch
{
return null;
}
}
public static User GetMe() public static User GetMe() {
{ return client.ExecuteAsync(new GetMe()).Result;
return client.ExecuteAsync(new GetMe()).Result; }
}
public static Message GetMessage(long chatId, long messageId) public static Message GetMessage(long chatId, long messageId) {
{ return client.ExecuteAsync(new GetMessage {ChatId = chatId, MessageId = messageId}).Result;
return client.ExecuteAsync(new GetMessage }
{
ChatId = chatId,
MessageId = messageId
}).Result;
}
public static int GetTotalMessages(long chatId) public static int GetTotalMessages(long chatId) {
{ try {
try var response = client.ExecuteAsync(new SearchChatMessages {ChatId = chatId, Query = "+", Limit = 1});
{ return response.Result.TotalCount;
var response = client.ExecuteAsync(new SearchChatMessages }
{ catch {
ChatId = chatId, return 9999;
Query = "+", }
Limit = 1 }
});
return response.Result.TotalCount;
}
catch
{
return 9999;
}
}
public static List<Message> GetHistory(long chatId, int limit = 5, long fromMessageId = 0, int offset = 0, public static List<Message> GetHistory(long chatId, int limit = 5, long fromMessageId = 0, int offset = 0, bool isSecret = false,
bool isSecret = false, bool skipTotal = false) bool skipTotal = false) {
{ var history = new List<Message>();
var history = new List<Message>(); var total = GetTotalMessages(chatId);
var total = GetTotalMessages(chatId); var chat = GetChat(chatId);
var chat = GetChat(chatId); if (chat.Type is ChatType.ChatTypeSupergroup || isSecret)
if (chat.Type is ChatType.ChatTypeSupergroup || isSecret) skipTotal = true;
skipTotal = true; if (limit > total && !skipTotal)
if (limit > total && !skipTotal) limit = total; limit = total;
for (var i = 5; i > 0; i--) for (var i = 5; i > 0; i--) {
{ if (limit <= 0) {
if (limit <= 0) if (total == 0)
{ return history;
if (total == 0) return history;
lock (@lock)
messageQueue.Add($"{Ansi.Red}[tgcli] " +
$"Limit cannot be less than one. Usage: /history <count>");
return history;
}
var response = client.ExecuteAsync(new GetChatHistory lock (@lock)
{ messageQueue.Add($"{Ansi.Red}[tgcli] " + $"Limit cannot be less than one. Usage: /history <count>");
ChatId = chatId, return history;
FromMessageId = fromMessageId, }
Limit = limit,
Offset = offset,
OnlyLocal = false
})
.Result;
if (response.Messages_.Length < limit && i > 1 && !isSecret) var response = client.ExecuteAsync(new GetChatHistory {
{ ChatId = chatId,
Thread.Sleep(100); FromMessageId = fromMessageId,
continue; Limit = limit,
} Offset = offset,
OnlyLocal = false
})
.Result;
history.AddRange(response.Messages_); if (response.Messages_.Length < limit && i > 1 && !isSecret) {
history.Reverse(); Thread.Sleep(100);
return history; continue;
} }
return history; history.AddRange(response.Messages_);
} history.Reverse();
return history;
}
public static List<Chat> GetUnreadChats(bool all = false) return history;
{ }
var response = client.ExecuteAsync(new GetChats
{
OffsetOrder = long.MaxValue,
Limit = int.MaxValue
}).Result;
return all
? response.ChatIds.Select(GetChat).Where(c => c.UnreadCount > 0 || c.IsMarkedAsUnread).ToList()
: response.ChatIds.Select(GetChat).Where(c => (c.UnreadCount > 0 || c.IsMarkedAsUnread)
&& c.NotificationSettings.MuteFor == 0)
.ToList();
}
public static List<Chat> GetChats() public static List<Chat> GetUnreadChats(bool all = false) {
{ var response = client.ExecuteAsync(new GetChats {OffsetOrder = long.MaxValue, Limit = int.MaxValue}).Result;
var response = client.ExecuteAsync(new GetChats return all
{ ? response.ChatIds.Select(GetChat).Where(c => c.UnreadCount > 0 || c.IsMarkedAsUnread).ToList()
OffsetOrder = long.MaxValue, : response.ChatIds.Select(GetChat).Where(c => (c.UnreadCount > 0 || c.IsMarkedAsUnread) && c.NotificationSettings.MuteFor == 0).ToList();
Limit = int.MaxValue }
}).Result;
return response.ChatIds.Select(GetChat).ToList();
}
public static List<Chat> SearchChatsGlobal(string query) public static List<Chat> GetChats() {
{ var response = client.ExecuteAsync(new GetChats {OffsetOrder = long.MaxValue, Limit = int.MaxValue}).Result;
if (query.TrimStart('@').Length < 5) return response.ChatIds.Select(GetChat).ToList();
{ }
return new List<Chat>();
}
var response = client.ExecuteAsync(new SearchPublicChats public static List<Chat> SearchChatsGlobal(string query) {
{ if (query.TrimStart('@').Length < 5) {
Query = query return new List<Chat>();
}).Result; }
var chats = response.ChatIds.Select(GetChat).ToList(); var response = client.ExecuteAsync(new SearchPublicChats {Query = query}).Result;
chats.AddRange(client.ExecuteAsync(new SearchChats var chats = response.ChatIds.Select(GetChat).ToList();
{
Query = query,
Limit = int.MaxValue
}).Result.ChatIds.Select(GetChat));
return chats; chats.AddRange(client.ExecuteAsync(new SearchChats {Query = query, Limit = int.MaxValue}).Result.ChatIds.Select(GetChat));
}
public static Chat GetChatByUsernameGlobal(string username) return chats;
{ }
try
{
var response = client.ExecuteAsync(new SearchPublicChat
{
Username = username
}).Result;
return response;
}
catch
{
return null;
}
}
public static int GetUserIdByUsername(string username) public static Chat GetChatByUsernameGlobal(string username) {
{ try {
try var response = client.ExecuteAsync(new SearchPublicChat {Username = username}).Result;
{ return response;
var response = client.ExecuteAsync(new SearchPublicChat }
{ catch {
Username = username return null;
}).Result; }
}
if (response.Type is ChatType.ChatTypePrivate priv) public static int GetUserIdByUsername(string username) {
return priv.UserId; try {
return 0; var response = client.ExecuteAsync(new SearchPublicChat {Username = username}).Result;
}
catch
{
return 0;
}
}
public static void AddUserToContacts(int userId, string name) if (response.Type is ChatType.ChatTypePrivate priv)
{ return priv.UserId;
//TODO implement when TDLib 1.6 is released
}
public static List<Chat> GetSecretChats() return 0;
{ }
var response = client.ExecuteAsync(new GetChats catch {
{ return 0;
OffsetOrder = long.MaxValue, }
Limit = int.MaxValue }
}).Result;
return response.ChatIds.Select(GetChat).Where(c => c.Type is ChatType.ChatTypeSecret).ToList();
}
public static void CloseSecretChat(int secretChatId) public static void AddUserToContacts(int userId, string name) {
{ //TODO implement when TDLib 1.6 is released
client.ExecuteAsync(new CloseSecretChat() }
{
SecretChatId = secretChatId
}).Wait();
}
public static Chat CreateSecretChat(int userId) public static List<Chat> GetSecretChats() {
{ var response = client.ExecuteAsync(new GetChats {OffsetOrder = long.MaxValue, Limit = int.MaxValue}).Result;
return client.ExecuteAsync(new CreateNewSecretChat return response.ChatIds.Select(GetChat).Where(c => c.Type is ChatType.ChatTypeSecret).ToList();
{ }
UserId = userId
}).Result;
}
public static void DeleteChatHistory(long chatId) public static void CloseSecretChat(int secretChatId) {
{ client.ExecuteAsync(new CloseSecretChat() {SecretChatId = secretChatId}).Wait();
client.ExecuteAsync(new DeleteChatHistory }
{
ChatId = chatId,
RemoveFromChatList = true,
Revoke = true
}).Wait();
}
public static SecretChat GetSecretChat(int secretChatId) public static Chat CreateSecretChat(int userId) {
{ return client.ExecuteAsync(new CreateNewSecretChat {UserId = userId}).Result;
var response = client.ExecuteAsync(new GetSecretChat }
{
SecretChatId = secretChatId
}).Result;
return response;
}
public static void ClearCurrentConsoleLine() public static void DeleteChatHistory(long chatId) {
{ client.ExecuteAsync(new DeleteChatHistory {ChatId = chatId, RemoveFromChatList = true, Revoke = true}).Wait();
Console.Write("\u001b[2K\r"); }
//Console.SetCursorPosition(0, Console.WindowHeight); public static SecretChat GetSecretChat(int secretChatId) {
//Console.Write(new string(' ', Console.WindowWidth)); var response = client.ExecuteAsync(new GetSecretChat {SecretChatId = secretChatId}).Result;
//Console.SetCursorPosition(0, Console.WindowHeight); return response;
} }
public static string ReadConsolePassword() public static void ClearCurrentConsoleLine() {
{ Console.Write("\u001b[2K\r");
string pass = "";
do
{
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
pass += key.KeyChar;
Console.Write("*");
}
else
{
if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
{
pass = pass.Substring(0, (pass.Length - 1));
Console.Write("\b \b");
}
else if (key.Key == ConsoleKey.Enter)
{
break;
}
}
} while (true);
Console.WriteLine(); //Console.SetCursorPosition(0, Console.WindowHeight);
return pass; //Console.Write(new string(' ', Console.WindowWidth));
} //Console.SetCursorPosition(0, Console.WindowHeight);
}
public static void SendMessage(string message, long chatId, long replyTo = 0) public static string ReadConsolePassword() {
{ string pass = "";
if (string.IsNullOrWhiteSpace(message)) do {
return; ConsoleKeyInfo key = Console.ReadKey(true);
Emojis.ForEach(em => message = message.Replace(em.Item1, em.Item2)); if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter) {
client.ExecuteAsync(new SendMessage pass += key.KeyChar;
{ Console.Write("*");
ChatId = chatId, }
InputMessageContent = new InputMessageContent.InputMessageText else {
{ if (key.Key == ConsoleKey.Backspace && pass.Length > 0) {
Text = new FormattedText() pass = pass.Substring(0, (pass.Length - 1));
{ Console.Write("\b \b");
Text = message }
} else if (key.Key == ConsoleKey.Enter) {
}, break;
ReplyToMessageId = replyTo, }
}); }
currentUserRead = false; } while (true);
}
public static Message EditMessage(string newText, Message message) Console.WriteLine();
{ return pass;
Emojis.ForEach(em => newText = newText.Replace(em.Item1, em.Item2)); }
var msg = client.ExecuteAsync(new EditMessageText public static void SendMessage(string message, long chatId, long replyTo = 0) {
{ if (string.IsNullOrWhiteSpace(message))
ChatId = message.ChatId, return;
MessageId = message.Id,
InputMessageContent = new InputMessageContent.InputMessageText
{
Text = new FormattedText()
{
Text = newText
}
}
}).Result;
return msg; Emojis.ForEach(em => message = message.Replace(em.Item1, em.Item2));
} client.ExecuteAsync(new SendMessage {
ChatId = chatId,
InputMessageContent = new InputMessageContent.InputMessageText {Text = new FormattedText() {Text = message}},
ReplyToMessageId = replyTo,
});
currentUserRead = false;
}
public static void MarkRead(long chatId, long messageId) public static Message EditMessage(string newText, Message message) {
{ Emojis.ForEach(em => newText = newText.Replace(em.Item1, em.Item2));
client.ExecuteAsync(new ViewMessages
{
ChatId = chatId,
MessageIds = new[]
{
messageId
},
ForceRead = true
});
}
public static void MarkUnread(long chatId) var msg = client.ExecuteAsync(new EditMessageText {
{ ChatId = message.ChatId,
client.ExecuteAsync(new ToggleChatIsMarkedAsUnread MessageId = message.Id,
{ InputMessageContent = new InputMessageContent.InputMessageText {Text = new FormattedText() {Text = newText}}
ChatId = chatId, })
IsMarkedAsUnread = true, .Result;
});
}
public static long SearchChatId(string query) return msg;
{ }
try
{
var results = client.ExecuteAsync(new SearchChats
{
Query = query,
Limit = 5
}).Result;
if (query.StartsWith("@")) public static void MarkRead(long chatId, long messageId) {
return results.ChatIds.First(p => client.ExecuteAsync(new ViewMessages {ChatId = chatId, MessageIds = new[] {messageId}, ForceRead = true});
GetChat(p).Type is ChatType.ChatTypePrivate type && }
GetUser(type.UserId).Username == query.Substring(1));
return results.ChatIds.First(p => !(GetChat(p).Type is ChatType.ChatTypeSecret));
}
catch
{
lock (@lock)
messageQueue.Add($"{Ansi.Red}[tgcli] No results found.");
return 0;
}
}
public static int SearchUserInChats(string query) public static void MarkUnread(long chatId) {
{ client.ExecuteAsync(new ToggleChatIsMarkedAsUnread {ChatId = chatId, IsMarkedAsUnread = true,});
var results = client.ExecuteAsync(new SearchChatsOnServer }
{
Query = query,
Limit = 5
}).Result;
if (results.ChatIds.Length == 0)
return 0;
return results.ChatIds
.Select(GetChat)
.Where(p => p.Type is ChatType.ChatTypePrivate)
.Select(p => ((ChatType.ChatTypePrivate) p.Type).UserId)
.First();
}
public static int SearchContacts(string query) public static long SearchChatId(string query) {
{ try {
//TODO implement when TDLib 1.6 is released var results = client.ExecuteAsync(new SearchChats {Query = query, Limit = 5}).Result;
try
{
var results = client.ExecuteAsync(new SearchContacts
{
Query = query,
Limit = 5
}).Result;
return query.StartsWith("@") if (query.StartsWith("@"))
? results.UserIds.First(p => GetUser(p).Username == query.Substring(1)) return results.ChatIds.First(p => GetChat(p).Type is ChatType.ChatTypePrivate type && GetUser(type.UserId).Username == query.Substring(1));
: results.UserIds.First();
}
catch
{
lock (@lock)
messageQueue.Add($"{Ansi.Red}[tgcli] No results found.");
return 0;
}
}
public static void LogOut() return results.ChatIds.First(p => !(GetChat(p).Type is ChatType.ChatTypeSecret));
{ }
lock (@lock) catch {
messageQueue.Add($"{Ansi.Yellow}[tgcli] Logging out..."); lock (@lock)
client.ExecuteAsync(new LogOut()).Wait(); messageQueue.Add($"{Ansi.Red}[tgcli] No results found.");
} return 0;
}
}
public static string GetFormattedUsername(User sender) public static int SearchUserInChats(string query) {
{ var results = client.ExecuteAsync(new SearchChatsOnServer {Query = query, Limit = 5}).Result;
var username = sender.Username; if (results.ChatIds.Length == 0)
if (string.IsNullOrWhiteSpace(username)) return 0;
username = sender.FirstName + " " +
sender.LastName;
else
username = "@" + username;
return username; return results.ChatIds.Select(GetChat)
} .Where(p => p.Type is ChatType.ChatTypePrivate)
.Select(p => ((ChatType.ChatTypePrivate) p.Type).UserId)
.First();
}
public static string FormatTime(long unix) public static int SearchContacts(string query) {
{ //TODO implement when TDLib 1.6 is released
var time = DateTimeOffset.FromUnixTimeSeconds(unix).DateTime.ToLocalTime(); try {
var currentTime = DateTime.Now.ToLocalTime(); var results = client.ExecuteAsync(new SearchContacts {Query = query, Limit = 5}).Result;
return time.ToString(time.Date.Ticks == currentTime.Date.Ticks ? "HH:mm" : "yyyy-MM-dd HH:mm");
}
public static bool IsMessageRead(long chatId, long messageId) return query.StartsWith("@") ? results.UserIds.First(p => GetUser(p).Username == query.Substring(1)) : results.UserIds.First();
{ }
var chat = GetChat(chatId); catch {
return chat.LastReadOutboxMessageId >= messageId; lock (@lock)
} messageQueue.Add($"{Ansi.Red}[tgcli] No results found.");
return 0;
}
}
public static int GetActualStringWidth(string input) public static void LogOut() {
{ lock (@lock)
input = input.Replace(Ansi.Blue, ""); messageQueue.Add($"{Ansi.Yellow}[tgcli] Logging out...");
input = input.Replace(Ansi.Bold, ""); client.ExecuteAsync(new LogOut()).Wait();
input = input.Replace(Ansi.Cyan, ""); }
input = input.Replace(Ansi.Green, "");
input = input.Replace(Ansi.Magenta, "");
input = input.Replace(Ansi.Red, "");
input = input.Replace(Ansi.Yellow, "");
input = input.Replace(Ansi.BoldOff, "");
input = input.Replace(Ansi.ResetAll, "");
return input.Length;
}
public static string GetFormattedStatus(bool isRead) public static string GetFormattedUsername(User sender) {
{ var username = sender.Username;
var output = " "; if (string.IsNullOrWhiteSpace(username))
output += (isRead ? Ansi.Green : Ansi.Red) + "r"; username = sender.FirstName + " " + sender.LastName;
return output + $"{Ansi.ResetAll}]"; else
} username = "@" + username;
public static string TruncateString(string input, int maxLen) return username;
{ }
if (maxLen < 2)
maxLen = 2;
return input.Length <= maxLen ? input : input.Substring(0, maxLen - 1) + "~";
}
public static string TruncateMessageStart(string input, int maxLen) public static string FormatTime(long unix) {
{ var time = DateTimeOffset.FromUnixTimeSeconds(unix).DateTime.ToLocalTime();
if (maxLen < 2) var currentTime = DateTime.Now.ToLocalTime();
maxLen = 2; return time.ToString(time.Date.Ticks == currentTime.Date.Ticks ? "HH:mm" : "yyyy-MM-dd HH:mm");
if (input.Contains("⏎")) }
input = "⏎" + input.Split("⏎").Last();
return input.Length < maxLen ? input : "<" + input.Substring(input.Length - maxLen + 2);
}
public static readonly List<Tuple<string, string>> Emojis = new List<Tuple<string, string>> public static bool IsMessageRead(long chatId, long messageId) {
{ var chat = GetChat(chatId);
new Tuple<string, string>("⏎", "\n"), return chat.LastReadOutboxMessageId >= messageId;
new Tuple<string, string>(":xd:", Emoji.FaceWithTearsOfJoy.Sequence.AsString), }
new Tuple<string, string>(":check:", Emoji.WhiteHeavyCheckMark.Sequence.AsString),
new Tuple<string, string>(":thinking:", Emoji.ThinkingFace.Sequence.AsString),
new Tuple<string, string>(":eyes:", Emoji.Eyes.Sequence.AsString),
new Tuple<string, string>(":heart:", Emoji.RedHeart.Sequence.AsString),
new Tuple<string, string>(":shrug:", Emoji.PersonShrugging.Sequence.AsString),
new Tuple<string, string>(":shrugf:", Emoji.WomanShrugging.Sequence.AsString),
new Tuple<string, string>(":shrugm:", Emoji.ManShrugging.Sequence.AsString)
};
public static readonly List<ConsoleKey> SpecialKeys = new List<ConsoleKey> public static int GetActualStringWidth(string input) {
{ input = input.Replace(Ansi.Blue, "");
ConsoleKey.Backspace, input = input.Replace(Ansi.Bold, "");
ConsoleKey.Tab, input = input.Replace(Ansi.Cyan, "");
ConsoleKey.Clear, input = input.Replace(Ansi.Green, "");
ConsoleKey.Enter, input = input.Replace(Ansi.Magenta, "");
ConsoleKey.Pause, input = input.Replace(Ansi.Red, "");
ConsoleKey.Escape, input = input.Replace(Ansi.Yellow, "");
ConsoleKey.PageUp, input = input.Replace(Ansi.BoldOff, "");
ConsoleKey.PageDown, input = input.Replace(Ansi.ResetAll, "");
ConsoleKey.End, return input.Length;
ConsoleKey.Home, }
ConsoleKey.LeftArrow,
ConsoleKey.UpArrow, public static string GetFormattedStatus(bool isRead) {
ConsoleKey.RightArrow, var output = " ";
ConsoleKey.DownArrow, output += (isRead ? Ansi.Green : Ansi.Red) + "r";
ConsoleKey.Select, return output + $"{Ansi.ResetAll}]";
ConsoleKey.Print, }
ConsoleKey.Execute,
ConsoleKey.PrintScreen, public static string TruncateString(string input, int maxLen) {
ConsoleKey.Insert, if (maxLen < 2)
ConsoleKey.Delete, maxLen = 2;
ConsoleKey.Help, return input.Length <= maxLen ? input : input.Substring(0, maxLen - 1) + "~";
ConsoleKey.LeftWindows, }
ConsoleKey.RightWindows,
ConsoleKey.Applications, public static string TruncateMessageStart(string input, int maxLen) {
ConsoleKey.Sleep, if (maxLen < 2)
ConsoleKey.F1, maxLen = 2;
ConsoleKey.F2, if (input.Contains("⏎ "))
ConsoleKey.F3, input = "⏎ " + input.Split("⏎ ").Last();
ConsoleKey.F4, return input.Length < maxLen ? input : "<" + input.Substring(input.Length - maxLen + 2);
ConsoleKey.F5, }
ConsoleKey.F6,
ConsoleKey.F7, public static readonly List<Tuple<string, string>> Emojis = new List<Tuple<string, string>> {
ConsoleKey.F8, new Tuple<string, string>("⏎ ", "\n"),
ConsoleKey.F9, new Tuple<string, string>(":xd:", Emoji.FaceWithTearsOfJoy.Sequence.AsString),
ConsoleKey.F10, new Tuple<string, string>(":check:", Emoji.WhiteHeavyCheckMark.Sequence.AsString),
ConsoleKey.F11, new Tuple<string, string>(":thinking:", Emoji.ThinkingFace.Sequence.AsString),
ConsoleKey.F12, new Tuple<string, string>(":eyes:", Emoji.Eyes.Sequence.AsString),
ConsoleKey.F13, new Tuple<string, string>(":heart:", Emoji.RedHeart.Sequence.AsString),
ConsoleKey.F14, new Tuple<string, string>(":shrug:", Emoji.PersonShrugging.Sequence.AsString),
ConsoleKey.F15, new Tuple<string, string>(":shrugf:", Emoji.WomanShrugging.Sequence.AsString),
ConsoleKey.F16, new Tuple<string, string>(":shrugm:", Emoji.ManShrugging.Sequence.AsString)
ConsoleKey.F17, };
ConsoleKey.F18,
ConsoleKey.F19, public static readonly List<ConsoleKey> SpecialKeys = new List<ConsoleKey> {
ConsoleKey.F20, ConsoleKey.Backspace,
ConsoleKey.F21, ConsoleKey.Tab,
ConsoleKey.F22, ConsoleKey.Clear,
ConsoleKey.F23, ConsoleKey.Enter,
ConsoleKey.F24, ConsoleKey.Pause,
ConsoleKey.BrowserBack, ConsoleKey.Escape,
ConsoleKey.BrowserForward, ConsoleKey.PageUp,
ConsoleKey.BrowserRefresh, ConsoleKey.PageDown,
ConsoleKey.BrowserStop, ConsoleKey.End,
ConsoleKey.BrowserSearch, ConsoleKey.Home,
ConsoleKey.BrowserFavorites, ConsoleKey.LeftArrow,
ConsoleKey.BrowserHome, ConsoleKey.UpArrow,
ConsoleKey.VolumeMute, ConsoleKey.RightArrow,
ConsoleKey.VolumeDown, ConsoleKey.DownArrow,
ConsoleKey.VolumeUp, ConsoleKey.Select,
ConsoleKey.MediaNext, ConsoleKey.Print,
ConsoleKey.MediaPrevious, ConsoleKey.Execute,
ConsoleKey.MediaStop, ConsoleKey.PrintScreen,
ConsoleKey.MediaPlay, ConsoleKey.Insert,
ConsoleKey.LaunchMail, ConsoleKey.Delete,
ConsoleKey.LaunchMediaSelect, ConsoleKey.Help,
ConsoleKey.LaunchApp1, ConsoleKey.LeftWindows,
ConsoleKey.LaunchApp2, ConsoleKey.RightWindows,
ConsoleKey.Oem1, ConsoleKey.Applications,
ConsoleKey.OemPlus, ConsoleKey.Sleep,
ConsoleKey.OemComma, ConsoleKey.F1,
ConsoleKey.OemMinus, ConsoleKey.F2,
ConsoleKey.OemPeriod, ConsoleKey.F3,
ConsoleKey.Oem2, ConsoleKey.F4,
ConsoleKey.Oem3, ConsoleKey.F5,
ConsoleKey.Oem4, ConsoleKey.F6,
ConsoleKey.Oem5, ConsoleKey.F7,
ConsoleKey.Oem6, ConsoleKey.F8,
ConsoleKey.Oem7, ConsoleKey.F9,
ConsoleKey.Oem8, ConsoleKey.F10,
ConsoleKey.Oem102, ConsoleKey.F11,
ConsoleKey.Process, ConsoleKey.F12,
ConsoleKey.Packet, ConsoleKey.F13,
ConsoleKey.Attention, ConsoleKey.F14,
ConsoleKey.CrSel, ConsoleKey.F15,
ConsoleKey.ExSel, ConsoleKey.F16,
ConsoleKey.EraseEndOfFile, ConsoleKey.F17,
ConsoleKey.Play, ConsoleKey.F18,
ConsoleKey.Zoom, ConsoleKey.F19,
ConsoleKey.NoName, ConsoleKey.F20,
ConsoleKey.Pa1, ConsoleKey.F21,
ConsoleKey.OemClear ConsoleKey.F22,
}; ConsoleKey.F23,
} ConsoleKey.F24,
ConsoleKey.BrowserBack,
ConsoleKey.BrowserForward,
ConsoleKey.BrowserRefresh,
ConsoleKey.BrowserStop,
ConsoleKey.BrowserSearch,
ConsoleKey.BrowserFavorites,
ConsoleKey.BrowserHome,
ConsoleKey.VolumeMute,
ConsoleKey.VolumeDown,
ConsoleKey.VolumeUp,
ConsoleKey.MediaNext,
ConsoleKey.MediaPrevious,
ConsoleKey.MediaStop,
ConsoleKey.MediaPlay,
ConsoleKey.LaunchMail,
ConsoleKey.LaunchMediaSelect,
ConsoleKey.LaunchApp1,
ConsoleKey.LaunchApp2,
ConsoleKey.Oem1,
ConsoleKey.OemPlus,
ConsoleKey.OemComma,
ConsoleKey.OemMinus,
ConsoleKey.OemPeriod,
ConsoleKey.Oem2,
ConsoleKey.Oem3,
ConsoleKey.Oem4,
ConsoleKey.Oem5,
ConsoleKey.Oem6,
ConsoleKey.Oem7,
ConsoleKey.Oem8,
ConsoleKey.Oem102,
ConsoleKey.Process,
ConsoleKey.Packet,
ConsoleKey.Attention,
ConsoleKey.CrSel,
ConsoleKey.ExSel,
ConsoleKey.EraseEndOfFile,
ConsoleKey.Play,
ConsoleKey.Zoom,
ConsoleKey.NoName,
ConsoleKey.Pa1,
ConsoleKey.OemClear
};
}
} }

View file

@ -10,553 +10,498 @@ using static telegram.CommandManager;
// ReSharper disable SwitchStatementMissingSomeEnumCasesNoDefault // ReSharper disable SwitchStatementMissingSomeEnumCasesNoDefault
namespace telegram namespace telegram {
{ /*
/* * TODO:
* TODO: * fuzzy matching for replies?
* fuzzy matching for replies? * unreads are unreliable in secret chats!
* unreads are unreliable in secret chats! * mute,unmute chats
* mute,unmute chats * photo & document download & show externally
* photo & document download & show externally * publish AUR package
* publish AUR package * cursor input nav (up/down history, (alt +) left/right)
* cursor input nav (up/down history, (alt +) left/right) * ref: http://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html#cursor-navigation
* ref: http://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html#cursor-navigation * ref: https://en.wikipedia.org/wiki/ANSI_escape_code#Escape_sequences
* ref: https://en.wikipedia.org/wiki/ANSI_escape_code#Escape_sequences * refactor everything
* refactor everything * re-evaluate ClearCurrentConsoleLine function
* re-evaluate ClearCurrentConsoleLine function * When TDLib 1.6 is released: implement contacts
* When TDLib 1.6 is released: implement contacts */
*/
// ReSharper disable once InconsistentNaming // ReSharper disable once InconsistentNaming
public static class tgcli public static class tgcli {
{ public static volatile Td.TdClient client = new Td.TdClient();
public static volatile Td.TdClient client = new Td.TdClient(); public static string dbdir = "";
public static string dbdir = ""; public static volatile bool authorized;
public static volatile bool authorized; public static volatile string connectionState = "Connecting";
public static volatile string connectionState = "Connecting"; public static long currentChatId = 0;
public static long currentChatId = 0; public static volatile int currentChatUserId = 0;
public static volatile int currentChatUserId = 0; public static volatile bool currentUserRead;
public static volatile bool currentUserRead; public static volatile Td.TdApi.Message lastMessage;
public static volatile Td.TdApi.Message lastMessage; public static volatile bool quitting;
public static volatile bool quitting; public static volatile string currentInputLine = "";
public static volatile string currentInputLine = ""; public static volatile List<string> messageQueue = new List<string>();
public static volatile List<string> messageQueue = new List<string>(); public static volatile List<string> missedMessages = new List<string>();
public static volatile List<string> missedMessages = new List<string>(); public static volatile string prefix = "[tgcli";
public static volatile string prefix = "[tgcli"; public static volatile bool silent;
public static volatile bool silent;
public static volatile object @lock = new object(); public static volatile object @lock = new object();
private static void Main(string[] args) private static void Main(string[] args) {
{ if (args.Length == 1 && args[0] == "-s")
if (args.Length == 1 && args[0] == "-s") silent = true;
silent = true;
dbdir = dbdir = $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}{Path.DirectorySeparatorChar}.tgcli";
$"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}{Path.DirectorySeparatorChar}.tgcli"; if (!Directory.Exists(dbdir))
if (!Directory.Exists(dbdir)) Directory.CreateDirectory(dbdir);
Directory.CreateDirectory(dbdir);
client.Send(new Td.TdApi.SetLogStream client.Send(new Td.TdApi.SetLogStream {
{ LogStream = new Td.TdApi.LogStream.LogStreamFile {Path = Path.Combine(dbdir, "tdlib.log"), MaxFileSize = 10000000}
LogStream = new Td.TdApi.LogStream.LogStreamFile });
{
Path = Path.Combine(dbdir, "tdlib.log"),
MaxFileSize = 10000000
}
});
client.Send(new Td.TdApi.SetLogVerbosityLevel client.Send(new Td.TdApi.SetLogVerbosityLevel {NewVerbosityLevel = 2});
{
NewVerbosityLevel = 2
});
Console.Clear(); Console.Clear();
ClearCurrentConsoleLine(); ClearCurrentConsoleLine();
client.UpdateReceived += HandleUpdate; client.UpdateReceived += HandleUpdate;
OnAuthUpdate(new Td.TdApi.Update.UpdateAuthorizationState() OnAuthUpdate(new Td.TdApi.Update.UpdateAuthorizationState() {
{ AuthorizationState = new Td.TdApi.AuthorizationState.AuthorizationStateWaitTdlibParameters()
AuthorizationState = new Td.TdApi.AuthorizationState.AuthorizationStateWaitTdlibParameters() });
});
while (!authorized) while (!authorized) {
{ Thread.Sleep(1);
Thread.Sleep(1); }
}
ScreenUpdate(); ScreenUpdate();
while (!quitting) while (!quitting)
MainLoop(); MainLoop();
ClearCurrentConsoleLine(); ClearCurrentConsoleLine();
Console.WriteLine($"{Ansi.Yellow}[tgcli] Shutting down...{Ansi.ResetAll}"); Console.WriteLine($"{Ansi.Yellow}[tgcli] Shutting down...{Ansi.ResetAll}");
} }
private static void MainLoop() private static void MainLoop() {
{ var key = Console.ReadKey(true);
var key = Console.ReadKey(true); OnKeyPressed(key);
OnKeyPressed(key); }
}
private static void HandleUpdate(object sender, Td.TdApi.Update e) private static void HandleUpdate(object sender, Td.TdApi.Update e) {
{ switch (e) {
switch (e) case Td.TdApi.Update.UpdateAuthorizationState state:
{ OnAuthUpdate(state);
case Td.TdApi.Update.UpdateAuthorizationState state: break;
OnAuthUpdate(state); case Td.TdApi.Update.UpdateNewMessage message: {
break; Task.Run(() => AddMessageToQueue(message.Message));
case Td.TdApi.Update.UpdateNewMessage message: break;
{ }
Task.Run(() => AddMessageToQueue(message.Message)); case Td.TdApi.Update.UpdateMessageContent message:
break; Task.Run(() => AddMessageToQueue(message));
} Task.Run(() => {
case Td.TdApi.Update.UpdateMessageContent message: var msg = GetMessage(message.ChatId, message.MessageId);
Task.Run(() => AddMessageToQueue(message)); if (msg.IsOutgoing && currentChatId == msg.ChatId) {
Task.Run(() => lastMessage = msg;
{ }
var msg = GetMessage(message.ChatId, message.MessageId); });
if (msg.IsOutgoing && currentChatId == msg.ChatId) break;
{ case Td.TdApi.Update.UpdateMessageSendSucceeded sentMsg:
lastMessage = msg; lastMessage = sentMsg.Message;
} break;
}); case Td.TdApi.Update.UpdateChatReadOutbox update:
break; if (lastMessage != null && lastMessage.ChatId == update.ChatId) {
case Td.TdApi.Update.UpdateMessageSendSucceeded sentMsg: currentUserRead = true;
lastMessage = sentMsg.Message; ScreenUpdate();
break; }
case Td.TdApi.Update.UpdateChatReadOutbox update:
if (lastMessage != null && lastMessage.ChatId == update.ChatId)
{
currentUserRead = true;
ScreenUpdate();
}
break; break;
case Td.TdApi.Update.UpdateConnectionState state: case Td.TdApi.Update.UpdateConnectionState state:
switch (state.State) switch (state.State) {
{ case Td.TdApi.ConnectionState.ConnectionStateConnecting _:
case Td.TdApi.ConnectionState.ConnectionStateConnecting _: connectionState = "Connecting";
connectionState = "Connecting"; if (!authorized)
if (!authorized) return; return;
messageQueue.Add($"{Ansi.Yellow}[tgcli] Connecting to Telegram servers...");
ScreenUpdate();
break;
case Td.TdApi.ConnectionState.ConnectionStateConnectingToProxy _:
connectionState = "Connecting";
if (!authorized) return;
messageQueue.Add($"{Ansi.Yellow}[tgcli] Connecting to Proxy...");
ScreenUpdate();
break;
case Td.TdApi.ConnectionState.ConnectionStateReady _:
if (!authorized) return;
messageQueue.Add($"{Ansi.Yellow}[tgcli] Connected.");
Task.Run(() =>
{
HandleCommand("u");
connectionState = "Ready";
ScreenUpdate();
});
ScreenUpdate();
break;
case Td.TdApi.ConnectionState.ConnectionStateUpdating _:
connectionState = "Updating";
if (!authorized) return;
messageQueue.Add($"{Ansi.Yellow}[tgcli] Updating message cache...");
ScreenUpdate();
break;
case Td.TdApi.ConnectionState.ConnectionStateWaitingForNetwork _:
connectionState = "Waiting for Network";
if (!authorized) return;
messageQueue.Add($"{Ansi.Yellow}[tgcli] Lost connection. Waiting for network...");
ScreenUpdate();
break;
}
break; messageQueue.Add($"{Ansi.Yellow}[tgcli] Connecting to Telegram servers...");
case Td.TdApi.Update.UpdateSecretChat update: ScreenUpdate();
var chat = update.SecretChat; break;
switch (chat.State) case Td.TdApi.ConnectionState.ConnectionStateConnectingToProxy _:
{ connectionState = "Connecting";
case Td.TdApi.SecretChatState.SecretChatStateClosed _: if (!authorized)
lock (@lock) return;
messageQueue.Add($"{Ansi.Red}[tgcli] Secret chat with {chat.Id} was closed.");
ScreenUpdate();
break;
case Td.TdApi.SecretChatState.SecretChatStatePending _:
break;
case Td.TdApi.SecretChatState.SecretChatStateReady _:
lock (@lock)
messageQueue.Add($"{Ansi.Green}[tgcli] Secret chat {chat.Id} connected.");
ScreenUpdate();
break;
}
break; messageQueue.Add($"{Ansi.Yellow}[tgcli] Connecting to Proxy...");
} ScreenUpdate();
} break;
case Td.TdApi.ConnectionState.ConnectionStateReady _:
if (!authorized)
return;
public static void ScreenUpdate() messageQueue.Add($"{Ansi.Yellow}[tgcli] Connected.");
{ Task.Run(() => {
lock (@lock) HandleCommand("u");
{ connectionState = "Ready";
ClearCurrentConsoleLine(); ScreenUpdate();
messageQueue.ForEach(p => Console.WriteLine(p + Ansi.ResetAll)); });
if (messageQueue.Count > 0 && !silent) ScreenUpdate();
Console.Write("\a"); //ring terminal bell break;
messageQueue.Clear(); case Td.TdApi.ConnectionState.ConnectionStateUpdating _:
var status = GetFormattedStatus(currentUserRead); connectionState = "Updating";
var output = prefix; if (!authorized)
if (connectionState != "Ready") return;
output += $" | {connectionState}";
if (currentChatUserId != 0)
output += status;
else
output += "]";
output += " > ";
output += TruncateMessageStart(currentInputLine, Console.LargestWindowWidth - GetActualStringWidth(output));
Console.Write(output);
}
}
private static void OnKeyPressed(ConsoleKeyInfo key) messageQueue.Add($"{Ansi.Yellow}[tgcli] Updating message cache...");
{ ScreenUpdate();
switch (key.Key) break;
{ case Td.TdApi.ConnectionState.ConnectionStateWaitingForNetwork _:
case ConsoleKey.Enter when connectionState != "Ready": connectionState = "Waiting for Network";
lock (@lock) if (!authorized)
messageQueue.Add($"{Ansi.Red}[tgcli] " + return;
"Connection unstable. Check your network connection and try again.");
ScreenUpdate();
break;
case ConsoleKey.Enter when currentInputLine.StartsWith("/"):
{
var command = currentInputLine.Substring(1);
currentInputLine = "";
HandleCommand(command);
ScreenUpdate();
return;
}
case ConsoleKey.Enter when currentChatId == 0:
{
lock (@lock)
messageQueue.Add($"{Ansi.Red}[tgcli] " +
"No chat selected. Select a chat with /open <query>");
ScreenUpdate();
return;
}
case ConsoleKey.Enter:
SendMessage(currentInputLine, currentChatId);
currentInputLine = "";
ScreenUpdate();
break;
case ConsoleKey.Backspace when currentInputLine.Length >= 1:
if (key.Modifiers.HasFlag(ConsoleModifiers.Alt))
{
var lastIndex = currentInputLine.TrimEnd().LastIndexOf(" ", StringComparison.Ordinal);
if (lastIndex < 0)
lastIndex = 0;
currentInputLine = currentInputLine.Substring(0, lastIndex);
if (lastIndex != 0)
currentInputLine += " ";
ScreenUpdate();
return;
}
currentInputLine = currentInputLine.Substring(0, currentInputLine.Length - 1); messageQueue.Add($"{Ansi.Yellow}[tgcli] Lost connection. Waiting for network...");
ScreenUpdate(); ScreenUpdate();
break; break;
default: }
{
switch (key.Key)
{
case ConsoleKey.N when key.Modifiers.HasFlag(ConsoleModifiers.Control):
currentInputLine += "⏎";
ScreenUpdate();
return;
case ConsoleKey.D when key.Modifiers.HasFlag(ConsoleModifiers.Control):
HandleCommand("q");
ScreenUpdate();
return;
case ConsoleKey.Q when key.Modifiers.HasFlag(ConsoleModifiers.Control):
HandleCommand("q");
ScreenUpdate();
return;
case ConsoleKey.E when key.Modifiers.HasFlag(ConsoleModifiers.Control):
HandleCommand("c");
ScreenUpdate();
return;
case ConsoleKey.U when key.Modifiers.HasFlag(ConsoleModifiers.Control):
HandleCommand("u");
ScreenUpdate();
return;
case ConsoleKey.O when key.Modifiers.HasFlag(ConsoleModifiers.Control):
if (string.IsNullOrWhiteSpace(currentInputLine))
currentInputLine = "/o ";
ScreenUpdate();
return;
case ConsoleKey.L when key.Modifiers.HasFlag(ConsoleModifiers.Control):
HandleCommand("cl");
ScreenUpdate();
return;
}
if (!SpecialKeys.Contains(key.Key)) break;
{ case Td.TdApi.Update.UpdateSecretChat update:
currentInputLine += key.KeyChar; var chat = update.SecretChat;
ScreenUpdate(); switch (chat.State) {
} case Td.TdApi.SecretChatState.SecretChatStateClosed _:
lock (@lock)
messageQueue.Add($"{Ansi.Red}[tgcli] Secret chat with {chat.Id} was closed.");
ScreenUpdate();
break;
case Td.TdApi.SecretChatState.SecretChatStatePending _: break;
case Td.TdApi.SecretChatState.SecretChatStateReady _:
lock (@lock)
messageQueue.Add($"{Ansi.Green}[tgcli] Secret chat {chat.Id} connected.");
ScreenUpdate();
break;
}
break; break;
} }
} }
}
private static void OnAuthUpdate(Td.TdApi.Update.UpdateAuthorizationState state) public static void ScreenUpdate() {
{ lock (@lock) {
switch (state.AuthorizationState) ClearCurrentConsoleLine();
{ messageQueue.ForEach(p => Console.WriteLine(p + Ansi.ResetAll));
case Td.TdApi.AuthorizationState.AuthorizationStateWaitTdlibParameters _: if (messageQueue.Count > 0 && !silent)
client.Send(new Td.TdApi.SetTdlibParameters Console.Write("\a"); //ring terminal bell
{ messageQueue.Clear();
Parameters = new Td.TdApi.TdlibParameters var status = GetFormattedStatus(currentUserRead);
{ var output = prefix;
ApiId = 600606, if (connectionState != "Ready")
ApiHash = "c973f46778be4b35481ce45e93271e82", output += $" | {connectionState}";
DatabaseDirectory = dbdir, if (currentChatUserId != 0)
UseMessageDatabase = true, output += status;
SystemLanguageCode = "en_US", else
DeviceModel = Environment.MachineName, output += "]";
SystemVersion = ".NET Core CLR " + Environment.Version, output += " > ";
ApplicationVersion = "0.1a", output += TruncateMessageStart(currentInputLine, Console.LargestWindowWidth - GetActualStringWidth(output));
EnableStorageOptimizer = true, Console.Write(output);
UseSecretChats = true }
} }
});
break;
case Td.TdApi.AuthorizationState.AuthorizationStateWaitEncryptionKey _:
client.Send(new Td.TdApi.CheckDatabaseEncryptionKey());
break;
case Td.TdApi.AuthorizationState.AuthorizationStateWaitPhoneNumber _:
{
Console.Write("[tgcli] login> ");
var phone = Console.ReadLine();
client.Send(new Td.TdApi.SetAuthenticationPhoneNumber
{
PhoneNumber = phone
});
break;
}
case Td.TdApi.AuthorizationState.AuthorizationStateWaitCode _:
{
Console.Write("[tgcli] code> ");
var code = Console.ReadLine();
client.Send(new Td.TdApi.CheckAuthenticationCode
{
Code = code
});
break;
}
case Td.TdApi.AuthorizationState.AuthorizationStateWaitPassword _:
{
Console.Write("[tgcli] 2fa password> ");
var pass = ReadConsolePassword();
client.Send(new Td.TdApi.CheckAuthenticationPassword
{
Password = pass
});
break;
}
case Td.TdApi.AuthorizationState.AuthorizationStateReady _:
Console.WriteLine("[tgcli] logged in.");
authorized = true;
connectionState = "Ready";
break;
case Td.TdApi.AuthorizationState.AuthorizationStateClosed _:
messageQueue.Add($"{Ansi.Yellow}[tgcli] Logged out successfully. All local data has been deleted.");
ScreenUpdate();
Environment.Exit(0);
break;
case Td.TdApi.AuthorizationState.AuthorizationStateClosing _:
messageQueue.Add($"{Ansi.Yellow}[tgcli] Logging out...");
ScreenUpdate();
break;
case Td.TdApi.AuthorizationState.AuthorizationStateLoggingOut _:
if (authorized) return;
Console.WriteLine(
"[tgcli] This session has been destroyed externally, to fix this delete ~/.tgcli");
Environment.Exit(1);
break;
default:
Console.WriteLine($"unknown state: {state.AuthorizationState.DataType}");
Environment.Exit(1);
break;
}
}
public static string FormatMessage(Td.TdApi.Message msg) private static void OnKeyPressed(ConsoleKeyInfo key) {
{ switch (key.Key) {
string text; case ConsoleKey.Enter when connectionState != "Ready":
if (msg.Content is Td.TdApi.MessageContent.MessageText messageText) lock (@lock)
text = messageText.Text.Text; messageQueue.Add($"{Ansi.Red}[tgcli] " + "Connection unstable. Check your network connection and try again.");
else if (msg.Content is Td.TdApi.MessageContent.MessagePhoto photo) ScreenUpdate();
text = !string.IsNullOrWhiteSpace(photo.Caption.Text) break;
? $"[unsupported {msg.Content.DataType}] {photo.Caption.Text}" case ConsoleKey.Enter when currentInputLine.StartsWith("/"): {
: $"[unsupported {msg.Content.DataType}]"; var command = currentInputLine.Substring(1);
else if (msg.Content is Td.TdApi.MessageContent.MessageDocument document) currentInputLine = "";
text = !string.IsNullOrWhiteSpace(document.Caption.Text) HandleCommand(command);
? $"[unsupported {msg.Content.DataType}] {document.Caption.Text}" ScreenUpdate();
: $"[unsupported {msg.Content.DataType}]"; return;
else }
text = $"[unsupported {msg.Content.DataType}]"; case ConsoleKey.Enter when currentChatId == 0: {
var sender = GetUser(msg.SenderUserId); lock (@lock)
var chat = GetChat(msg.ChatId); messageQueue.Add($"{Ansi.Red}[tgcli] " + "No chat selected. Select a chat with /open <query>");
var username = TruncateString(GetFormattedUsername(sender), 10); ScreenUpdate();
var time = FormatTime(msg.Date); return;
var isChannel = msg.IsChannelPost; }
var isPrivate = chat.Type is Td.TdApi.ChatType.ChatTypePrivate || case ConsoleKey.Enter:
chat.Type is Td.TdApi.ChatType.ChatTypeSecret; SendMessage(currentInputLine, currentChatId);
var isSecret = chat.Type is Td.TdApi.ChatType.ChatTypeSecret; currentInputLine = "";
var isReply = msg.ReplyToMessageId != 0; ScreenUpdate();
break;
case ConsoleKey.Backspace when currentInputLine.Length >= 1:
if (key.Modifiers.HasFlag(ConsoleModifiers.Alt)) {
var lastIndex = currentInputLine.TrimEnd().LastIndexOf(" ", StringComparison.Ordinal);
if (lastIndex < 0)
lastIndex = 0;
currentInputLine = currentInputLine.Substring(0, lastIndex);
if (lastIndex != 0)
currentInputLine += " ";
ScreenUpdate();
return;
}
chat.Title = TruncateString(chat.Title, 20); currentInputLine = currentInputLine.Substring(0, currentInputLine.Length - 1);
ScreenUpdate();
break;
default: {
switch (key.Key) {
case ConsoleKey.N when key.Modifiers.HasFlag(ConsoleModifiers.Control):
currentInputLine += "⏎ ";
ScreenUpdate();
return;
case ConsoleKey.D when key.Modifiers.HasFlag(ConsoleModifiers.Control):
HandleCommand("q");
ScreenUpdate();
return;
case ConsoleKey.Q when key.Modifiers.HasFlag(ConsoleModifiers.Control):
HandleCommand("q");
ScreenUpdate();
return;
case ConsoleKey.E when key.Modifiers.HasFlag(ConsoleModifiers.Control):
HandleCommand("c");
ScreenUpdate();
return;
case ConsoleKey.U when key.Modifiers.HasFlag(ConsoleModifiers.Control):
HandleCommand("u");
ScreenUpdate();
return;
case ConsoleKey.O when key.Modifiers.HasFlag(ConsoleModifiers.Control):
if (string.IsNullOrWhiteSpace(currentInputLine))
currentInputLine = "/o ";
ScreenUpdate();
return;
case ConsoleKey.L when key.Modifiers.HasFlag(ConsoleModifiers.Control):
HandleCommand("cl");
ScreenUpdate();
return;
}
Td.TdApi.Message replyMessage; if (!SpecialKeys.Contains(key.Key)) {
currentInputLine += key.KeyChar;
ScreenUpdate();
}
var msgPrefix = break;
$"{Ansi.Bold}{Ansi.Green}[{time}] {(isSecret ? $"{Ansi.Red}[sec] " : "")}{Ansi.Cyan}{chat.Title} " + }
$"{(isPrivate || isChannel ? "" : $"{Ansi.Yellow}{username} ")}"; }
var finalOutput = msgPrefix; }
var indent = new string(' ', GetActualStringWidth(msgPrefix)); private static void OnAuthUpdate(Td.TdApi.Update.UpdateAuthorizationState state) {
var arrows = $"{(msg.IsOutgoing ? $"{Ansi.Blue}»»»" : $"{Ansi.Magenta}«««")} "; switch (state.AuthorizationState) {
case Td.TdApi.AuthorizationState.AuthorizationStateWaitTdlibParameters _:
client.Send(new Td.TdApi.SetTdlibParameters {
Parameters = new Td.TdApi.TdlibParameters {
ApiId = 600606,
ApiHash = "c973f46778be4b35481ce45e93271e82",
DatabaseDirectory = dbdir,
UseMessageDatabase = true,
SystemLanguageCode = "en_US",
DeviceModel = Environment.MachineName,
SystemVersion = ".NET Core CLR " + Environment.Version,
ApplicationVersion = "0.1a",
EnableStorageOptimizer = true,
UseSecretChats = true
}
});
break;
case Td.TdApi.AuthorizationState.AuthorizationStateWaitEncryptionKey _:
client.Send(new Td.TdApi.CheckDatabaseEncryptionKey());
break;
case Td.TdApi.AuthorizationState.AuthorizationStateWaitPhoneNumber _: {
Console.Write("[tgcli] login> ");
var phone = Console.ReadLine();
client.Send(new Td.TdApi.SetAuthenticationPhoneNumber {PhoneNumber = phone});
break;
}
case Td.TdApi.AuthorizationState.AuthorizationStateWaitCode _: {
Console.Write("[tgcli] code> ");
var code = Console.ReadLine();
client.Send(new Td.TdApi.CheckAuthenticationCode {Code = code});
break;
}
case Td.TdApi.AuthorizationState.AuthorizationStateWaitPassword _: {
Console.Write("[tgcli] 2fa password> ");
var pass = ReadConsolePassword();
client.Send(new Td.TdApi.CheckAuthenticationPassword {Password = pass});
break;
}
case Td.TdApi.AuthorizationState.AuthorizationStateReady _:
Console.WriteLine("[tgcli] logged in.");
authorized = true;
connectionState = "Ready";
break;
case Td.TdApi.AuthorizationState.AuthorizationStateClosed _:
messageQueue.Add($"{Ansi.Yellow}[tgcli] Logged out successfully. All local data has been deleted.");
ScreenUpdate();
Environment.Exit(0);
break;
case Td.TdApi.AuthorizationState.AuthorizationStateClosing _:
messageQueue.Add($"{Ansi.Yellow}[tgcli] Logging out...");
ScreenUpdate();
break;
case Td.TdApi.AuthorizationState.AuthorizationStateLoggingOut _:
if (authorized)
return;
if (isReply) Console.WriteLine("[tgcli] This session has been destroyed externally, to fix this delete ~/.tgcli");
{ Environment.Exit(1);
try break;
{ default:
replyMessage = GetMessage(chat.Id, msg.ReplyToMessageId); Console.WriteLine($"unknown state: {state.AuthorizationState.DataType}");
finalOutput = $"{FormatMessageReply(replyMessage, msgPrefix)}"; Environment.Exit(1);
} break;
catch }
{ }
//ignored; reply to deleted msg
}
}
var rest = $"{text}{(msg.EditDate == 0 ? "" : $"{Ansi.Yellow}*")}"; public static string FormatMessage(Td.TdApi.Message msg) {
var lines = rest.Split("\n").ToList(); string text;
if (!isReply) if (msg.Content is Td.TdApi.MessageContent.MessageText messageText)
{ text = messageText.Text.Text;
finalOutput += arrows + lines.First(); else if (msg.Content is Td.TdApi.MessageContent.MessagePhoto photo)
lines.RemoveAt(0); text = !string.IsNullOrWhiteSpace(photo.Caption.Text)
} ? $"[unsupported {msg.Content.DataType}] {photo.Caption.Text}"
: $"[unsupported {msg.Content.DataType}]";
else if (msg.Content is Td.TdApi.MessageContent.MessageDocument document)
text = !string.IsNullOrWhiteSpace(document.Caption.Text)
? $"[unsupported {msg.Content.DataType}] {document.Caption.Text}"
: $"[unsupported {msg.Content.DataType}]";
else
text = $"[unsupported {msg.Content.DataType}]";
var sender = GetUser(msg.SenderUserId);
var chat = GetChat(msg.ChatId);
var username = TruncateString(GetFormattedUsername(sender), 10);
var time = FormatTime(msg.Date);
var isChannel = msg.IsChannelPost;
var isPrivate = chat.Type is Td.TdApi.ChatType.ChatTypePrivate || chat.Type is Td.TdApi.ChatType.ChatTypeSecret;
var isSecret = chat.Type is Td.TdApi.ChatType.ChatTypeSecret;
var isReply = msg.ReplyToMessageId != 0;
lines.ForEach(l => finalOutput += "\n" + indent + arrows + l); chat.Title = TruncateString(chat.Title, 20);
return finalOutput; Td.TdApi.Message replyMessage;
}
public static string FormatMessageReply(Td.TdApi.Message msg, string origPrefix) var msgPrefix = $"{Ansi.Bold}{Ansi.Green}[{time}] {(isSecret ? $"{Ansi.Red}[sec] " : "")}{Ansi.Cyan}{chat.Title} "
{ + $"{(isPrivate || isChannel ? "" : $"{Ansi.Yellow}{username} ")}";
string text; var finalOutput = msgPrefix;
if (msg.Content is Td.TdApi.MessageContent.MessageText messageText)
text = messageText.Text.Text;
else
text = $"[unsupported {msg.Content.DataType}]";
var sender = GetUser(msg.SenderUserId);
var chat = GetChat(msg.ChatId);
var username = GetFormattedUsername(sender);
var time = FormatTime(msg.Date);
var isChannel = msg.IsChannelPost;
var isPrivate = chat.Type is Td.TdApi.ChatType.ChatTypePrivate ||
chat.Type is Td.TdApi.ChatType.ChatTypeSecret;
var isSecret = chat.Type is Td.TdApi.ChatType.ChatTypeSecret;
chat.Title = TruncateString(chat.Title, 20); var indent = new string(' ', GetActualStringWidth(msgPrefix));
var arrows = $"{(msg.IsOutgoing ? $"{Ansi.Blue}»»»" : $"{Ansi.Magenta}«««")} ";
var finalOutput = ""; if (isReply) {
var replyPrefix = $"{origPrefix}{Ansi.Yellow}Re: {Ansi.Bold}{Ansi.Green}[{time}] " + try {
$"{(isSecret ? $"{Ansi.Red}[sec] " : "")}{Ansi.Cyan}{chat.Title} " + replyMessage = GetMessage(chat.Id, msg.ReplyToMessageId);
$"{(isPrivate || isChannel ? "" : $"{Ansi.Yellow}{username} ")}"; finalOutput = $"{FormatMessageReply(replyMessage, msgPrefix)}";
}
catch {
//ignored; reply to deleted msg
}
}
var indent = new string(' ', GetActualStringWidth(replyPrefix)); var rest = $"{text}{(msg.EditDate == 0 ? "" : $"{Ansi.Yellow}*")}";
var arrows = $"{(msg.IsOutgoing ? $"{Ansi.Blue}»»»" : $"{Ansi.Magenta}«««")} "; var lines = rest.Split("\n").ToList();
if (!isReply) {
finalOutput += arrows + lines.First();
lines.RemoveAt(0);
}
var rest = $"{text}{(msg.EditDate == 0 ? "" : $"{Ansi.Yellow}*")}"; lines.ForEach(l => finalOutput += "\n" + indent + arrows + l);
finalOutput += replyPrefix; return finalOutput;
}
var lines = rest.Split("\n").ToList(); public static string FormatMessageReply(Td.TdApi.Message msg, string origPrefix) {
finalOutput += arrows + lines.First(); string text;
lines.RemoveAt(0); if (msg.Content is Td.TdApi.MessageContent.MessageText messageText)
lines.ForEach(l => finalOutput += "\n" + indent + arrows + l); text = messageText.Text.Text;
else
text = $"[unsupported {msg.Content.DataType}]";
var sender = GetUser(msg.SenderUserId);
var chat = GetChat(msg.ChatId);
var username = GetFormattedUsername(sender);
var time = FormatTime(msg.Date);
var isChannel = msg.IsChannelPost;
var isPrivate = chat.Type is Td.TdApi.ChatType.ChatTypePrivate || chat.Type is Td.TdApi.ChatType.ChatTypeSecret;
var isSecret = chat.Type is Td.TdApi.ChatType.ChatTypeSecret;
return finalOutput; chat.Title = TruncateString(chat.Title, 20);
}
private static string FormatMessage(Td.TdApi.Update.UpdateMessageContent msg) var finalOutput = "";
{ var replyPrefix = $"{origPrefix}{Ansi.Yellow}Re: {Ansi.Bold}{Ansi.Green}[{time}] "
string text; + $"{(isSecret ? $"{Ansi.Red}[sec] " : "")}{Ansi.Cyan}{chat.Title} "
if (msg.NewContent is Td.TdApi.MessageContent.MessageText messageText) + $"{(isPrivate || isChannel ? "" : $"{Ansi.Yellow}{username} ")}";
text = messageText.Text.Text;
else
text = $"[unsupported {msg.NewContent.DataType}]";
var message = GetMessage(msg.ChatId, msg.MessageId);
var sender = GetUser(message.SenderUserId);
var chat = GetChat(msg.ChatId);
var username = GetFormattedUsername(sender);
var time = FormatTime(message.EditDate);
var isChannel = message.IsChannelPost;
var isPrivate = chat.Type is Td.TdApi.ChatType.ChatTypePrivate;
return $"{Ansi.Bold}{Ansi.Green}[{time}] {Ansi.Cyan}{chat.Title} " + var indent = new string(' ', GetActualStringWidth(replyPrefix));
$"{(isPrivate || isChannel ? "" : $"{Ansi.Yellow}{username} ")}" + var arrows = $"{(msg.IsOutgoing ? $"{Ansi.Blue}»»»" : $"{Ansi.Magenta}«««")} ";
$"{(message.IsOutgoing ? $"{Ansi.Blue}»»»" : $"{Ansi.Magenta}«««")} " +
$"{text}" +
$"{Ansi.Yellow}*";
}
public static void AddMessageToQueue(Td.TdApi.Message msg) var rest = $"{text}{(msg.EditDate == 0 ? "" : $"{Ansi.Yellow}*")}";
{
//handle muted
if (GetChat(msg.ChatId).NotificationSettings.MuteFor > 0 && currentChatId != msg.ChatId)
return;
//we aren't interested in backlog finalOutput += replyPrefix;
if (connectionState != "Ready")
return;
var formattedMessage = FormatMessage(msg); var lines = rest.Split("\n").ToList();
finalOutput += arrows + lines.First();
lines.RemoveAt(0);
lines.ForEach(l => finalOutput += "\n" + indent + arrows + l);
if (currentChatId != 0 && msg.ChatId != currentChatId) return finalOutput;
lock (@lock) }
missedMessages.Add(formattedMessage);
else
lock (@lock)
messageQueue.Add(formattedMessage);
if (msg.ChatId == currentChatId) private static string FormatMessage(Td.TdApi.Update.UpdateMessageContent msg) {
MarkRead(msg.ChatId, msg.Id); string text;
ScreenUpdate(); if (msg.NewContent is Td.TdApi.MessageContent.MessageText messageText)
} text = messageText.Text.Text;
else
text = $"[unsupported {msg.NewContent.DataType}]";
var message = GetMessage(msg.ChatId, msg.MessageId);
var sender = GetUser(message.SenderUserId);
var chat = GetChat(msg.ChatId);
var username = GetFormattedUsername(sender);
var time = FormatTime(message.EditDate);
var isChannel = message.IsChannelPost;
var isPrivate = chat.Type is Td.TdApi.ChatType.ChatTypePrivate;
public static void AddMessageToQueue(Td.TdApi.Update.UpdateMessageContent msg) return $"{Ansi.Bold}{Ansi.Green}[{time}] {Ansi.Cyan}{chat.Title} "
{ + $"{(isPrivate || isChannel ? "" : $"{Ansi.Yellow}{username} ")}"
//handle muted + $"{(message.IsOutgoing ? $"{Ansi.Blue}»»»" : $"{Ansi.Magenta}«««")} "
if (GetChat(msg.ChatId).NotificationSettings.MuteFor > 0 && currentChatId != msg.ChatId + $"{text}"
|| GetMessage(msg.ChatId, msg.MessageId).EditDate == 0) + $"{Ansi.Yellow}*";
return; }
var formattedMessage = FormatMessage(msg); public static void AddMessageToQueue(Td.TdApi.Message msg) {
//handle muted
if (GetChat(msg.ChatId).NotificationSettings.MuteFor > 0 && currentChatId != msg.ChatId)
return;
if (currentChatId != 0 && msg.ChatId != currentChatId) //we aren't interested in backlog
lock (@lock) if (connectionState != "Ready")
missedMessages.Add(formattedMessage); return;
else
lock (@lock) var formattedMessage = FormatMessage(msg);
messageQueue.Add(formattedMessage);
ScreenUpdate(); 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 || GetMessage(msg.ChatId, msg.MessageId).EditDate == 0)
return;
var formattedMessage = FormatMessage(msg);
if (currentChatId != 0 && msg.ChatId != currentChatId)
lock (@lock)
missedMessages.Add(formattedMessage);
else
lock (@lock)
messageQueue.Add(formattedMessage);
ScreenUpdate();
}
}
} }