fix read indicator, fix history, small refactor

This commit is contained in:
Laura Hausmann 2019-12-12 18:55:43 +01:00
parent a9d19b2b25
commit 21220e978e
Signed by: zotan
GPG key ID: 5EC1D38FFC321311
3 changed files with 220 additions and 196 deletions

View file

@ -1,5 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using TdLib; using TdLib;
using static telegram.tgcli; using static telegram.tgcli;
@ -20,14 +19,14 @@ namespace telegram
var query = command.Substring(split[0].Length); var query = command.Substring(split[0].Length);
var chatId = searchChatId(query); var chatId = SearchChatId(query);
if (chatId == 0) return; if (chatId == 0) return;
currentChatId = 0; currentChatId = 0;
currentChatUserId = 0; currentChatUserId = 0;
currentUserRead = false; currentUserRead = false;
var chat = getChat(chatId); var chat = GetChat(chatId);
if (chat.Type is TdApi.ChatType.ChatTypePrivate privChat) if (chat.Type is TdApi.ChatType.ChatTypePrivate privChat)
{ {
currentChatUserId = privChat.UserId; currentChatUserId = privChat.UserId;
@ -35,38 +34,39 @@ namespace telegram
currentChatId = chat.Id; currentChatId = chat.Id;
prefix = $"[{chat.Title}"; prefix = $"[{chat.Title}";
lock (_lock) lock (@lock)
{ {
messageQueue.Add($"{Ansi.Yellow}[tgcli] Opening chat: {chat.Title}"); messageQueue.Add($"{Ansi.Yellow}[tgcli] Opening chat: {chat.Title}");
messageQueue.Add($"{Ansi.Yellow}" + $"[tgcli] You have {chat.UnreadCount} unread message" + $"{(chat.UnreadCount == 1 ? "." : "s.")}"); messageQueue.Add($"{Ansi.Yellow}" + $"[tgcli] You have {chat.UnreadCount} unread message" + $"{(chat.UnreadCount == 1 ? "." : "s.")}");
while (getHistory(chatId, 50).Count == 1) while (GetHistory(chatId, 50).Count == 1)
{ {
getHistory(chatId, 10); GetHistory(chatId, 10);
} }
if (chat.UnreadCount >= 5) if (chat.UnreadCount >= 5)
{ {
var capped = chat.UnreadCount > 50; var capped = chat.UnreadCount > 50;
getHistory(chatId, capped ? 50 : chat.UnreadCount).ForEach(AddMessageToQueue); GetHistory(chatId, capped ? 50 : chat.UnreadCount).ForEach(AddMessageToQueue);
if (capped) messageQueue.Add($"{Ansi.Yellow}[tgcli] " + $"Showing 50 of {chat.UnreadCount} unread messages."); if (capped) messageQueue.Add($"{Ansi.Yellow}[tgcli] " + $"Showing 50 of {chat.UnreadCount} unread messages.");
} }
else if (chat.UnreadCount > 0) else if (chat.UnreadCount > 0)
{ {
var unreads = getHistory(chatId, chat.UnreadCount); var unreads = GetHistory(chatId, chat.UnreadCount);
var rest = getHistory(chatId, 5 - unreads.Count, unreads.First().Id); var rest = GetHistory(chatId, 5 - unreads.Count, unreads.First().Id);
rest.ForEach(AddMessageToQueue); rest.ForEach(AddMessageToQueue);
messageQueue.Add($"{Ansi.Yellow}[tgcli] ---UNREAD---"); messageQueue.Add($"{Ansi.Yellow}[tgcli] ---UNREAD---");
unreads.ForEach(AddMessageToQueue); unreads.ForEach(AddMessageToQueue);
} }
else else
{ {
getHistory(chatId).ForEach(AddMessageToQueue); GetHistory(chatId).ForEach(AddMessageToQueue);
} }
} }
markRead(chat.Id, getHistory(chat.Id).First().Id); var history = GetHistory(currentChatId, 50);
var history = getHistory(currentChatId, 50); if (history.Count != 0)
var last = history.FirstOrDefault(p => p.IsOutgoing); MarkRead(chat.Id, history.First().Id);
var last = history.LastOrDefault(p => p.IsOutgoing);
if (last == null) if (last == null)
{ {
currentUserRead = true; currentUserRead = true;
@ -74,12 +74,12 @@ namespace telegram
} }
lastMessage = last; lastMessage = last;
currentUserRead = isMessageRead(last.ChatId, last.Id); currentUserRead = IsMessageRead(last.ChatId, last.Id);
} }
else if (split[0].Equals("cu") || split[0].Equals("closeunread")) else if (split[0].Equals("cu") || split[0].Equals("closeunread"))
{ {
if (currentChatId == 0) return; if (currentChatId == 0) return;
markUnread(currentChatId); MarkUnread(currentChatId);
command = "close"; command = "close";
continue; continue;
} }
@ -93,7 +93,7 @@ namespace telegram
prefix = "[tgcli"; prefix = "[tgcli";
lock (_lock) lock (@lock)
{ {
messageQueue.Add($"{Ansi.Yellow}[tgcli] Closing chat."); messageQueue.Add($"{Ansi.Yellow}[tgcli] Closing chat.");
var count = missedMessages.Count; var count = missedMessages.Count;
@ -107,17 +107,17 @@ namespace telegram
{ {
if (split.Length != 1 && split.Length != 2 || currentChatId == 0) 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>"); lock (@lock) messageQueue.Add($"{Ansi.Red}[tgcli] " + "No chat selected. Select a chat with /open <query>");
return; return;
} }
var history = split.Length > 1 && int.TryParse(split[1], out var limit) var history = split.Length > 1 && int.TryParse(split[1], out var limit)
? getHistory(currentChatId, limit) ? GetHistory(currentChatId, limit)
: getHistory(currentChatId); : GetHistory(currentChatId);
lock (_lock) lock (@lock)
{ {
messageQueue.Add($"{Ansi.Yellow}[tgcli] Last {history.Count} messages in " + $"{getChat(currentChatId).Title}"); messageQueue.Add($"{Ansi.Yellow}[tgcli] Last {history.Count} messages in " + $"{GetChat(currentChatId).Title}");
} }
foreach (var msg in history) foreach (var msg in history)
@ -127,7 +127,7 @@ namespace telegram
} }
else if (split[0].Equals("clear") || split[0].Equals("cl")) else if (split[0].Equals("clear") || split[0].Equals("cl"))
{ {
lock (_lock) lock (@lock)
{ {
Console.Clear(); Console.Clear();
} }
@ -138,9 +138,9 @@ namespace telegram
} }
else if (split[0].Equals("unreads") || split[0].Equals("u")) else if (split[0].Equals("unreads") || split[0].Equals("u"))
{ {
var unreads = getUnreadChats(split.Length == 2 && split[1].Equals("all")); var unreads = GetUnreadChats(split.Length == 2 && split[1].Equals("all"));
lock (_lock) lock (@lock)
{ {
messageQueue.Add($"{Ansi.Yellow}[tgcli] You have {unreads.Count} unread chats."); messageQueue.Add($"{Ansi.Yellow}[tgcli] You have {unreads.Count} unread chats.");
unreads.ForEach(chat => unreads.ForEach(chat =>
@ -167,14 +167,14 @@ namespace telegram
if (lastMessage == null) if (lastMessage == null)
{ {
//try to find last message //try to find last message
var history = getHistory(currentChatId, 50); var history = GetHistory(currentChatId, 50);
var last = history.LastOrDefault(p => p.IsOutgoing); var last = history.LastOrDefault(p => p.IsOutgoing);
if (last == null) return; if (last == null) return;
lastMessage = last; lastMessage = last;
} }
var message = command.Substring(split[0].Length); var message = command.Substring(split[0].Length);
editMessage(message, lastMessage); EditMessage(message, lastMessage);
} }
break; break;

View file

@ -1,7 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using NeoSmart.Unicode; using NeoSmart.Unicode;
using static TdLib.TdApi; using static TdLib.TdApi;
@ -24,7 +24,7 @@ namespace telegram
public const string BoldOff = "\x1b[22m"; public const string BoldOff = "\x1b[22m";
} }
public static User getUser(int uid) public static User GetUser(int uid)
{ {
try try
{ {
@ -43,7 +43,7 @@ namespace telegram
} }
} }
public static Chat getChat(long chatId) public static Chat GetChat(long chatId)
{ {
return client.ExecuteAsync(new GetChat return client.ExecuteAsync(new GetChat
{ {
@ -51,12 +51,12 @@ namespace telegram
}).Result; }).Result;
} }
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 return client.ExecuteAsync(new GetMessage
{ {
@ -65,31 +65,56 @@ namespace telegram
}).Result; }).Result;
} }
public static List<Message> getHistory(long chatId, int limit = 5, long fromMessageId = 0, int offset = 0) public static int GetTotalMessages(long chatId)
{
var response = client.ExecuteAsync(new SearchChatMessages
{
ChatId = chatId,
Query = "+",
Limit = 1
});
return response.Result.TotalCount;
}
public static List<Message> GetHistory(long chatId, int limit = 5, long fromMessageId = 0, int offset = 0)
{ {
var history = new List<Message>(); var history = new List<Message>();
if (limit <= 0) var total = GetTotalMessages(chatId);
if (limit > total) limit = total;
for (var i = 5; i > 0; i--)
{ {
lock (_lock) if (limit <= 0)
messageQueue.Add($"{Ansi.Red}[tgcli] " + {
$"Limit cannot be less than one. Usage: /history <count>"); lock (@lock) messageQueue.Add($"{Ansi.Red}[tgcli] " + $"Limit cannot be less than one. Usage: /history <count>");
return history;
}
var response = client.ExecuteAsync(new GetChatHistory
{
ChatId = chatId,
FromMessageId = fromMessageId,
Limit = limit,
Offset = offset,
OnlyLocal = false
})
.Result;
if (response.Messages_.Length < limit && i > 1)
{
Thread.Sleep(100);
continue;
}
history.AddRange(response.Messages_);
history.Reverse();
return history; return history;
} }
var response = client.ExecuteAsync(new GetChatHistory
{
ChatId = chatId,
FromMessageId = fromMessageId,
Limit = limit,
Offset = offset,
OnlyLocal = false
}).Result;
history.AddRange(response.Messages_);
history.Reverse();
return history; return history;
} }
public static List<Chat> getUnreadChats(bool all = false) public static List<Chat> GetUnreadChats(bool all = false)
{ {
var response = client.ExecuteAsync(new GetChats var response = client.ExecuteAsync(new GetChats
{ {
@ -97,8 +122,8 @@ namespace telegram
Limit = int.MaxValue Limit = int.MaxValue
}).Result; }).Result;
return all 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).ToList()
: response.ChatIds.Select(getChat).Where(c => (c.UnreadCount > 0 || c.IsMarkedAsUnread) : response.ChatIds.Select(GetChat).Where(c => (c.UnreadCount > 0 || c.IsMarkedAsUnread)
&& c.NotificationSettings.MuteFor == 0) && c.NotificationSettings.MuteFor == 0)
.ToList(); .ToList();
} }
@ -139,7 +164,7 @@ namespace telegram
return pass; return pass;
} }
public static void sendMessage(string message, long chatId) public static void SendMessage(string message, long chatId)
{ {
if (string.IsNullOrWhiteSpace(message)) if (string.IsNullOrWhiteSpace(message))
return; return;
@ -163,7 +188,7 @@ namespace telegram
currentUserRead = false; currentUserRead = false;
} }
public static Message editMessage(string newText, Message message) public static Message EditMessage(string newText, Message message)
{ {
var msg = client.ExecuteAsync(new EditMessageText var msg = client.ExecuteAsync(new EditMessageText
{ {
@ -181,7 +206,7 @@ namespace telegram
return msg; return msg;
} }
public static void markRead(long chatId, long messageId) public static void MarkRead(long chatId, long messageId)
{ {
client.ExecuteAsync(new ViewMessages client.ExecuteAsync(new ViewMessages
{ {
@ -194,7 +219,7 @@ namespace telegram
}); });
} }
public static void markUnread(long chatId) public static void MarkUnread(long chatId)
{ {
client.ExecuteAsync(new ToggleChatIsMarkedAsUnread client.ExecuteAsync(new ToggleChatIsMarkedAsUnread
{ {
@ -203,7 +228,7 @@ namespace telegram
}); });
} }
public static long searchChatId(string query) public static long SearchChatId(string query)
{ {
try try
{ {
@ -217,13 +242,13 @@ namespace telegram
} }
catch catch
{ {
lock (_lock) lock (@lock)
messageQueue.Add($"{Ansi.Red}[tgcli] No results found."); messageQueue.Add($"{Ansi.Red}[tgcli] No results found.");
return 0; return 0;
} }
} }
public static object getFormattedUsername(User sender) public static object GetFormattedUsername(User sender)
{ {
var username = sender.Username; var username = sender.Username;
if (string.IsNullOrWhiteSpace(username)) if (string.IsNullOrWhiteSpace(username))
@ -235,20 +260,20 @@ namespace telegram
return username; return username;
} }
public static string formatTime(long unix) public static string FormatTime(long unix)
{ {
var time = DateTimeOffset.FromUnixTimeSeconds(unix).DateTime.ToLocalTime(); var time = DateTimeOffset.FromUnixTimeSeconds(unix).DateTime.ToLocalTime();
var currentTime = DateTime.Now.ToLocalTime(); var currentTime = DateTime.Now.ToLocalTime();
return time.ToString(time.Date.Ticks == currentTime.Date.Ticks ? "HH:mm" : "yyyy-MM-dd HH:mm"); return time.ToString(time.Date.Ticks == currentTime.Date.Ticks ? "HH:mm" : "yyyy-MM-dd HH:mm");
} }
public static bool isMessageRead(long chatId, long messageId) public static bool IsMessageRead(long chatId, long messageId)
{ {
var chat = getChat(chatId); var chat = GetChat(chatId);
return chat.LastReadOutboxMessageId <= messageId; return chat.LastReadOutboxMessageId >= messageId;
} }
public static int getActualStringWidth(string input) public static int GetActualStringWidth(string input)
{ {
input = input.Replace(Ansi.Blue, ""); input = input.Replace(Ansi.Blue, "");
input = input.Replace(Ansi.Bold, ""); input = input.Replace(Ansi.Bold, "");
@ -262,11 +287,106 @@ namespace telegram
return input.Length; return input.Length;
} }
public static string getFormattedStatus(bool isRead) public static string GetFormattedStatus(bool isRead)
{ {
var output = " "; var output = " ";
output += (isRead ? Ansi.Green : Ansi.Red) + "r"; output += (isRead ? Ansi.Green : Ansi.Red) + "r";
return output + $"{Ansi.ResetAll}]"; return output + $"{Ansi.ResetAll}]";
} }
public static readonly List<ConsoleKey> SpecialKeys = new List<ConsoleKey>
{
ConsoleKey.Backspace,
ConsoleKey.Tab,
ConsoleKey.Clear,
ConsoleKey.Enter,
ConsoleKey.Pause,
ConsoleKey.Escape,
ConsoleKey.PageUp,
ConsoleKey.PageDown,
ConsoleKey.End,
ConsoleKey.Home,
ConsoleKey.LeftArrow,
ConsoleKey.UpArrow,
ConsoleKey.RightArrow,
ConsoleKey.DownArrow,
ConsoleKey.Select,
ConsoleKey.Print,
ConsoleKey.Execute,
ConsoleKey.PrintScreen,
ConsoleKey.Insert,
ConsoleKey.Delete,
ConsoleKey.Help,
ConsoleKey.LeftWindows,
ConsoleKey.RightWindows,
ConsoleKey.Applications,
ConsoleKey.Sleep,
ConsoleKey.F1,
ConsoleKey.F2,
ConsoleKey.F3,
ConsoleKey.F4,
ConsoleKey.F5,
ConsoleKey.F6,
ConsoleKey.F7,
ConsoleKey.F8,
ConsoleKey.F9,
ConsoleKey.F10,
ConsoleKey.F11,
ConsoleKey.F12,
ConsoleKey.F13,
ConsoleKey.F14,
ConsoleKey.F15,
ConsoleKey.F16,
ConsoleKey.F17,
ConsoleKey.F18,
ConsoleKey.F19,
ConsoleKey.F20,
ConsoleKey.F21,
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

@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
@ -17,24 +16,23 @@ namespace telegram
* replace emoji on send & un-replace on edit, two-way dictionary!! * replace emoji on send & un-replace on edit, two-way dictionary!!
* replace more emojis on send (is there a lib for that) * replace more emojis on send (is there a lib for that)
* make typing newlines actually good (inputline as list?) * make typing newlines actually good (inputline as list?)
* fix history not fully displaying on channel open (query returning less results than expected?)
* waaay more error messages instead of just doing nothing * waaay more error messages instead of just doing nothing
* make Util.getActualStringWidth better * make Util.getActualStringWidth better
* make the command system not shit (classes & manager & /help etc) * make the command system not shit (classes & manager & /help etc)
* refactor everything * refactor everything
* publish AUR package * publish AUR package
* make login less frustrating
* add option to disable terminal bell * add option to disable terminal bell
* command /s /search -> list matching chats, option 1-n, archived indicator * command /s /search -> list matching chats, option 1-n, archived indicator
* secret chats! * secret chats!
* split with newline if received message enters next line * split with newline if received message enters next line
* fix issues when current_input message is longer than term width (only show as much as fits?) * fix issues when current_input message is longer than term width (only show as much as fits?)
* maintain a list of statuses per user (online, read, typing) ? -> make otr indicators more reliable
* photo/document/etc captions * photo/document/etc captions
* photo download & show externally * photo download & show externally
* maybe cursor input nav (cmd+del, left/right, up for last inputs, etc) * maybe cursor input nav (cmd+del, left/right, up for last inputs, etc)
*/ */
public class tgcli
// ReSharper disable once InconsistentNaming
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 = "";
@ -50,102 +48,8 @@ namespace telegram
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 object _lock = new object(); public static volatile object @lock = new object();
public static readonly List<ConsoleKey> specialKeys = new List<ConsoleKey>
{
ConsoleKey.Backspace,
ConsoleKey.Tab,
ConsoleKey.Clear,
ConsoleKey.Enter,
ConsoleKey.Pause,
ConsoleKey.Escape,
ConsoleKey.PageUp,
ConsoleKey.PageDown,
ConsoleKey.End,
ConsoleKey.Home,
ConsoleKey.LeftArrow,
ConsoleKey.UpArrow,
ConsoleKey.RightArrow,
ConsoleKey.DownArrow,
ConsoleKey.Select,
ConsoleKey.Print,
ConsoleKey.Execute,
ConsoleKey.PrintScreen,
ConsoleKey.Insert,
ConsoleKey.Delete,
ConsoleKey.Help,
ConsoleKey.LeftWindows,
ConsoleKey.RightWindows,
ConsoleKey.Applications,
ConsoleKey.Sleep,
ConsoleKey.F1,
ConsoleKey.F2,
ConsoleKey.F3,
ConsoleKey.F4,
ConsoleKey.F5,
ConsoleKey.F6,
ConsoleKey.F7,
ConsoleKey.F8,
ConsoleKey.F9,
ConsoleKey.F10,
ConsoleKey.F11,
ConsoleKey.F12,
ConsoleKey.F13,
ConsoleKey.F14,
ConsoleKey.F15,
ConsoleKey.F16,
ConsoleKey.F17,
ConsoleKey.F18,
ConsoleKey.F19,
ConsoleKey.F20,
ConsoleKey.F21,
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
};
private static void Main() private static void Main()
{ {
dbdir = dbdir =
@ -207,7 +111,7 @@ namespace telegram
Task.Run(() => AddMessageToQueue(message)); Task.Run(() => AddMessageToQueue(message));
Task.Run(() => Task.Run(() =>
{ {
var msg = getMessage(message.ChatId, message.MessageId); var msg = GetMessage(message.ChatId, message.MessageId);
if (msg.IsOutgoing && currentChatId == msg.ChatId) if (msg.IsOutgoing && currentChatId == msg.ChatId)
{ {
lastMessage = msg; lastMessage = msg;
@ -269,14 +173,14 @@ namespace telegram
public static void ScreenUpdate() public static void ScreenUpdate()
{ {
lock (_lock) lock (@lock)
{ {
ClearCurrentConsoleLine(); ClearCurrentConsoleLine();
messageQueue.ForEach(p => Console.WriteLine(p + Ansi.ResetAll)); messageQueue.ForEach(p => Console.WriteLine(p + Ansi.ResetAll));
if (messageQueue.Count > 0) if (messageQueue.Count > 0)
Console.Write("\a"); //ring terminal bell Console.Write("\a"); //ring terminal bell
messageQueue.Clear(); messageQueue.Clear();
var status = getFormattedStatus(currentUserRead); var status = GetFormattedStatus(currentUserRead);
Console.Write(prefix Console.Write(prefix
+ (connectionState == "Ready" ? "" : $" ({connectionState})") + (connectionState == "Ready" ? "" : $" ({connectionState})")
+ (currentChatUserId != 0 ? status : "]") + " > " + currentInputLine); + (currentChatUserId != 0 ? status : "]") + " > " + currentInputLine);
@ -288,7 +192,7 @@ namespace telegram
switch (key.Key) switch (key.Key)
{ {
case ConsoleKey.Enter when connectionState != "Ready": case ConsoleKey.Enter when connectionState != "Ready":
lock(_lock) lock(@lock)
messageQueue.Add($"{Ansi.Red}[tgcli] " + messageQueue.Add($"{Ansi.Red}[tgcli] " +
"Connection unstable. Check your network connection and try again."); "Connection unstable. Check your network connection and try again.");
ScreenUpdate(); ScreenUpdate();
@ -303,14 +207,14 @@ namespace telegram
} }
case ConsoleKey.Enter when currentChatId == 0: case ConsoleKey.Enter when currentChatId == 0:
{ {
lock(_lock) lock(@lock)
messageQueue.Add($"{Ansi.Red}[tgcli] " + messageQueue.Add($"{Ansi.Red}[tgcli] " +
"No chat selected. Select a chat with /open <query>"); "No chat selected. Select a chat with /open <query>");
ScreenUpdate(); ScreenUpdate();
return; return;
} }
case ConsoleKey.Enter: case ConsoleKey.Enter:
sendMessage(currentInputLine, currentChatId); SendMessage(currentInputLine, currentChatId);
currentInputLine = ""; currentInputLine = "";
ScreenUpdate(); ScreenUpdate();
break; break;
@ -349,7 +253,7 @@ namespace telegram
ScreenUpdate(); ScreenUpdate();
return; return;
} }
if (!specialKeys.Contains(key.Key)) if (!SpecialKeys.Contains(key.Key))
{ {
currentInputLine += key.KeyChar; currentInputLine += key.KeyChar;
ScreenUpdate(); ScreenUpdate();
@ -432,10 +336,10 @@ namespace telegram
text = messageText.Text.Text; text = messageText.Text.Text;
else else
text = $"[unsupported {msg.Content.DataType}]"; text = $"[unsupported {msg.Content.DataType}]";
var sender = getUser(msg.SenderUserId); var sender = GetUser(msg.SenderUserId);
var chat = getChat(msg.ChatId); var chat = GetChat(msg.ChatId);
var username = getFormattedUsername(sender); var username = GetFormattedUsername(sender);
var time = formatTime(msg.Date); var time = FormatTime(msg.Date);
var isChannel = msg.IsChannelPost; var isChannel = msg.IsChannelPost;
var isPrivate = chat.Type is Td.TdApi.ChatType.ChatTypePrivate; var isPrivate = chat.Type is Td.TdApi.ChatType.ChatTypePrivate;
var isReply = msg.ReplyToMessageId != 0; var isReply = msg.ReplyToMessageId != 0;
@ -445,14 +349,14 @@ namespace telegram
$"{(isPrivate || isChannel ? "" : $"{Ansi.Yellow}{username} ")}"; $"{(isPrivate || isChannel ? "" : $"{Ansi.Yellow}{username} ")}";
var finalOutput = msgPrefix; var finalOutput = msgPrefix;
var indent = new string(' ', getActualStringWidth(msgPrefix)); var indent = new string(' ', GetActualStringWidth(msgPrefix));
var arrows = $"{(msg.IsOutgoing ? $"{Ansi.Blue}»»»" : $"{Ansi.Magenta}«««")} "; var arrows = $"{(msg.IsOutgoing ? $"{Ansi.Blue}»»»" : $"{Ansi.Magenta}«««")} ";
if (isReply) if (isReply)
{ {
try try
{ {
replyMessage = getMessage(chat.Id, msg.ReplyToMessageId); replyMessage = GetMessage(chat.Id, msg.ReplyToMessageId);
finalOutput = $"{FormatMessageReply(replyMessage, msgPrefix)}"; finalOutput = $"{FormatMessageReply(replyMessage, msgPrefix)}";
} }
catch catch
@ -480,22 +384,22 @@ namespace telegram
text = messageText.Text.Text; text = messageText.Text.Text;
else else
text = $"[unsupported {msg.Content.DataType}]"; text = $"[unsupported {msg.Content.DataType}]";
var sender = getUser(msg.SenderUserId); var sender = GetUser(msg.SenderUserId);
var chat = getChat(msg.ChatId); var chat = GetChat(msg.ChatId);
var username = getFormattedUsername(sender); var username = GetFormattedUsername(sender);
var time = formatTime(msg.Date); var time = FormatTime(msg.Date);
var isChannel = msg.IsChannelPost; var isChannel = msg.IsChannelPost;
var isPrivate = chat.Type is Td.TdApi.ChatType.ChatTypePrivate; var isPrivate = chat.Type is Td.TdApi.ChatType.ChatTypePrivate;
var finalOutput = ""; var finalOutput = "";
var prefix = $"{origPrefix}{Ansi.Yellow}Re: {Ansi.Bold}{Ansi.Green}[{time}] {Ansi.Cyan}{chat.Title} " + 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(prefix)); var indent = new string(' ', GetActualStringWidth(replyPrefix));
var arrows = $"{(msg.IsOutgoing ? $"{Ansi.Blue}»»»" : $"{Ansi.Magenta}«««")} "; var arrows = $"{(msg.IsOutgoing ? $"{Ansi.Blue}»»»" : $"{Ansi.Magenta}«««")} ";
var rest = $"{text}{(msg.EditDate == 0 ? "" : $"{Ansi.Yellow}*")}"; var rest = $"{text}{(msg.EditDate == 0 ? "" : $"{Ansi.Yellow}*")}";
finalOutput += prefix; finalOutput += replyPrefix;
var lines = rest.Split("\n").ToList(); var lines = rest.Split("\n").ToList();
finalOutput += arrows + lines.First(); finalOutput += arrows + lines.First();
@ -512,11 +416,11 @@ namespace telegram
text = messageText.Text.Text; text = messageText.Text.Text;
else else
text = $"[unsupported {msg.NewContent.DataType}]"; text = $"[unsupported {msg.NewContent.DataType}]";
var message = getMessage(msg.ChatId, msg.MessageId); var message = GetMessage(msg.ChatId, msg.MessageId);
var sender = getUser(message.SenderUserId); var sender = GetUser(message.SenderUserId);
var chat = getChat(msg.ChatId); var chat = GetChat(msg.ChatId);
var username = getFormattedUsername(sender); var username = GetFormattedUsername(sender);
var time = formatTime(message.EditDate); var time = FormatTime(message.EditDate);
var isChannel = message.IsChannelPost; var isChannel = message.IsChannelPost;
var isPrivate = chat.Type is Td.TdApi.ChatType.ChatTypePrivate; var isPrivate = chat.Type is Td.TdApi.ChatType.ChatTypePrivate;
@ -530,7 +434,7 @@ namespace telegram
public static void AddMessageToQueue(Td.TdApi.Message msg) public static void AddMessageToQueue(Td.TdApi.Message msg)
{ {
//handle muted //handle muted
if (getChat(msg.ChatId).NotificationSettings.MuteFor > 0 && currentChatId != msg.ChatId) if (GetChat(msg.ChatId).NotificationSettings.MuteFor > 0 && currentChatId != msg.ChatId)
return; return;
//we aren't interested in backlog //we aren't interested in backlog
@ -540,31 +444,31 @@ namespace telegram
var formattedMessage = FormatMessage(msg); var formattedMessage = FormatMessage(msg);
if (currentChatId != 0 && msg.ChatId != currentChatId) if (currentChatId != 0 && msg.ChatId != currentChatId)
lock (_lock) lock (@lock)
missedMessages.Add(formattedMessage); missedMessages.Add(formattedMessage);
else else
lock (_lock) lock (@lock)
messageQueue.Add(formattedMessage); messageQueue.Add(formattedMessage);
if (msg.ChatId == currentChatId) if (msg.ChatId == currentChatId)
markRead(msg.ChatId, msg.Id); MarkRead(msg.ChatId, msg.Id);
ScreenUpdate(); ScreenUpdate();
} }
public static void AddMessageToQueue(Td.TdApi.Update.UpdateMessageContent msg) public static void AddMessageToQueue(Td.TdApi.Update.UpdateMessageContent msg)
{ {
//handle muted //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) || GetMessage(msg.ChatId, msg.MessageId).EditDate == 0)
return; return;
var formattedMessage = FormatMessage(msg); var formattedMessage = FormatMessage(msg);
if (currentChatId != 0 && msg.ChatId != currentChatId) if (currentChatId != 0 && msg.ChatId != currentChatId)
lock (_lock) lock (@lock)
missedMessages.Add(formattedMessage); missedMessages.Add(formattedMessage);
else else
lock (_lock) lock (@lock)
messageQueue.Add(formattedMessage); messageQueue.Add(formattedMessage);
ScreenUpdate(); ScreenUpdate();
} }