Пример #1
0
        private static async Task DoCommand(string command)
        {
			// Clean the input
			command = command.Trim();
			// Don't do anything if we have empty input
			if(command == "")
				return;

			// Split and handle command
            var args = SplitCommandLine(command).ToList();

            switch (args[0].ToLower())
            {
                case "help":
                    PrintHelp();
                    break;
                case "register":
                    {
                        
                        var service = ServiceManager.GetByName(args[1]);
                        ServiceManager.Register(service);
                        ServiceManager.RegisteredServicesDatabase.SaveAllRegistered();
                        Console.WriteLine(service + " registered");
                    }
                    break;
                case "startall":
                    {
                        foreach (var service in ServiceManager.Registered)
                        {
                            var unifiedService = service as UnifiedService;
                            if (unifiedService != null)
                            {
                                ServiceManager.StartUnified(unifiedService, null);
                            }
                            else
                            {
                                await ServiceManager.Start(service, true);
                            }
                            Console.WriteLine(service + " started");
                        }
                    }
                    break;
                case "stop":
                    {
                        var service = ServiceManager.GetByName(args[1]);
                        await ServiceManager.Abort(service);
                        Console.WriteLine(service + " stopped");
                    }
                    break;
                case "start":
                    {
                        var service = ServiceManager.GetByName(args[1]);
                        await ServiceManager.Start(service, true);
                        Console.WriteLine(service + " started");
                    }
                    break;
                case "send":
                    {
                        var service = ServiceManager.GetByName(args[1]);
                        var address = args[2];
                        var message = args[3];
                        var textBubble = new TextBubble(Time.GetNowUnixTimestamp(), Bubble.BubbleDirection.Outgoing, 
                            address, null, false, service, message);
                        await BubbleManager.Send(textBubble);
                        Console.WriteLine(textBubble + " sent");
                    }
                    break;
                case "deploy-unregister":
                    {
                        var pluginName = args[1];
                        var deployment = Settings.PluginDeployments.FirstOrDefault(x => x.Name.ToLower() == pluginName.ToLower());
                        if (deployment != null)
                        {
                            Settings.PluginDeployments.Remove(deployment);
                        }
                        MutableSettingsManager.Save(Settings);
                        Console.WriteLine("Removed.");
                    }
                    break;
                case "deploy-register":
                    {
                        var pluginName = args[1];
                        var path = args[2].ToLower();
                        if (Settings.PluginDeployments != null)
                        {
                            var hasDeployment = Settings.PluginDeployments.FirstOrDefault(x => x.Name.ToLower() == pluginName.ToLower()) != null;
                            if (hasDeployment)
                            {
                                Console.WriteLine("Plugin has already been registered in deployment system.");
                                break;
                            }
                        }
                        if (Settings.PluginDeployments == null)
                        {
                            Settings.PluginDeployments = new List<TerminalSettings.PluginDeployment>();
                        }
                        Settings.PluginDeployments.Add(new TerminalSettings.PluginDeployment
                        {
                            Name = pluginName,
                            Path = path,
                        });
                        MutableSettingsManager.Save(Settings);
                        Console.WriteLine("Plugin registered!");
                    }
                    break;
                case "deploy-clean":
                    {
                        var pluginName = args[1];
                        var deployment = Settings.PluginDeployments.FirstOrDefault(x => x.Name.ToLower() == pluginName.ToLower());
                        if (deployment != null)
                        {
                            deployment.Assemblies = null;
                            MutableSettingsManager.Save(Settings);
                            Console.WriteLine("Cleaned assemblies.");
                        }
                        else
                        {
                            Console.WriteLine("Could not find plugin deployment: " + pluginName);
                        }
                    }
                    break;
                case "deploy":
                    {
                        var pluginName = args[1];
                        var deployment = Settings.PluginDeployments.FirstOrDefault(x => x.Name.ToLower() == pluginName.ToLower());
                        var oldAssemblies = deployment.Assemblies ?? new List<TerminalSettings.PluginDeployment.Assembly>();
                        var assembliesToDeploy = new List<TerminalSettings.PluginDeployment.Assembly>();
                        var newAssemblies = new List<TerminalSettings.PluginDeployment.Assembly>();
                        var pluginManifest = Path.Combine(deployment.Path, "PluginManifest.xml");
                        if (!File.Exists(pluginManifest))
                        {
                            Console.WriteLine("A plugin manifest file is needed!");
                            break;
                        }
                        foreach (var assemblyFile in Directory.EnumerateFiles(deployment.Path, "*.dll")
                            .Concat(new [] { pluginManifest }))
                        {
                            var assemblyFileName = Path.GetFileName(assemblyFile);
                            if (PlatformManager.AndroidLinkedAssemblies.Contains(assemblyFileName))
                                continue;

                            var lastModified = File.GetLastWriteTime(assemblyFile);
                            var newAssembly = new TerminalSettings.PluginDeployment.Assembly
                            {
                                Name = assemblyFileName,
                                Modified = lastModified
                            };
                            newAssemblies.Add(newAssembly);

                            var oldAssembly = oldAssemblies.FirstOrDefault(x => x.Name == assemblyFileName);
                            if (oldAssembly == null)
                            {
                                assembliesToDeploy.Add(newAssembly);
                            }
                            else if (oldAssembly.Modified != lastModified)
                            {
                                assembliesToDeploy.Add(newAssembly);
                            }
                        }
                        deployment.Assemblies = newAssemblies;
                        MutableSettingsManager.Save(Settings);
                        var instance = AndroidController.Instance;
                        var devices = instance.ConnectedDevices;
                        Device selectedDevice;
                        if (devices.Count > 1)
                        {
                            Console.WriteLine("Please pick a device:");
                            var counter = 0;
                            foreach (var device in devices)
                            {
                                Console.WriteLine(counter++ + ") " + device);
                            }
                            Console.Write("Selection: ");
                            var selection = int.Parse(Console.ReadLine().Trim());
                            selectedDevice = instance.GetConnectedDevice(devices[selection]);
                        }
                        else
                        {
                            selectedDevice = instance.GetConnectedDevice();
                        }
                        var remotePath = "/sdcard/Disa/plugins/" + deployment.Name;
                        if (selectedDevice.FileSystem.FileOrDirectory(remotePath) == ListingType.NONE)
                        {
                            selectedDevice.FileSystem.MakeDirectory(remotePath);
                        }

                        foreach (var assemblyToDeploy in assembliesToDeploy)
                        {
                            Console.WriteLine("Transferring " + assemblyToDeploy.Name + "...");
                            var remoteAssembly = remotePath + "/" + assemblyToDeploy.Name;
                            if (selectedDevice.FileSystem.FileOrDirectory(remoteAssembly) != ListingType.NONE)
                            {
                                selectedDevice.FileSystem.Delete(remoteAssembly);

                            }
                            selectedDevice.PushFile(Path.Combine(deployment.Path, assemblyToDeploy.Name), remoteAssembly);
                        }
                        Console.WriteLine("Plugin deployed! Restarting Disa...");
                        var cmd = Adb.FormAdbShellCommand(selectedDevice, false, "am", "force-stop", "com.disa");
                        Adb.ExecuteAdbCommand(cmd);
                        Task.Delay(250).Wait();
                        cmd = Adb.FormAdbShellCommand(selectedDevice, false, "monkey", "-p com.disa", "-c android.intent.category.LAUNCHER 1");
                        Adb.ExecuteAdbCommand(cmd);
                        Console.WriteLine("Disa restarted!");
                    }
                    break;
                case "deploy-print-dependencies":
                    {
                        var pluginName = args[1];
                        var deployment = Settings.PluginDeployments.FirstOrDefault(x => x.Name.ToLower() == pluginName.ToLower());
                        foreach (var assemblyFile in Directory.EnumerateFiles(deployment.Path, "*.dll"))
                        {
                            var assemblyFileName = Path.GetFileName(assemblyFile);
                            if (PlatformManager.AndroidLinkedAssemblies.Contains(assemblyFileName))
                                continue;
                            var module = ModuleDefinition.ReadModule(assemblyFile);
                            Console.WriteLine(assemblyFileName + ": ");
                            foreach (var referenceAssembly in module.AssemblyReferences)
                            {
                                Console.WriteLine("> " + referenceAssembly.FullName);
                            }  
                        }
                    }
                    break;
                default:
                    {
                        var service = ServiceManager.GetByName(args[0]);
                        if (service != null)
                        {
                            var terminal = service as ITerminal;
                            if (terminal != null)
                            {
                                try
                                {
                                    terminal.DoCommand(args.GetRange(1, args.Count - 1).ToArray());
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("Error in processing a service terminal command: " + ex);
                                }
                            }

                        }           
                    }
                    break;
            }
        }
Пример #2
0
        private List<VisualBubble> ProcessFullMessage(Message message,bool useCurrentTime)
        {
            var peerUser = message.ToId as PeerUser;
            var peerChat = message.ToId as PeerChat;
            var peerChannel = message.ToId as PeerChannel;

            var direction = message.FromId == _settings.AccountId
                ? Bubble.BubbleDirection.Outgoing
                : Bubble.BubbleDirection.Incoming;

            if (!string.IsNullOrWhiteSpace(message.MessageProperty))
            {
                TextBubble tb = null;

                if (peerUser != null)
                {
                    var address = direction == Bubble.BubbleDirection.Incoming
                        ? message.FromId
                        : peerUser.UserId;
                    var addressStr = address.ToString(CultureInfo.InvariantCulture);
                    tb = new TextBubble(
                        useCurrentTime ? Time.GetNowUnixTimestamp() : (long)message.Date,
                        direction, addressStr, null, false, this, message.MessageProperty,
                        message.Id.ToString(CultureInfo.InvariantCulture));

                }
                else if (peerChat != null)
                {
                    var address = peerChat.ChatId.ToString(CultureInfo.InvariantCulture);
                    var participantAddress = message.FromId.ToString(CultureInfo.InvariantCulture);
                    tb = new TextBubble(
                        useCurrentTime ? Time.GetNowUnixTimestamp() : (long)message.Date,
                        direction, address, participantAddress, true, this, message.MessageProperty,
                        message.Id.ToString(CultureInfo.InvariantCulture));
                }
                else if (peerChannel != null) 
                {
                    var address = peerChannel.ChannelId.ToString(CultureInfo.InvariantCulture);
                    var participantAddress = message.FromId.ToString(CultureInfo.InvariantCulture);
                    tb = new TextBubble(
                        useCurrentTime ? Time.GetNowUnixTimestamp() : (long)message.Date,
                        direction, address, participantAddress, true, this, message.MessageProperty,
                        message.Id.ToString(CultureInfo.InvariantCulture));
                    tb.ExtendedParty = true;
                }
                if (tb == null) return null;
                if (direction == Bubble.BubbleDirection.Outgoing)
                {
                    tb.Status = Bubble.BubbleStatus.Sent;
                }
                return new List<VisualBubble> 
                { 
                    tb
                };
            }
            else
            {
                if (peerUser != null)
                {
                    var address = direction == Bubble.BubbleDirection.Incoming
                        ? message.FromId
                        : peerUser.UserId;
                    var addressStr = address.ToString(CultureInfo.InvariantCulture);
                    var bubble = MakeMediaBubble(message, useCurrentTime, true, addressStr);
                    return bubble;
                }
                else if (peerChat != null)
                {
                    var address = peerChat.ChatId.ToString(CultureInfo.InvariantCulture);
                    var participantAddress = message.FromId.ToString(CultureInfo.InvariantCulture);
                    var bubble = MakeMediaBubble(message, useCurrentTime, false, address, participantAddress);
                    return bubble;
                }
                else if (peerChannel != null)
                {
                    var address = peerChannel.ChannelId.ToString(CultureInfo.InvariantCulture);
                    var participantAddress = message.FromId.ToString(CultureInfo.InvariantCulture);
                    var bubbles = MakeMediaBubble(message, useCurrentTime, false, address, participantAddress);
                    foreach (var bubble in bubbles)
                    {
                        bubble.ExtendedParty = true;   
                    }
                    return bubbles;
                }

            }
            return null;
        }
Пример #3
0
        private void ProcessIncomingPayload(List<object> payloads, bool useCurrentTime, TelegramClient optionalClient = null)
        {
            uint maxMessageId = 0;

            foreach (var payload in AdjustUpdates(payloads))
            {
                var update = NormalizeUpdateIfNeeded(payload);

                var shortMessage = update as UpdateShortMessage;
                var shortChatMessage = update as UpdateShortChatMessage;
                var typing = update as UpdateUserTyping;
                var typingChat = update as UpdateChatUserTyping;
                var userStatus = update as UpdateUserStatus;
                var messageService = update as MessageService;
                var updateChatParticipants = update as UpdateChatParticipants;
                var updateContactRegistered = update as UpdateContactRegistered;
                var updateContactLink = update as UpdateContactLink;
                var updateUserPhoto = update as UpdateUserPhoto;
                var updateReadHistoryInbox = update as UpdateReadHistoryInbox;
                var updateReadHistoryOutbox = update as UpdateReadHistoryOutbox;
                var updateReadChannelInbox = update as UpdateReadChannelInbox;
                var updateReadChannelOutbox = update as UpdateReadChannelOutbox;
                var updateChannelTooLong = update as UpdateChannelTooLong;
                var updateDeleteChannelMessage = update as UpdateDeleteChannelMessages;
                var updateEditChannelMessage = update as UpdateEditChannelMessage;
                var updateChatAdmins = update as UpdateChatAdmins;
                var updateChannel = update as UpdateChannel;
                var message = update as SharpTelegram.Schema.Message;
                var user = update as IUser;
                var chat = update as IChat;

                DebugPrint(">>>>>> The type of object in process incoming payload is " + ObjectDumper.Dump(update));

                if (shortMessage != null)
                {
                    if (!string.IsNullOrWhiteSpace(shortMessage.Message))
                    {
                        var fromId = shortMessage.UserId.ToString(CultureInfo.InvariantCulture);
                        var shortMessageUser = _dialogs.GetUser(shortMessage.UserId);
                        if (shortMessageUser == null)
                        {
                            DebugPrint(">>>>> User is null, fetching user from the server");
                            GetMessage(shortMessage.Id, optionalClient);
                        }

                        EventBubble(new TypingBubble(Time.GetNowUnixTimestamp(),
                            Bubble.BubbleDirection.Incoming,
                            fromId, false, this, false, false));
                        TextBubble textBubble = new TextBubble(
                                            useCurrentTime ? Time.GetNowUnixTimestamp() : (long)shortMessage.Date,
                                            shortMessage.Out != null ? Bubble.BubbleDirection.Outgoing : Bubble.BubbleDirection.Incoming,
                                            fromId, null, false, this, shortMessage.Message,
                                            shortMessage.Id.ToString(CultureInfo.InvariantCulture));

                        if (shortMessage.Out != null)
                        {
                            textBubble.Status = Bubble.BubbleStatus.Sent;
                        }
                        if (textBubble.Direction == Bubble.BubbleDirection.Incoming)
                        {
                            if (shortMessage.ReplyToMsgId != 0)
                            {
                                var iReplyMessage = GetMessage(shortMessage.ReplyToMsgId, optionalClient);
                                DebugPrint(">>> got message " + ObjectDumper.Dump(iReplyMessage));
                                var replyMessage = iReplyMessage as Message;
                                AddQuotedMessageToBubble(replyMessage, textBubble);

                            }
                        }
                        EventBubble(textBubble);
                    }
                    if (shortMessage.Id > maxMessageId)
                    {
                        maxMessageId = shortMessage.Id;
                    }
                }
                else if (updateUserPhoto != null)
                {
                    var iUpdatedUser = _dialogs.GetUser(updateUserPhoto.UserId);
                    var updatedUser = iUpdatedUser as User;
                    if (updatedUser != null)
                    {
                        updatedUser.Photo = updateUserPhoto.Photo;
                        InvalidateThumbnail(updatedUser.Id.ToString(), false, false);
                        InvalidateThumbnail(updatedUser.Id.ToString(), false, true);
                    }
                    _dialogs.AddUser(updatedUser);
                }
                else if (updateChannel != null)
                {
                    var channel = _dialogs.GetChat(updateChannel.ChannelId) as Channel;
                    if (channel != null)
                    {
                        if (channel.Left != null)
                        { 
                            var bubbleGroup = BubbleGroupManager.FindWithAddress(this, updateChannel.ChannelId.ToString());
                            Platform.DeleteBubbleGroup(new BubbleGroup[] { bubbleGroup });
                        }
                    }
                }
                else if (updateChatAdmins != null)
                {
                    var chatToUpdate = _dialogs.GetUser(updateChatAdmins.ChatId) as Chat;
                    if (chatToUpdate != null)
                    {
                        if (updateChatAdmins.Enabled)
                        {
                            chatToUpdate.AdminsEnabled = new True();
                        }
                        else
                        {
                            chatToUpdate.AdminsEnabled = null;
                        }
                    }
                    _dialogs.AddChat(chatToUpdate);
                }
                else if (updateReadHistoryOutbox != null)
                {
                    var iPeer = updateReadHistoryOutbox.Peer;
                    var peerChat = iPeer as PeerChat;
                    var peerUser = iPeer as PeerUser;

                    if (peerUser != null)
                    {
                        BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                            peerUser.UserId.ToString(CultureInfo.InvariantCulture));
                        DebugPrint("Found bubble group " + bubbleGroup);
                        if (bubbleGroup != null)
                        {
                            string idString = bubbleGroup.LastBubbleSafe().IdService;
                            if (idString == updateReadHistoryOutbox.MaxId.ToString(CultureInfo.InvariantCulture))
                            {
                                EventBubble(
                                    new ReadBubble(Time.GetNowUnixTimestamp(),
                                        Bubble.BubbleDirection.Incoming, this,
                                        peerUser.UserId.ToString(CultureInfo.InvariantCulture), null,
                                        Time.GetNowUnixTimestamp(), false, false));
                            }
                        }
                    }
                    else if (peerChat != null)
                    {
                        BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                           peerChat.ChatId.ToString(CultureInfo.InvariantCulture));
                        if (bubbleGroup != null)
                        {
                            string idString = bubbleGroup.LastBubbleSafe().IdService;
                            if (idString == updateReadHistoryOutbox.MaxId.ToString(CultureInfo.InvariantCulture))
                            {
                                EventBubble(
                                    new ReadBubble(
                                        Time.GetNowUnixTimestamp(),
                                        Bubble.BubbleDirection.Incoming, this,
                                        peerChat.ChatId.ToString(CultureInfo.InvariantCulture), DisaReadTime.SingletonPartyParticipantAddress,
                                        Time.GetNowUnixTimestamp(), true, false));
                            }
                        }

                    }

                }
                else if (updateReadChannelOutbox != null)
                {
                    BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                          updateReadChannelOutbox.ChannelId.ToString(CultureInfo.InvariantCulture));
                    if (bubbleGroup != null)
                    {
                        string idString = bubbleGroup.LastBubbleSafe().IdService;
                        if (idString == updateReadChannelOutbox.MaxId.ToString(CultureInfo.InvariantCulture))
                        {
                            EventBubble(
                                new ReadBubble(
                                    Time.GetNowUnixTimestamp(),
                                    Bubble.BubbleDirection.Incoming, this,
                                    updateReadChannelOutbox.ChannelId.ToString(CultureInfo.InvariantCulture), DisaReadTime.SingletonPartyParticipantAddress,
                                    Time.GetNowUnixTimestamp(), true, false));
                        }
                    }
                }
                else if (updateReadHistoryInbox != null)
                {
                    DebugPrint(">>> In update read history inbox");
                    var iPeer = updateReadHistoryInbox.Peer;
                    var peerChat = iPeer as PeerChat;
                    var peerUser = iPeer as PeerUser;

                    if (peerUser != null)
                    {
                        BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                            peerUser.UserId.ToString(CultureInfo.InvariantCulture));

                        if (bubbleGroup == null)
                        {
                            continue;
                        }

                        string idString = bubbleGroup.LastBubbleSafe().IdService;
                        DebugPrint("idstring" + idString);
                        if (idString != null)
                        {
                            if (uint.Parse(idString) <= updateReadHistoryInbox.MaxId)
                            {
                                BubbleGroupManager.SetUnread(this, false, peerUser.UserId.ToString(CultureInfo.InvariantCulture));
                                NotificationManager.Remove(this, peerUser.UserId.ToString(CultureInfo.InvariantCulture));
                            }
                        }

                    }
                    else if (peerChat != null)
                    {
                        BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                            peerChat.ChatId.ToString(CultureInfo.InvariantCulture));
                        if (bubbleGroup == null)
                        {
                            continue;
                        }
                        string idString = bubbleGroup.LastBubbleSafe().IdService;
                        if (idString != null)
                        {
                            if (uint.Parse(idString) == updateReadHistoryInbox.MaxId)
                            {
                                BubbleGroupManager.SetUnread(this, false,
                                    peerChat.ChatId.ToString(CultureInfo.InvariantCulture));
                                NotificationManager.Remove(this, peerChat.ChatId.ToString(CultureInfo.InvariantCulture));
                            }
                        }

                    }

                }
                else if (updateReadChannelInbox != null)
                {
                    BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                                              updateReadChannelInbox.ChannelId.ToString(CultureInfo.InvariantCulture));
                    if (bubbleGroup == null)
                    {
                        continue;
                    }

                    string idString = bubbleGroup.LastBubbleSafe().IdService;
                    DebugPrint("idstring" + idString);
                    if (idString != null)
                    {
                        if (uint.Parse(idString) <= updateReadChannelInbox.MaxId)
                        {
                            BubbleGroupManager.SetUnread(this, false, updateReadChannelInbox.ChannelId.ToString(CultureInfo.InvariantCulture));
                            NotificationManager.Remove(this, updateReadChannelInbox.ChannelId.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                }
                else if (shortChatMessage != null)
                {
                    if (!string.IsNullOrWhiteSpace(shortChatMessage.Message))
                    {
                        var address = shortChatMessage.ChatId.ToString(CultureInfo.InvariantCulture);
                        var participantAddress = shortChatMessage.FromId.ToString(CultureInfo.InvariantCulture);
                        EventBubble(new TypingBubble(Time.GetNowUnixTimestamp(),
                            Bubble.BubbleDirection.Incoming,
                            address, participantAddress, true, this, false, false));
                        TextBubble textBubble = new TextBubble(
                            useCurrentTime ? Time.GetNowUnixTimestamp() : (long)shortChatMessage.Date,
                            shortChatMessage.Out != null
                                ? Bubble.BubbleDirection.Outgoing
                                : Bubble.BubbleDirection.Incoming,
                            address, participantAddress, true, this, shortChatMessage.Message,
                            shortChatMessage.Id.ToString(CultureInfo.InvariantCulture));
                        if (shortChatMessage.Out != null)
                        {
                            textBubble.Status = Bubble.BubbleStatus.Sent;
                        }
                        if (textBubble.Direction == Bubble.BubbleDirection.Incoming)
                        {
                            if (shortChatMessage.ReplyToMsgId != 0)
                            {
                                var iReplyMessage = GetMessage(shortChatMessage.ReplyToMsgId, optionalClient);
                                DebugPrint(">>> got message " + ObjectDumper.Dump(iReplyMessage));
                                var replyMessage = iReplyMessage as Message;
                                AddQuotedMessageToBubble(replyMessage, textBubble);
                            }
                        }

                        EventBubble(textBubble);
                    }
                    if (shortChatMessage.Id > maxMessageId)
                    {
                        maxMessageId = shortChatMessage.Id;
                    }
                }
                else if (message != null)
                {
                    var bubbles = ProcessFullMessage(message, useCurrentTime);
                    var i = 0;
                    foreach (var bubble in bubbles)
                    {
                        if (bubble != null)
                        {
                            if (bubble.Direction == Bubble.BubbleDirection.Incoming)
                            {
                                var fromId = message.FromId.ToString(CultureInfo.InvariantCulture);
                                var messageUser = _dialogs.GetUser(message.FromId);
                                if (messageUser == null)
                                {
                                    DebugPrint(">>>>> User is null, fetching user from the server");
                                    GetMessage(message.Id, optionalClient, uint.Parse(TelegramUtils.GetPeerId(message.ToId)), message.ToId is PeerChannel);
                                }
                                if (message.ReplyToMsgId != 0 && i == 0)//we should only add quoted message to first bubble if multiple bubbles exist
                                {
                                    var iReplyMessage = GetMessage(message.ReplyToMsgId, optionalClient, uint.Parse(TelegramUtils.GetPeerId(message.ToId)), message.ToId is PeerChannel);
                                    DebugPrint(">>> got message " + ObjectDumper.Dump(iReplyMessage));
                                    var replyMessage = iReplyMessage as Message;
                                    AddQuotedMessageToBubble(replyMessage, bubble);
                                }
                            }
                            EventBubble(bubble);
                        }
                        i++;
                    }
                    if (message.Id > maxMessageId)
                    {
                        maxMessageId = message.Id;
                    }
                }
                else if (updateContactRegistered != null)
                {
                    contactsCache = new List<User>(); //invalidate cache
                }
                else if (updateContactLink != null)
                {
                    contactsCache = new List<User>();
                }
                else if (userStatus != null)
                {
                    var available = TelegramUtils.GetAvailable(userStatus.Status);
                    var userToUpdate = _dialogs.GetUser(userStatus.UserId);
                    if (userToUpdate != null)
                    {
                        var userToUpdateAsUser = userToUpdate as User;
                        if (userToUpdateAsUser != null)
                        {
                            userToUpdateAsUser.Status = userStatus.Status;
                            _dialogs.AddUser(userToUpdateAsUser);
                        }
                    }

                    EventBubble(new PresenceBubble(Time.GetNowUnixTimestamp(),
                        Bubble.BubbleDirection.Incoming,
                        userStatus.UserId.ToString(CultureInfo.InvariantCulture),
                        false, this, available));
                }
                else if (typing != null || typingChat != null)
                {
                    var isAudio = false;
                    var isTyping = false;
                    if (typing != null)
                    {
                        isAudio = typing.Action is SendMessageRecordAudioAction;
                        isTyping = typing.Action is SendMessageTypingAction;
                    }
                    if (typingChat != null)
                    {
                        isAudio = typingChat.Action is SendMessageRecordAudioAction;
                        isTyping = typingChat.Action is SendMessageTypingAction;
                    }
                    var userId = typing != null ? typing.UserId : typingChat.UserId;
                    var party = typingChat != null;
                    var participantAddress = party ? userId.ToString(CultureInfo.InvariantCulture) : null;
                    var address = party
                        ? typingChat.ChatId.ToString(CultureInfo.InvariantCulture)
                        : userId.ToString(CultureInfo.InvariantCulture);
                    var key = address + participantAddress;


                    if (isAudio || isTyping)
                    {
                        EventBubble(new TypingBubble(Time.GetNowUnixTimestamp(),
                            Bubble.BubbleDirection.Incoming,
                            address, participantAddress, party,
                            this, true, isAudio));
                        CancelTypingTimer(key);
                        var newTimer = new Timer(6000) { AutoReset = false };
                        newTimer.Elapsed += (sender2, e2) =>
                        {
                            EventBubble(new TypingBubble(Time.GetNowUnixTimestamp(),
                                Bubble.BubbleDirection.Incoming,
                                address, participantAddress, party,
                                this, false, isAudio));
                            newTimer.Dispose();
                            _typingTimers.Remove(key);
                        };
                        _typingTimers[key] = newTimer;
                        newTimer.Start();
                    }
                    else
                    {
                        //Console.WriteLine("Unknown typing action: " + typing.Action.GetType().Name); //causes null pointer in some cases
                    }
                }
                else if (user != null)
                {
                    _dialogs.AddUser(user);
                }
                else if (chat != null)
                {
                    _dialogs.AddChat(chat);
                }
                else if (updateChatParticipants != null)
                {
                    //do nothing, we just use party options for this
                }
                else if (messageService != null)
                {
                    var partyInformationBubbles = MakePartyInformationBubble(messageService, useCurrentTime);
                    foreach (var partyInformationBubble in partyInformationBubbles)
                    {
                        EventBubble(partyInformationBubble);
                    }
                }
                else if (updateChannelTooLong != null)
                {
                    //this dude gives me a pts of 0, which messes up shit. So we wont do nothin mah man
                    //SaveChannelState(updateChannelTooLong.ChannelId, updateChannelTooLong.Pts);
                }
                else if (updateEditChannelMessage != null)
                {
                    var editChannelMessage = updateEditChannelMessage.Message as Message;
                    if (message == null)
                    {
                        continue;
                    }
                    var peerChannel = editChannelMessage.ToId as PeerChannel;
                    SaveChannelState(peerChannel.ChannelId, updateEditChannelMessage.Pts);
                }
                else if (updateDeleteChannelMessage != null)
                {
                    SaveChannelState(updateDeleteChannelMessage.ChannelId, updateDeleteChannelMessage.Pts);
                }
                else
                {
                    Console.WriteLine("Unknown update: " + ObjectDumper.Dump(update));
                }
            }

            //if (maxMessageId != 0)
            //{
            //    SendReceivedMessages(optionalClient, maxMessageId);
            //}
        }
Пример #4
0
        private List<VisualBubble> MakeMediaBubble(Message message, bool useCurrentTime, bool isUser, string addressStr, string participantAddress = null)
        {
            DebugPrint(">>>>>>> Making media bubble");
            var messageMedia = message.Media;
            var messageMediaPhoto = messageMedia as MessageMediaPhoto;
            var messageMediaDocument = messageMedia as MessageMediaDocument;
            var messageMediaGeo = messageMedia as MessageMediaGeo;
            var messageMediaVenue = messageMedia as MessageMediaVenue;
            var messageMediaContact = messageMedia as MessageMediaContact;

            if (messageMediaPhoto != null)
            {
                var fileLocation = GetPhotoFileLocation(messageMediaPhoto.Photo);
                var fileSize = GetPhotoFileSize(messageMediaPhoto.Photo);
                var dimensions = GetPhotoDimensions(messageMediaPhoto.Photo);
                var cachedPhoto = GetCachedPhotoBytes(messageMediaPhoto.Photo);
                FileInformation fileInfo = new FileInformation
                {
                    FileLocation = fileLocation,
                    Size = fileSize,
                    FileType = "image",
                    Document = new Document()
                };
                using (var memoryStream = new MemoryStream())
                {
                    Serializer.Serialize<FileInformation>(memoryStream, fileInfo);
                    ImageBubble imageBubble = null;
                    if (isUser)
                    {
                        imageBubble = new ImageBubble(useCurrentTime ? Time.GetNowUnixTimestamp() : (long) message.Date,
                            message.Out != null ? Bubble.BubbleDirection.Outgoing : Bubble.BubbleDirection.Incoming,
                            addressStr, null, false, this, null, ImageBubble.Type.Url,
                            cachedPhoto, message.Id.ToString(CultureInfo.InvariantCulture));
                    }
                    else
                    {
                        imageBubble = new ImageBubble(useCurrentTime ? Time.GetNowUnixTimestamp() : (long) message.Date,
                            message.Out != null ? Bubble.BubbleDirection.Outgoing : Bubble.BubbleDirection.Incoming,
                            addressStr, participantAddress, true, this, null,
                            ImageBubble.Type.Url, cachedPhoto, message.Id.ToString(CultureInfo.InvariantCulture));
                    }
                    if (imageBubble.Direction == Bubble.BubbleDirection.Outgoing)
                    {
                        imageBubble.Status = Bubble.BubbleStatus.Sent;
                    }
                    imageBubble.AdditionalData = memoryStream.ToArray();
                    imageBubble.Width = dimensions.Width;
                    imageBubble.Height = dimensions.Height;
                    var returnList = new List<VisualBubble>
                    {
                        imageBubble  
                    };
                    if (!string.IsNullOrEmpty(messageMediaPhoto.Caption))
                    {
                        TextBubble captionBubble = null;
                        if (isUser)
                        {
                            captionBubble = new TextBubble(useCurrentTime ? Time.GetNowUnixTimestamp() : (long)message.Date,
                                message.Out != null ? Bubble.BubbleDirection.Outgoing : Bubble.BubbleDirection.Incoming,
                                addressStr, null, false, this, messageMediaPhoto.Caption,
                                message.Id.ToString(CultureInfo.InvariantCulture));
                        }
                        else
                        {
                            captionBubble = new TextBubble(useCurrentTime ? Time.GetNowUnixTimestamp() : (long)message.Date,
                                message.Out != null ? Bubble.BubbleDirection.Outgoing : Bubble.BubbleDirection.Incoming,
                                addressStr, participantAddress, true, this, messageMediaPhoto.Caption,
                                message.Id.ToString(CultureInfo.InvariantCulture));
                        }
                        returnList.Add(captionBubble);
                    }
                    return returnList;
                }
                
            }
            else if (messageMediaDocument != null)
            {
                DebugPrint(">>>> Media document " + ObjectDumper.Dump(messageMediaDocument));
                //DebugPrint(">>>>> Media attributes " +  (messageMediaDocument.Document as Document).Attributes);
                var document = messageMediaDocument.Document as Document;
                if (document != null)
                {
                    FileInformation fileInfo = new FileInformation
                    {
                        FileType = "document",
                        Document = document
                    };
                    using (var memoryStream = new MemoryStream())
                    {
                        Serializer.Serialize<FileInformation>(memoryStream, fileInfo);
                        VisualBubble bubble = null;
                        if (document.MimeType.Contains("audio"))
                        {
                            var audioTime = (int) GetAudioTime(document);
                            if (isUser)
                            {
                                bubble =
                                    new AudioBubble(useCurrentTime ? Time.GetNowUnixTimestamp() : (long) message.Date,
                                        message.Out != null
                                            ? Bubble.BubbleDirection.Outgoing
                                            : Bubble.BubbleDirection.Incoming, addressStr, null, false, this, "",
                                        AudioBubble.Type.Url,
                                        false, audioTime, message.Id.ToString(CultureInfo.InvariantCulture));
                            }
                            else
                            {
                                bubble =
                                    new AudioBubble(useCurrentTime ? Time.GetNowUnixTimestamp() : (long) message.Date,
                                        message.Out != null
                                            ? Bubble.BubbleDirection.Outgoing
                                            : Bubble.BubbleDirection.Incoming, addressStr, participantAddress, true,
                                        this, "",
                                        AudioBubble.Type.Url, false, audioTime,
                                        message.Id.ToString(CultureInfo.InvariantCulture));
                            }
                        }
                        else
                        {
                            //TODO: localize
                            var filename = document.MimeType.Contains("video")
                                ? ""
                                : GetDocumentFileName(document);GetDocumentFileName(document);

                            if (isUser)
                            {
                                bubble =
                                    new FileBubble(useCurrentTime ? Time.GetNowUnixTimestamp() : (long) message.Date,
                                        message.Out != null
                                            ? Bubble.BubbleDirection.Outgoing
                                            : Bubble.BubbleDirection.Incoming, addressStr, null, false, this, "",
                                        FileBubble.Type.Url, filename, document.MimeType,
                                        message.Id.ToString(CultureInfo.InvariantCulture));
                            }
                            else
                            {
                                bubble =
                                    new FileBubble(useCurrentTime ? Time.GetNowUnixTimestamp() : (long) message.Date,
                                        message.Out != null
                                            ? Bubble.BubbleDirection.Outgoing
                                            : Bubble.BubbleDirection.Incoming, addressStr, participantAddress, true,
                                        this, "", FileBubble.Type.Url, filename, document.MimeType,
                                        message.Id.ToString(CultureInfo.InvariantCulture));
                            }

                        }

                        if (bubble.Direction == Bubble.BubbleDirection.Outgoing)
                        {
                            bubble.Status = Bubble.BubbleStatus.Sent;
                        }
                        bubble.AdditionalData = memoryStream.ToArray();

                        var returnList = new List<VisualBubble>
                        {
                            bubble
                        };
                        if (!string.IsNullOrEmpty(messageMediaDocument.Caption))
                        {
                            TextBubble captionBubble = null;
                            if (isUser)
                            {
                                captionBubble = new TextBubble(useCurrentTime ? Time.GetNowUnixTimestamp() : (long)message.Date,
                                    message.Out != null ? Bubble.BubbleDirection.Outgoing : Bubble.BubbleDirection.Incoming,
                                    addressStr, null, false, this, messageMediaDocument.Caption,
                                    message.Id.ToString(CultureInfo.InvariantCulture));
                            }
                            else
                            {
                                captionBubble = new TextBubble(useCurrentTime ? Time.GetNowUnixTimestamp() : (long)message.Date,
                                    message.Out != null ? Bubble.BubbleDirection.Outgoing : Bubble.BubbleDirection.Incoming,
                                    addressStr, participantAddress, true, this, messageMediaDocument.Caption,
                                    message.Id.ToString(CultureInfo.InvariantCulture));
                            }
                            returnList.Add(captionBubble);
                        }
                        return returnList;
                    }

                }

            }
            else if (messageMediaGeo != null)
            {

                var geoPoint = messageMediaGeo.Geo as GeoPoint;

                if (geoPoint != null)
                {
                    var geoBubble = MakeGeoBubble(geoPoint, message, isUser, useCurrentTime, addressStr, participantAddress, null);
                    return new List<VisualBubble>
                    {
                        geoBubble
                    };
                }


            }
            else if (messageMediaVenue != null)
            {
                var geoPoint = messageMediaVenue.Geo as GeoPoint;

                if (geoPoint != null)
                {
                    var geoBubble = MakeGeoBubble(geoPoint,message,isUser,useCurrentTime,addressStr,participantAddress,messageMediaVenue.Title);
                    return new List<VisualBubble>
                    {
                        geoBubble
                    };
                }

            }
            else if (messageMediaContact != null)
            {
                var contactCard = new ContactCard
                {
                    GivenName = messageMediaContact.FirstName,
                    FamilyName = messageMediaContact.LastName
                };
                contactCard.Phones.Add(new ContactCard.ContactCardPhone
                {
                    Number = messageMediaContact.PhoneNumber
                });
                var vCardData = Platform.GenerateBytesFromContactCard(contactCard);
                var contactBubble = MakeContactBubble(message, isUser, useCurrentTime, addressStr, participantAddress, vCardData, messageMediaContact.FirstName);

                return new List<VisualBubble>
                { 
                    contactBubble
                };
            }

            return new List<VisualBubble>();
        }
Пример #5
0
        private void ProcessIncomingPayload(List<object> payloads, bool useCurrentTime, TelegramClient optionalClient = null)
        {
            //NOTE: Only client disposable should be called in this method
            foreach (var payload in payloads)
            {
                var update = NormalizeUpdateIfNeeded(payload);

                var shortMessage = update as UpdateShortMessage;
                var shortChatMessage = update as UpdateShortChatMessage;
                var typing = update as UpdateUserTyping;
                var userStatus = update as UpdateUserStatus;
                var readMessages = update as UpdateReadMessages;
                var message = update as SharpTelegram.Schema.Layer18.Message;
                var user = update as IUser;
                var chat = update as IChat;

                if (shortMessage != null)
                {
                    if (!string.IsNullOrWhiteSpace(shortMessage.Message))
                    {
                        var fromId = shortMessage.FromId.ToString(CultureInfo.InvariantCulture);
                        EventBubble(new TypingBubble(Time.GetNowUnixTimestamp(),
                            Bubble.BubbleDirection.Incoming,
                            fromId, false, this, false, false));
                        EventBubble(new TextBubble(
                            useCurrentTime ? Time.GetNowUnixTimestamp() : (long)shortMessage.Date, 
                            Bubble.BubbleDirection.Incoming, 
                            fromId, null, false, this, shortMessage.Message,
                            shortMessage.Id.ToString(CultureInfo.InvariantCulture)));
                        CancelTypingTimer(shortMessage.FromId);
                    }
                    MarkMessageAsRecevied(shortMessage.Id, optionalClient);
                }
                else if (shortChatMessage != null)
                {
                    if (!string.IsNullOrWhiteSpace(shortChatMessage.Message))
                    {
                        var address = shortChatMessage.ChatId.ToString(CultureInfo.InvariantCulture);
                        var participantAddress = shortChatMessage.FromId.ToString(CultureInfo.InvariantCulture);
                        EventBubble(new TextBubble(
                            useCurrentTime ? Time.GetNowUnixTimestamp() : (long)shortChatMessage.Date, 
                            Bubble.BubbleDirection.Incoming, 
                            address, participantAddress, true, this, shortChatMessage.Message,
                            shortChatMessage.Id.ToString(CultureInfo.InvariantCulture)));
                    }
                    MarkMessageAsRecevied(shortChatMessage.Id, optionalClient);
                }
                else if (message != null)
                {
                    if (!string.IsNullOrWhiteSpace(message.MessageProperty))
                    {
                        TextBubble tb = null;

                        var peerUser = message.ToId as PeerUser;
                        var peerChat = message.ToId as PeerChat;

                        var direction = message.FromId == _settings.AccountId 
                        ? Bubble.BubbleDirection.Outgoing : Bubble.BubbleDirection.Incoming;

                        if (peerUser != null)
                        {
                            var address = direction == Bubble.BubbleDirection.Incoming ? message.FromId : peerUser.UserId;
                            var addressStr = address.ToString(CultureInfo.InvariantCulture);
                            tb = new TextBubble(
                                useCurrentTime ? Time.GetNowUnixTimestamp() : (long)message.Date,
                                direction, addressStr, null, false, this, message.MessageProperty,
                                message.Id.ToString(CultureInfo.InvariantCulture));
                        }
                        else if (peerChat != null)
                        {
                            var address = peerChat.ChatId.ToString(CultureInfo.InvariantCulture);
                            var participantAddress = message.FromId.ToString(CultureInfo.InvariantCulture);
                            tb = new TextBubble(
                                useCurrentTime ? Time.GetNowUnixTimestamp() : (long)message.Date,
                                direction, address, participantAddress, true, this, message.MessageProperty,
                                message.Id.ToString(CultureInfo.InvariantCulture));
                        }

                        if (direction == Bubble.BubbleDirection.Outgoing)
                        {
                            tb.Status = Bubble.BubbleStatus.Sent;
                        }

                        EventBubble(tb);
                    }
                    MarkMessageAsRecevied(message.Id, optionalClient);
                }
                else if (readMessages != null)
                {
                    //TODO:
                }
                else if (userStatus != null)
                {
                    var available = TelegramUtils.GetAvailable(userStatus.Status);
                    EventBubble(new PresenceBubble(Time.GetNowUnixTimestamp(),
                        Bubble.BubbleDirection.Incoming,
                        userStatus.UserId.ToString(CultureInfo.InvariantCulture),
                        false, this, available));
                }
                else if (typing != null)
                {
                    var isAudio = typing.Action is SendMessageRecordAudioAction;
                    var isTyping = typing.Action is SendMessageTypingAction;

                    if (isAudio || isTyping)
                    {
                        EventBubble(new TypingBubble(Time.GetNowUnixTimestamp(),
                            Bubble.BubbleDirection.Incoming,
                            typing.UserId.ToString(CultureInfo.InvariantCulture),
                            false, this, true, isAudio));
                        CancelTypingTimer(typing.UserId);
                        var newTimer = new Timer(6000) { AutoReset = false };
                        newTimer.Elapsed += (sender2, e2) =>
                        {
                            EventBubble(new TypingBubble(Time.GetNowUnixTimestamp(),
                                Bubble.BubbleDirection.Incoming,
                                typing.UserId.ToString(CultureInfo.InvariantCulture),
                                false, this, false, isAudio));
                            newTimer.Dispose();
                            _typingTimers.Remove(typing.UserId);
                        };
                        _typingTimers[typing.UserId] = newTimer;
                        newTimer.Start();
                    }
                    else
                    {
                        Console.WriteLine("Unknown typing action: " + typing.Action.GetType().Name);
                    }
                }
                else if (user != null)
                {
                    if (_dialogs == null)
                        return;
                    var userId = TelegramUtils.GetUserId(user);
                    if (userId != null)
                    {
                        var updatedUser = false;
                        for (int i = 0; i < _dialogs.Users.Count; i++)
                        {
                            var userInnerId = TelegramUtils.GetUserId(_dialogs.Users[i]);
                            if (userInnerId != null && userInnerId == userId)
                            {
                                Console.WriteLine("Updating user with new updates information: " + userId);
                                _dialogs.Users[i] = user;
                                updatedUser = true;
                                break;
                            }
                        }
                        if (!updatedUser)
                        {
                            Console.WriteLine("New user information: " + userId + " adding to dialogs!");
                            _dialogs.Users.Add(user);
                        }
                    }
                }
                else if (chat != null)
                {
                    if (_dialogs == null)
                        return;
                    var chatId = TelegramUtils.GetChatId(chat);
                    if (chatId != null)
                    {
                        var updatedChat = false;
                        for (int i = 0; i < _dialogs.Chats.Count; i++)
                        {
                            var chatInnerId = TelegramUtils.GetChatId(_dialogs.Chats[i]);
                            if (chatInnerId != null && chatInnerId == chatId)
                            {
                                Console.WriteLine("Updating chat with new updates information: " + chatId);
                                _dialogs.Chats[i] = chat;
                                updatedChat = true;
                                break;
                            }
                        }
                        if (!updatedChat)
                        {
                            Console.WriteLine("New chat information: " + chatId + " adding to dialogs!");
                            _dialogs.Chats.Add(chat);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Unknown update: " + ObjectDumper.Dump(update));
                }
            }            
        }
Пример #6
0
        private void ProcessIncomingPayload(List<object> payloads, bool useCurrentTime, TelegramClient optionalClient = null)
        {
            uint maxMessageId = 0;

            foreach (var payload in AdjustUpdates(payloads))
            {
                var update = NormalizeUpdateIfNeeded(payload);

                var shortMessage = update as UpdateShortMessage;
                var shortChatMessage = update as UpdateShortChatMessage;
                var typing = update as UpdateUserTyping;
                var typingChat = update as UpdateChatUserTyping;
                var userStatus = update as UpdateUserStatus;
                var messageService = update as MessageService;
                var updateChatParticipants = update as UpdateChatParticipants;
                var updateContactRegistered = update as UpdateContactRegistered;
                var updateContactLink = update as UpdateContactLink;
                var updateUserPhoto = update as UpdateUserPhoto;
                var updateReadHistoryInbox = update as UpdateReadHistoryInbox;
                var updateReadHistoryOutbox = update as UpdateReadHistoryOutbox;
                var updateReadChannelInbox = update as UpdateReadChannelInbox;
                var message = update as SharpTelegram.Schema.Message;
                var user = update as IUser;
                var chat = update as IChat;

                DebugPrint(">>>>>> The type of object in process incoming payload is " + ObjectDumper.Dump(update));

                if (shortMessage != null)
                {
                    if (!string.IsNullOrWhiteSpace(shortMessage.Message))
                    {
						var fromId = shortMessage.UserId.ToString(CultureInfo.InvariantCulture);
                        var shortMessageUser = _dialogs.GetUser(shortMessage.UserId);
                        if (shortMessageUser == null)
                        {
                            DebugPrint(">>>>> User is null, fetching user from the server");
                            GetMessage(shortMessage.Id, optionalClient);
                        }
                        
                        EventBubble(new TypingBubble(Time.GetNowUnixTimestamp(),
                            Bubble.BubbleDirection.Incoming,
                            fromId, false, this, false, false));
                        TextBubble textBubble = new TextBubble(
                                            useCurrentTime ? Time.GetNowUnixTimestamp() : (long)shortMessage.Date, 
                                            shortMessage.Out != null ? Bubble.BubbleDirection.Outgoing : Bubble.BubbleDirection.Incoming, 
                                            fromId, null, false, this, shortMessage.Message,
                                            shortMessage.Id.ToString(CultureInfo.InvariantCulture));
                        
                        if (shortMessage.Out != null)
                        {
                            textBubble.Status = Bubble.BubbleStatus.Sent;
                        }
                        if (textBubble.Direction == Bubble.BubbleDirection.Incoming)
                        {
                            if (shortMessage.ReplyToMsgId != 0)
                            {
                                var iReplyMessage = GetMessage(shortMessage.ReplyToMsgId,optionalClient);
                                DebugPrint(">>> got message " + ObjectDumper.Dump(iReplyMessage));
                                var replyMessage = iReplyMessage as Message;
                                AddQuotedMessageToBubble(replyMessage, textBubble);

                            }
                        }
                        EventBubble(textBubble);
                    }
                    if (shortMessage.Id > maxMessageId)
                    {
                        maxMessageId = shortMessage.Id;
                    }
                }
                else if (updateUserPhoto != null)
                {
                    var iUpdatedUser = _dialogs.GetUser(updateUserPhoto.UserId);
                    var updatedUser = iUpdatedUser as User;
                    if (updatedUser != null)
                    {
                        updatedUser.Photo = updateUserPhoto.Photo;
                    }
                    _dialogs.AddUser(updatedUser);
                }
                else if (updateReadHistoryOutbox != null)
                {
                    var iPeer = updateReadHistoryOutbox.Peer;
                    var peerChat = iPeer as PeerChat;
                    var peerUser = iPeer as PeerUser;


                    if (peerUser != null)
                    {
                        BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                            peerUser.UserId.ToString(CultureInfo.InvariantCulture));
                        DebugPrint("Found bubble group " + bubbleGroup);
                        if (bubbleGroup != null)
                        {
                            string idString = bubbleGroup.LastBubbleSafe().IdService;
                            if (idString == updateReadHistoryOutbox.MaxId.ToString(CultureInfo.InvariantCulture))
                            {
                                EventBubble(
                                    new ReadBubble(Time.GetNowUnixTimestamp(),
                                        Bubble.BubbleDirection.Incoming, this,
                                        peerUser.UserId.ToString(CultureInfo.InvariantCulture), null,
                                        Time.GetNowUnixTimestamp(), false, false));
                            }
                        }
                        

                    }
                    else if (peerChat != null)
                    {
                        BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                           peerChat.ChatId.ToString(CultureInfo.InvariantCulture));
                        if (bubbleGroup != null)
                        {
                            string idString = bubbleGroup.LastBubbleSafe().IdService;
                            if (idString == updateReadHistoryOutbox.MaxId.ToString(CultureInfo.InvariantCulture))
                            {
                                EventBubble(
                                    new ReadBubble(
                                        Time.GetNowUnixTimestamp(),
                                        Bubble.BubbleDirection.Incoming, this,
                                        peerChat.ChatId.ToString(CultureInfo.InvariantCulture), _settings.AccountId.ToString(CultureInfo.InvariantCulture),
                                        Time.GetNowUnixTimestamp(), true, false));
                            }
                        }

                    }

                }
                else if (updateReadHistoryInbox != null)
                {
                    DebugPrint(">>> In update read history inbox");
                    var iPeer = updateReadHistoryInbox.Peer;
                    var peerChat = iPeer as PeerChat;
                    var peerUser = iPeer as PeerUser;

                    if (peerUser != null)
                    {
                        BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                            peerUser.UserId.ToString(CultureInfo.InvariantCulture));

                        if (bubbleGroup == null)
                        {
                            return;
                        }

                        string idString = bubbleGroup.LastBubbleSafe().IdService;
                        DebugPrint("idstring" + idString);
                        if (uint.Parse(idString) <= updateReadHistoryInbox.MaxId)
                        {
                            BubbleGroupManager.SetUnread(this,false, peerUser.UserId.ToString(CultureInfo.InvariantCulture));
                            NotificationManager.Remove(this,peerUser.UserId.ToString(CultureInfo.InvariantCulture));
                        }

                    }
                    else if (peerChat != null)
                    {
                        BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                            peerChat.ChatId.ToString(CultureInfo.InvariantCulture));
                        if (bubbleGroup == null)
                        {
                            return;
                        }
                        string idString = bubbleGroup.LastBubbleSafe().IdService;
                        if (uint.Parse(idString) == updateReadHistoryInbox.MaxId)
                        {
                            BubbleGroupManager.SetUnread(this, false,
                                peerChat.ChatId.ToString(CultureInfo.InvariantCulture));
                            NotificationManager.Remove(this, peerChat.ChatId.ToString(CultureInfo.InvariantCulture));
                        }

                    }

                }


                else if (shortChatMessage != null)
                {
                    if (!string.IsNullOrWhiteSpace(shortChatMessage.Message))
                    {
                        var address = shortChatMessage.ChatId.ToString(CultureInfo.InvariantCulture);
                        var participantAddress = shortChatMessage.FromId.ToString(CultureInfo.InvariantCulture);
                        EventBubble(new TypingBubble(Time.GetNowUnixTimestamp(),
                            Bubble.BubbleDirection.Incoming,
                            address, participantAddress, true, this, false, false));
                        TextBubble textBubble = new TextBubble(
                            useCurrentTime ? Time.GetNowUnixTimestamp() : (long) shortChatMessage.Date,
                            shortChatMessage.Out != null
                                ? Bubble.BubbleDirection.Outgoing
                                : Bubble.BubbleDirection.Incoming,
                            address, participantAddress, true, this, shortChatMessage.Message,
                            shortChatMessage.Id.ToString(CultureInfo.InvariantCulture));
                        if (shortChatMessage.Out != null)
                        {
                            textBubble.Status = Bubble.BubbleStatus.Sent;
                        }
                        if (textBubble.Direction == Bubble.BubbleDirection.Incoming)
                        {
                            if (shortChatMessage.ReplyToMsgId != 0)
                            {
                                var iReplyMessage = GetMessage(shortChatMessage.ReplyToMsgId,optionalClient);
                                DebugPrint(">>> got message " + ObjectDumper.Dump(iReplyMessage));
                                var replyMessage = iReplyMessage as Message;
                                AddQuotedMessageToBubble(replyMessage, textBubble);

                            }
                        }

                        EventBubble(textBubble);
                    }
                    if (shortChatMessage.Id > maxMessageId)
                    {
                        maxMessageId = shortChatMessage.Id;
                    }
                }
                else if (message != null)
                {
                    var bubble = ProcessFullMessage(message,useCurrentTime);
                    if (bubble != null)
                    {
                        if (bubble.Direction == Bubble.BubbleDirection.Incoming)
                        {
                            var fromId = message.FromId.ToString(CultureInfo.InvariantCulture);
                            var messageUser = _dialogs.GetUser(message.FromId);
                            if (messageUser == null)
                            {
                                DebugPrint(">>>>> User is null, fetching user from the server");
                                GetMessage(message.Id, optionalClient);
                            }
                            if (message.ReplyToMsgId != 0)
                            {
                                var iReplyMessage = GetMessage(message.ReplyToMsgId,optionalClient);
                                DebugPrint(">>> got message " + ObjectDumper.Dump(iReplyMessage));
                                var replyMessage = iReplyMessage as Message;
                                AddQuotedMessageToBubble(replyMessage, bubble);

                            }
                        }
                        EventBubble(bubble);
                    }
                    if (message.Id > maxMessageId)
                    {
                        maxMessageId = message.Id;
                    }
                }
                else if (updateContactRegistered != null)
                {
                    contactsCache = new List<User>(); //invalidate cache
                }
                else if (updateContactLink != null)
                {
                    contactsCache = new List<User>();
                }
                else if (userStatus != null)
                {
                    var available = TelegramUtils.GetAvailable(userStatus.Status);
                    var userToUpdate = _dialogs.GetUser(userStatus.UserId);
                    if (userToUpdate != null)
                    {
                        var userToUpdateAsUser = userToUpdate as User;
                        if (userToUpdateAsUser != null)
                        {
                            userToUpdateAsUser.Status = userStatus.Status;
                            _dialogs.AddUser(userToUpdateAsUser);
                        }
                    }

                    EventBubble(new PresenceBubble(Time.GetNowUnixTimestamp(),
                        Bubble.BubbleDirection.Incoming,
                        userStatus.UserId.ToString(CultureInfo.InvariantCulture),
                        false, this, available));
                }
                else if (typing != null || typingChat != null)
                {
                    var isAudio = false;
                    var isTyping = false;
                    if (typing != null)
                    {
                        isAudio = typing.Action is SendMessageRecordAudioAction;
                        isTyping = typing.Action is SendMessageTypingAction;
                    }
                    if (typingChat != null)
                    {
                        isAudio = typingChat.Action is SendMessageRecordAudioAction;
                        isTyping = typingChat.Action is SendMessageTypingAction;
                    }
                    var userId = typing != null ? typing.UserId : typingChat.UserId;
                    var party = typingChat != null;
                    var participantAddress = party ? userId.ToString(CultureInfo.InvariantCulture) : null;
                    var address = party
                        ? typingChat.ChatId.ToString(CultureInfo.InvariantCulture)
                        : userId.ToString(CultureInfo.InvariantCulture);
                    var key = address + participantAddress;


                    if (isAudio || isTyping)
                    {
                        EventBubble(new TypingBubble(Time.GetNowUnixTimestamp(),
                            Bubble.BubbleDirection.Incoming,
                            address, participantAddress, party,
                            this, true, isAudio));
                        CancelTypingTimer(key);
                        var newTimer = new Timer(6000) {AutoReset = false};
                        newTimer.Elapsed += (sender2, e2) =>
                        {
                            EventBubble(new TypingBubble(Time.GetNowUnixTimestamp(),
                                Bubble.BubbleDirection.Incoming,
                                address, participantAddress, party,
                                this, false, isAudio));
                            newTimer.Dispose();
                            _typingTimers.Remove(key);
                        };
                        _typingTimers[key] = newTimer;
                        newTimer.Start();
                    }
                    else
                    {
                        //Console.WriteLine("Unknown typing action: " + typing.Action.GetType().Name); //causes null pointer in some cases
                    }
                }
                else if (user != null)
                {
                    _dialogs.AddUser(user);
                }
                else if (chat != null)
                {
                    _dialogs.AddChat(chat);
                }
                else if (updateChatParticipants != null)
                {
                    //do nothing, we just use party options for this
                }
                else if (messageService != null)
                {
                    var editTitle = messageService.Action as MessageActionChatEditTitle;
                    var deleteUser = messageService.Action as MessageActionChatDeleteUser;
                    var addUser = messageService.Action as MessageActionChatAddUser;
                    var created = messageService.Action as MessageActionChatCreate;

                    var address = TelegramUtils.GetPeerId(messageService.ToId);
                    var fromId = messageService.FromId.ToString(CultureInfo.InvariantCulture);
                    if (editTitle != null)
                    {
                        var newTitle = editTitle.Title;
                        var chatToUpdate = _dialogs.GetChat(uint.Parse(address));
                        if (chatToUpdate != null)
                        {
                            TelegramUtils.SetChatTitle(chatToUpdate, newTitle);
                        }
                        EventBubble(PartyInformationBubble.CreateTitleChanged(
                            useCurrentTime ? Time.GetNowUnixTimestamp() : (long) messageService.Date, address,
                            this, messageService.Id.ToString(CultureInfo.InvariantCulture), fromId, newTitle));
                        BubbleGroupUpdater.Update(this, address);
                    }
                    else if (deleteUser != null)
                    {
                        var userDeleted = deleteUser.UserId.ToString(CultureInfo.InvariantCulture);
                        EventBubble(PartyInformationBubble.CreateParticipantRemoved(
                            useCurrentTime ? Time.GetNowUnixTimestamp() : (long) messageService.Date, address,
                            this, messageService.Id.ToString(CultureInfo.InvariantCulture), fromId, userDeleted));
                    }
                    else if (addUser != null)
                    {
                        foreach (var userId in addUser.Users)
                        {
                            var userAdded = userId.ToString(CultureInfo.InvariantCulture);
                            EventBubble(PartyInformationBubble.CreateParticipantAdded(
                                useCurrentTime ? Time.GetNowUnixTimestamp() : (long) messageService.Date, address,
                                this, messageService.Id.ToString(CultureInfo.InvariantCulture), fromId, userAdded));
                        }
                    }
                    else if (created != null)
                    {
                        EventBubble(PartyInformationBubble.CreateParticipantAdded(
                            useCurrentTime ? Time.GetNowUnixTimestamp() : (long) messageService.Date, address,
                            this, messageService.Id.ToString(CultureInfo.InvariantCulture), fromId,
                            _settings.AccountId.ToString(CultureInfo.InvariantCulture)));
                    }
                    else
                    {
                        Console.WriteLine("Unknown message service: " + ObjectDumper.Dump(update));
                    }
                }
                else
                {
                    Console.WriteLine("Unknown update: " + ObjectDumper.Dump(update));
                }
            }

            if (maxMessageId != 0)
            {
                SendReceivedMessages(optionalClient, maxMessageId);
            }
        }