Esempio n. 1
0
        public void handle(SignalServiceEnvelope envelope, bool sendExplicitReceipt)
        {
            if (!isActiveNumber(envelope.getSource()))
            {
                TextSecureDirectory directory           = DatabaseFactory.getDirectoryDatabase();
                ContactTokenDetails contactTokenDetails = new ContactTokenDetails();
                contactTokenDetails.setNumber(envelope.getSource());

                directory.setNumber(contactTokenDetails, true);

                // TODO: evtl DirectoryRefresh
            }

            if (envelope.isReceipt())
            {
                handleReceipt(envelope);
            }
            else if (envelope.isPreKeySignalMessage() || envelope.isSignalMessage())
            {
                handleMessage(envelope, sendExplicitReceipt);
            }
            else
            {
                Log.Warn($"Received envelope of unknown type: {envelope.GetType()}");
            }
        }
Esempio n. 2
0
        private void handleEndSessionMessage(SignalServiceEnvelope envelope,
                                             SignalServiceDataMessage message,
                                             May <long> smsMessageId)
        {
            var smsDatabase         = DatabaseFactory.getTextMessageDatabase();//getEncryptingSmsDatabase(context);
            var incomingTextMessage = new IncomingTextMessage(envelope.getSource(),
                                                              envelope.getSourceDevice(),
                                                              message.getTimestamp(),
                                                              "", May <SignalServiceGroup> .NoValue);

            long threadId;

            if (!smsMessageId.HasValue)
            {
                IncomingEndSessionMessage incomingEndSessionMessage = new IncomingEndSessionMessage(incomingTextMessage);
                Pair <long, long>         messageAndThreadId        = smsDatabase.InsertMessageInbox(incomingEndSessionMessage);

                threadId = messageAndThreadId.second();
            }
            else
            {
                var messageId = smsMessageId.ForceGetValue();
                smsDatabase.MarkAsEndSession(messageId);
                threadId = smsDatabase.GetThreadIdForMessage(messageId);
            }

            SessionStore sessionStore = new TextSecureAxolotlStore();

            sessionStore.DeleteAllSessions(envelope.getSource());

            //SecurityEvent.broadcastSecurityUpdateEvent(context, threadId);
            //MessageNotifier.updateNotification(context, masterSecret.getMasterSecret().orNull(), threadId);
        }
Esempio n. 3
0
        private void HandleSessionResetMessage(SignalServiceEnvelope envelope, SignalServiceContent content, SignalServiceDataMessage dataMessage, bool isSync, long timestamp)
        {
            SignalMessageDirection type;
            SignalContact          author;
            SignalMessageStatus    status;
            string prefix;
            string conversationId;
            long   composedTimestamp;

            if (isSync)
            {
                var sent = content.SynchronizeMessage.getSent().ForceGetValue();
                type              = SignalMessageDirection.Synced;
                status            = SignalMessageStatus.Confirmed;
                composedTimestamp = sent.getTimestamp();
                author            = null;
                prefix            = "You have";
                conversationId    = sent.getDestination().ForceGetValue();
            }
            else
            {
                status            = 0;
                type              = SignalMessageDirection.Incoming;
                author            = SignalDBContext.GetOrCreateContactLocked(envelope.getSource(), timestamp, this);
                prefix            = $"{author.ThreadDisplayName} has";
                composedTimestamp = envelope.getTimestamp();
                conversationId    = envelope.getSource();
            }
            LibsignalDBContext.DeleteAllSessions(conversationId);

            SignalMessage sm = new SignalMessage()
            {
                Direction = type,
                Type      = SignalMessageType.SessionReset,
                Status    = status,
                Author    = author,
                Content   = new SignalMessageContent()
                {
                    Content = $"{prefix} reset the session."
                },
                ThreadId          = conversationId,
                DeviceId          = (uint)envelope.getSourceDevice(),
                Receipts          = 0,
                ComposedTimestamp = composedTimestamp,
                ReceivedTimestamp = timestamp,
            };

            Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                await UIHandleIncomingMessage(sm);
            }).AsTask().Wait();
        }
Esempio n. 4
0
        private void HandleSessionResetMessage(SignalServiceEnvelope envelope, SignalServiceContent content, SignalServiceDataMessage dataMessage, bool isSync, long timestamp)
        {
            SignalMessageDirection type;
            SignalContact          author;
            SignalMessageStatus    status;
            SignalConversation     conversation;
            string prefix;
            string conversationId;
            long   composedTimestamp;

            if (isSync)
            {
                var sent = content.SynchronizeMessage.getSent().ForceGetValue();
                type              = SignalMessageDirection.Synced;
                status            = SignalMessageStatus.Confirmed;
                composedTimestamp = sent.getTimestamp();
                author            = null;
                prefix            = "You have";
                conversationId    = sent.getDestination().ForceGetValue();
            }
            else
            {
                status            = 0;
                type              = SignalMessageDirection.Incoming;
                author            = SignalDBContext.GetOrCreateContactLocked(envelope.getSource(), timestamp);
                prefix            = $"{author.ThreadDisplayName} has";
                composedTimestamp = envelope.getTimestamp();
                conversationId    = envelope.getSource();
            }
            LibsignalDBContext.DeleteAllSessions(conversationId);
            conversation = SignalDBContext.GetOrCreateContactLocked(conversationId, 0);

            SignalMessage sm = new SignalMessage()
            {
                Direction = type,
                Type      = SignalMessageType.SessionReset,
                Status    = status,
                Author    = author,
                Content   = new SignalMessageContent()
                {
                    Content = $"{prefix} reset the session."
                },
                ThreadId          = conversationId,
                DeviceId          = (uint)envelope.getSourceDevice(),
                Receipts          = 0,
                ComposedTimestamp = composedTimestamp,
                ReceivedTimestamp = timestamp,
            };

            SignalLibHandle.Instance.SaveAndDispatchSignalMessage(sm, conversation);
        }
Esempio n. 5
0
        private void handleMessage(SignalServiceEnvelope envelope, bool sendExplicitReceipt)
        {
            var  worker    = App.Current.Worker;
            long messageId = DatabaseFactory.getPushDatabase().Insert(envelope);

            if (sendExplicitReceipt)
            {
                worker.AddTaskActivities(new DeliveryReceiptTask(envelope.getSource(),
                                                                 envelope.getTimestamp(),
                                                                 envelope.getRelay()));
            }

            worker.AddTaskActivities(new PushDecryptTask(messageId, envelope.getSource()));
        }
Esempio n. 6
0
        public static SignalMessage IncreaseReceiptCountLocked(SignalServiceEnvelope envelope)
        {
            SignalMessage m;
            bool          set_mark = false;

            lock (DBLock)
            {
                using (var ctx = new SignalDBContext())
                {
                    m = ctx.Messages.SingleOrDefault(t => t.ComposedTimestamp == envelope.getTimestamp());
                    if (m != null)
                    {
                        m.Receipts++;
                        if (m.Status == SignalMessageStatus.Confirmed)
                        {
                            m.Status = SignalMessageStatus.Received;
                            set_mark = true;
                        }
                    }
                    else
                    {
                        ctx.EarlyReceipts.Add(new SignalEarlyReceipt()
                        {
                            DeviceId  = (uint)envelope.getSourceDevice(),
                            Timestamp = envelope.getTimestamp(),
                            Username  = envelope.getSource()
                        });
                    }
                    ctx.SaveChanges();
                }
            }
            return(set_mark? m : null);
        }
        private byte[] decrypt(SignalServiceEnvelope envelope, byte[] ciphertext)

        {
            SignalProtocolAddress sourceAddress = new SignalProtocolAddress(envelope.getSource(), (uint)envelope.getSourceDevice());
            SessionCipher         sessionCipher = new SessionCipher(signalProtocolStore, sourceAddress);

            byte[] paddedMessage;

            if (envelope.isPreKeySignalMessage())
            {
                paddedMessage = sessionCipher.decrypt(new PreKeySignalMessage(ciphertext));
            }
            else if (envelope.isSignalMessage())
            {
                paddedMessage = sessionCipher.decrypt(new SignalMessage(ciphertext));
            }
            else
            {
                throw new InvalidMessageException("Unknown type: " + envelope.getType() + " from " + envelope.getSource());
            }

            PushTransportDetails transportDetails = new PushTransportDetails(sessionCipher.getSessionVersion());

            return(transportDetails.getStrippedPaddingMessageBody(paddedMessage));
        }
Esempio n. 8
0
        private Pair <long, long> insertPlaceholder(SignalServiceEnvelope envelope)
        {
            var database = DatabaseFactory.getTextMessageDatabase(); //getEncryptingSmsDatabase(context);
            IncomingTextMessage textMessage = new IncomingTextMessage(envelope.getSource(), envelope.getSourceDevice(),
                                                                      envelope.getTimestamp(), "",
                                                                      May <SignalServiceGroup> .NoValue);

            textMessage = new IncomingEncryptedMessage(textMessage, "");
            return(database.InsertMessageInbox(textMessage));
        }
Esempio n. 9
0
        private void handleTextMessage(/*@NonNull MasterSecretUnion masterSecret,*/
            SignalServiceEnvelope envelope,
            SignalServiceDataMessage message,
            May <long> smsMessageId)
        {
            var    textMessageDatabase = DatabaseFactory.getTextMessageDatabase();
            String body = message.getBody().HasValue ? message.getBody().ForceGetValue() : "";


            IncomingTextMessage textMessage = new IncomingTextMessage(envelope.getSource(),
                                                                      envelope.getSourceDevice(),
                                                                      message.getTimestamp(), body,
                                                                      message.getGroupInfo());

            textMessage = new IncomingEncryptedMessage(textMessage, body);
            var messageAndThreadId = textMessageDatabase.InsertMessageInbox(textMessage);

            ToastHelper.NotifyNewMessage(messageAndThreadId.second(), DatabaseFactory.getDirectoryDatabase().GetForNumber(envelope.getSource()).Name, body);
        }
Esempio n. 10
0
        public long Insert(SignalServiceEnvelope envelope)
        {
            // TODO check if exists
            var push = new Push()
            {
                Type          = envelope.getType(),
                Source        = envelope.getSource(),
                DeviceId      = envelope.getSourceDevice(),
                LegacyMessage = envelope.hasLegacyMessage() ? Base64.encodeBytes(envelope.getLegacyMessage()) : "",
                Content       = envelope.hasContent() ? Base64.encodeBytes(envelope.getContent()) : "",
                Timestamp     = TimeUtil.GetDateTime(envelope.getTimestamp())
            };

            try
            {
                conn.Insert(push);
            } catch (Exception e) { Debug.WriteLine(e.Message); }


            return(push.PushId);
        }
Esempio n. 11
0
        public static void IncreaseReceiptCountLocked(SignalServiceEnvelope envelope, MainPageViewModel mpvm)
        {
            SignalMessage m;
            bool          set_mark = false;

            lock (DBLock)
            {
                using (var ctx = new SignalDBContext())
                {
                    m = ctx.Messages.SingleOrDefault(t => t.ComposedTimestamp == envelope.getTimestamp());
                    if (m != null)
                    {
                        m.Receipts++;
                        if (m.Status == SignalMessageStatus.Confirmed)
                        {
                            m.Status = SignalMessageStatus.Received;
                            set_mark = true;
                        }
                    }
                    else
                    {
                        ctx.EarlyReceipts.Add(new SignalEarlyReceipt()
                        {
                            DeviceId  = (uint)envelope.getSourceDevice(),
                            Timestamp = envelope.getTimestamp(),
                            Username  = envelope.getSource()
                        });
                    }
                    ctx.SaveChanges();
                }
            }
            if (set_mark)
            {
                Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    mpvm.UIUpdateMessageBox(m);
                }).AsTask().Wait();
            }
        }
Esempio n. 12
0
        private void handleUntrustedIdentityMessage(SignalServiceEnvelope envelope, May <long> smsMessageId)
        {
            try
            {
                var                 database       = DatabaseFactory.getTextMessageDatabase(); //getEncryptingSmsDatabase(context);
                Recipients          recipients     = RecipientFactory.getRecipientsFromString(envelope.getSource(), false);
                long                recipientId    = recipients.getPrimaryRecipient().getRecipientId();
                PreKeySignalMessage whisperMessage = new PreKeySignalMessage(envelope.getLegacyMessage());
                IdentityKey         identityKey    = whisperMessage.getIdentityKey();
                String              encoded        = Base64.encodeBytes(envelope.getLegacyMessage());
                IncomingTextMessage textMessage    = new IncomingTextMessage(envelope.getSource(), envelope.getSourceDevice(),
                                                                             envelope.getTimestamp(), encoded,
                                                                             May <SignalServiceGroup> .NoValue);

                if (!smsMessageId.HasValue)
                {
                    IncomingPreKeyBundleMessage bundleMessage      = new IncomingPreKeyBundleMessage(textMessage, encoded);
                    Pair <long, long>           messageAndThreadId = database.InsertMessageInbox(bundleMessage);

                    database.SetMismatchedIdentity(messageAndThreadId.first(), recipientId, identityKey);
                    //MessageNotifier.updateNotification(context, masterSecret.getMasterSecret().orNull(), messageAndThreadId.second);
                }
                else
                {
                    var messageId = smsMessageId.ForceGetValue();
                    database.UpdateMessageBody(messageId, encoded);
                    database.MarkAsPreKeyBundle(messageId);
                    database.SetMismatchedIdentity(messageId, recipientId, identityKey);
                }
            }
            catch (InvalidMessageException e)
            {
                throw new InvalidOperationException(e.Message);
            }
            catch (InvalidVersionException e)
            {
                throw new InvalidOperationException(e.Message);
            }
        }
Esempio n. 13
0
        private void HandleMessage(SignalServiceEnvelope envelope)
        {
            var  cipher    = new SignalServiceCipher(new SignalServiceAddress(App.Store.Username), new Store());
            var  content   = cipher.decrypt(envelope);
            long timestamp = Util.CurrentTimeMillis();

            if (content.Message != null)
            {
                SignalServiceDataMessage message = content.Message;
                if (message.EndSession)
                {
                    HandleSessionResetMessage(envelope, content, message, false, timestamp);
                }
                else if (message.IsGroupUpdate())
                {
                    if (message.Group.Type == SignalServiceGroup.GroupType.UPDATE)
                    {
                        HandleGroupUpdateMessage(envelope, content, message, false, timestamp);
                    }
                }
                else if (message.ExpirationUpdate)
                {
                    HandleExpirationUpdateMessage(envelope, content, message, false, timestamp);
                }
                else
                {
                    HandleSignalMessage(envelope, content, message, false, timestamp);
                }
            }
            else if (content.SynchronizeMessage != null)
            {
                if (content.SynchronizeMessage.getSent().HasValue)
                {
                    var syncMessage = content.SynchronizeMessage.getSent().ForceGetValue();
                    var dataMessage = syncMessage.getMessage();

                    if (dataMessage.EndSession)
                    {
                        HandleSessionResetMessage(envelope, content, dataMessage, true, timestamp);
                    }
                    else if (dataMessage.IsGroupUpdate())
                    {
                        if (dataMessage.Group.Type == SignalServiceGroup.GroupType.UPDATE)
                        {
                            HandleGroupUpdateMessage(envelope, content, dataMessage, true, timestamp);
                        }
                    }
                    else if (dataMessage.ExpirationUpdate)
                    {
                        HandleExpirationUpdateMessage(envelope, content, dataMessage, true, timestamp);
                    }
                    else
                    {
                        HandleSignalMessage(envelope, content, dataMessage, true, timestamp);
                    }
                }
                else if (content.SynchronizeMessage.getRead().HasValue)
                {
                    var readMessages = content.SynchronizeMessage.getRead().ForceGetValue();
                    foreach (var readMessage in readMessages)
                    {
                        //TODO
                    }
                }
            } //TODO callmessages
            else
            {
                Debug.WriteLine("HandleMessage got unrecognized message from " + envelope.getSource());
            }
        }
Esempio n. 14
0
 public void OnMessage(SignalServiceMessagePipeMessage message)
 {
     if (message is SignalServiceEnvelope)
     {
         SignalServiceEnvelope envelope = (SignalServiceEnvelope)message;
         List <SignalMessage>  messages = new List <SignalMessage>();
         if (envelope.isReceipt())
         {
             SignalDBContext.IncreaseReceiptCountLocked(envelope, this);
         }
         else if (envelope.isPreKeySignalMessage() || envelope.isSignalMessage())
         {
             HandleMessage(envelope);
         }
         else
         {
             Debug.WriteLine("received message of unknown type " + envelope.getType() + " from " + envelope.getSource());
         }
     }
 }
Esempio n. 15
0
        private void HandleSignalMessage(SignalServiceEnvelope envelope, SignalServiceContent content, SignalServiceDataMessage dataMessage, bool isSync, long timestamp)
        {
            SignalMessageDirection type;
            SignalContact          author;
            SignalMessageStatus    status;
            string threadId;
            long   composedTimestamp;
            string body = dataMessage.Body != null ? dataMessage.Body : "";

            if (dataMessage.Group != null)
            {
                var rawId = dataMessage.Group.GroupId;
                threadId = Base64.encodeBytes(rawId);
                var g = SignalDBContext.GetOrCreateGroupLocked(threadId, timestamp, this);
                if (!g.CanReceive)
                {
                    SignalServiceGroup group = new SignalServiceGroup()
                    {
                        Type    = SignalServiceGroup.GroupType.REQUEST_INFO,
                        GroupId = rawId
                    };
                    SignalServiceDataMessage requestInfoMessage = new SignalServiceDataMessage()
                    {
                        Group     = group,
                        Timestamp = Util.CurrentTimeMillis()
                    };
                    MessageSender.sendMessage(envelope.getSourceAddress(), requestInfoMessage);
                }
                composedTimestamp = envelope.getTimestamp();
            }
            else
            {
                if (isSync)
                {
                    var sent = content.SynchronizeMessage.getSent().ForceGetValue();
                    threadId          = SignalDBContext.GetOrCreateContactLocked(sent.getDestination().ForceGetValue(), timestamp, this).ThreadId;
                    composedTimestamp = sent.getTimestamp();
                }
                else
                {
                    threadId          = SignalDBContext.GetOrCreateContactLocked(envelope.getSource(), timestamp, this).ThreadId;
                    composedTimestamp = envelope.getTimestamp();
                }
            }

            if (isSync)
            {
                type   = SignalMessageDirection.Synced;
                status = SignalMessageStatus.Confirmed;
                author = null;
            }
            else
            {
                status = 0;
                type   = SignalMessageDirection.Incoming;
                author = SignalDBContext.GetOrCreateContactLocked(envelope.getSource(), timestamp, this);
            }

            List <SignalAttachment> attachments = new List <SignalAttachment>();
            SignalMessage           message     = new SignalMessage()
            {
                Direction = type,
                Status    = status,
                Author    = author,
                Content   = new SignalMessageContent()
                {
                    Content = body
                },
                ThreadId          = threadId,
                DeviceId          = (uint)envelope.getSourceDevice(),
                Receipts          = 0,
                ComposedTimestamp = composedTimestamp,
                ReceivedTimestamp = timestamp,
                AttachmentsCount  = (uint)attachments.Count,
                Attachments       = attachments
            };

            if (dataMessage.Attachments != null)
            {
                var receivedAttachments = dataMessage.Attachments;
                foreach (var receivedAttachment in receivedAttachments)
                {
                    var pointer         = receivedAttachment.asPointer();
                    SignalAttachment sa = new SignalAttachment()
                    {
                        Message      = message,
                        Status       = (uint)SignalAttachmentStatus.Default,
                        SentFileName = pointer.FileName,
                        ContentType  = "",
                        Key          = pointer.Key,
                        Relay        = pointer.Relay,
                        StorageId    = pointer.Id
                    };
                    attachments.Add(sa);
                }
            }
            Debug.WriteLine("received message: " + message.Content);
            if (type == SignalMessageDirection.Incoming)
            {
                if (App.WindowActive)
                {
                    Utils.TryVibrate(true);
                }
                else
                {
                    SendTileNotification(message);
                    SendMessageNotification(message);
                }
            }
            Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                await UIHandleIncomingMessage(message);
            }).AsTask().Wait();
        }
Esempio n. 16
0
        private void HandleGroupUpdateMessage(SignalServiceEnvelope envelope, SignalServiceContent content, SignalServiceDataMessage dataMessage, bool isSync, long timestamp)
        {
            if (dataMessage.Group != null) //TODO check signal droid: group messages have different types!
            {
                SignalServiceGroup group       = dataMessage.Group;
                string             groupid     = Base64.encodeBytes(group.GroupId);
                SignalGroup        g           = new SignalGroup();
                string             displayname = "Unknown group";
                string             avatarfile  = null;
                if (group.Name != null)
                {
                    displayname = group.Name;
                }
                var dbgroup = SignalDBContext.InsertOrUpdateGroupLocked(groupid, displayname, avatarfile, true, timestamp, this);
                if (group.Members != null)
                {
                    foreach (var member in group.Members)
                    {
                        SignalDBContext.InsertOrUpdateGroupMembershipLocked(dbgroup.Id, SignalDBContext.GetOrCreateContactLocked(member, 0, this).Id);
                    }
                }

                /* insert message into conversation */
                SignalMessageDirection type;
                SignalContact          author;
                SignalMessageStatus    status;
                string prefix;
                long   composedTimestamp;

                if (isSync)
                {
                    var sent = content.SynchronizeMessage.getSent().ForceGetValue();
                    type              = SignalMessageDirection.Synced;
                    status            = SignalMessageStatus.Confirmed;
                    composedTimestamp = sent.getTimestamp();
                    author            = null;
                    prefix            = "You have";
                }
                else
                {
                    status            = 0;
                    type              = SignalMessageDirection.Incoming;
                    author            = SignalDBContext.GetOrCreateContactLocked(envelope.getSource(), timestamp, this);
                    prefix            = $"{author.ThreadDisplayName} has";
                    composedTimestamp = envelope.getTimestamp();
                }

                SignalMessage sm = new SignalMessage()
                {
                    Direction = type,
                    Type      = SignalMessageType.GroupUpdate,
                    Status    = status,
                    Author    = author,
                    Content   = new SignalMessageContent()
                    {
                        Content = $"{prefix} updated the group."
                    },
                    ThreadId          = groupid,
                    DeviceId          = (uint)envelope.getSourceDevice(),
                    Receipts          = 0,
                    ComposedTimestamp = composedTimestamp,
                    ReceivedTimestamp = timestamp,
                };
                Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
                {
                    await UIHandleIncomingMessage(sm);
                }).AsTask().Wait();
            }
            else
            {
                Debug.WriteLine("received group update without group info!");
            }
        }
Esempio n. 17
0
        private void HandleGroupUpdateMessage(SignalServiceEnvelope envelope, SignalServiceContent content, SignalServiceDataMessage dataMessage, bool isSync, long timestamp)
        {
            if (dataMessage.Group != null) //TODO check signal droid: group messages have different types!
            {
                SignalServiceGroup group       = dataMessage.Group;
                string             groupid     = Base64.encodeBytes(group.GroupId);
                SignalGroup        g           = new SignalGroup();
                string             displayname = "Unknown group";
                string             avatarfile  = null;
                if (group.Name != null)
                {
                    displayname = group.Name;
                }
                var dbgroup = SignalDBContext.InsertOrUpdateGroupLocked(groupid, displayname, avatarfile, true, timestamp);
                if (group.Members != null)
                {
                    foreach (var member in group.Members)
                    {
                        SignalDBContext.InsertOrUpdateGroupMembershipLocked(dbgroup.Id, SignalDBContext.GetOrCreateContactLocked(member, 0).Id);
                    }
                }

                /* insert message into conversation */
                SignalMessageDirection type;
                SignalContact          author;
                SignalMessageStatus    status;
                string prefix;
                long   composedTimestamp;

                if (isSync)
                {
                    var sent = content.SynchronizeMessage.getSent().ForceGetValue();
                    type              = SignalMessageDirection.Synced;
                    status            = SignalMessageStatus.Confirmed;
                    composedTimestamp = sent.getTimestamp();
                    author            = null;
                    prefix            = "You have";
                }
                else
                {
                    status            = 0;
                    type              = SignalMessageDirection.Incoming;
                    author            = SignalDBContext.GetOrCreateContactLocked(envelope.getSource(), timestamp);
                    prefix            = $"{author.ThreadDisplayName} has";
                    composedTimestamp = envelope.getTimestamp();
                }

                SignalMessage sm = new SignalMessage()
                {
                    Direction = type,
                    Type      = SignalMessageType.GroupUpdate,
                    Status    = status,
                    Author    = author,
                    Content   = new SignalMessageContent()
                    {
                        Content = $"{prefix} updated the group."
                    },
                    ThreadId          = groupid,
                    DeviceId          = (uint)envelope.getSourceDevice(),
                    Receipts          = 0,
                    ComposedTimestamp = composedTimestamp,
                    ReceivedTimestamp = timestamp,
                };
                SignalDBContext.SaveMessageLocked(sm);
                dbgroup.MessagesCount += 1;
                if (sm.Direction == SignalMessageDirection.Incoming)
                {
                    dbgroup.UnreadCount += 1;
                }
                else
                {
                    dbgroup.UnreadCount          = 0;
                    dbgroup.LastSeenMessageIndex = dbgroup.MessagesCount;
                }
                dbgroup.LastMessage = sm;
                SignalLibHandle.Instance.DispatchAddOrUpdateConversation(dbgroup, sm);
            }
            else
            {
                Logger.LogError("HandleGroupUpdateMessage() received group update without group info");
            }
        }
        /// <summary>
        /// Decrypt a received <see cref="SignalServiceEnvelope"/>
        /// </summary>
        /// <param name="envelope">The received SignalServiceEnvelope</param>
        /// <returns>a decrypted SignalServiceContent</returns>
        public SignalServiceContent decrypt(SignalServiceEnvelope envelope)
        {
            try
            {
                SignalServiceContent content = new SignalServiceContent();

                if (envelope.hasLegacyMessage())
                {
                    DataMessage message = DataMessage.Parser.ParseFrom(decrypt(envelope, envelope.getLegacyMessage()));
                    content = new SignalServiceContent()
                    {
                        Message = createSignalServiceMessage(envelope, message)
                    };
                }
                else if (envelope.hasContent())
                {
                    Content message = Content.Parser.ParseFrom(decrypt(envelope, envelope.getContent()));

                    if (message.DataMessageOneofCase == Content.DataMessageOneofOneofCase.DataMessage)
                    {
                        content = new SignalServiceContent()
                        {
                            Message = createSignalServiceMessage(envelope, message.DataMessage)
                        };
                    }
                    else if (message.SyncMessageOneofCase == Content.SyncMessageOneofOneofCase.SyncMessage && localAddress.getNumber().Equals(envelope.getSource()))
                    {
                        content = new SignalServiceContent()
                        {
                            SynchronizeMessage = createSynchronizeMessage(envelope, message.SyncMessage)
                        };
                    }
                    else if (message.CallMessageOneofCase == Content.CallMessageOneofOneofCase.CallMessage)
                    {
                        content = new SignalServiceContent()
                        {
                            CallMessage = createCallMessage(message.CallMessage)
                        };
                    }
                }

                return(content);
            }
            catch (InvalidProtocolBufferException e)
            {
                throw new InvalidMessageException(e);
            }
        }
Esempio n. 19
0
        private void HandleSignalMessage(SignalServiceEnvelope envelope, SignalServiceContent content, SignalServiceDataMessage dataMessage, bool isSync, long timestamp)
        {
            SignalMessageDirection type;
            SignalContact          author;
            SignalMessageStatus    status;
            SignalConversation     conversation;
            long   composedTimestamp;
            string body = dataMessage.Body ?? "";

            if (dataMessage.Group != null)
            {
                var rawId    = dataMessage.Group.GroupId;
                var threadId = Base64.encodeBytes(rawId);
                conversation = SignalDBContext.GetOrCreateGroupLocked(threadId, timestamp);
                if (!conversation.CanReceive)
                {
                    SignalServiceGroup group = new SignalServiceGroup()
                    {
                        Type    = SignalServiceGroup.GroupType.REQUEST_INFO,
                        GroupId = rawId
                    };
                    SignalServiceDataMessage requestInfoMessage = new SignalServiceDataMessage()
                    {
                        Group     = group,
                        Timestamp = Util.CurrentTimeMillis()
                    };
                    //MessageSender.sendMessage(envelope.getSourceAddress(), requestInfoMessage); TODO
                }
                composedTimestamp = envelope.getTimestamp();
            }
            else
            {
                if (isSync)
                {
                    var sent = content.SynchronizeMessage.getSent().ForceGetValue();
                    conversation      = SignalDBContext.GetOrCreateContactLocked(sent.getDestination().ForceGetValue(), timestamp);
                    composedTimestamp = sent.getTimestamp();
                }
                else
                {
                    conversation      = SignalDBContext.GetOrCreateContactLocked(envelope.getSource(), timestamp);
                    composedTimestamp = envelope.getTimestamp();
                }
            }

            if (isSync)
            {
                type   = SignalMessageDirection.Synced;
                status = SignalMessageStatus.Confirmed;
                author = null;
            }
            else
            {
                status = 0;
                type   = SignalMessageDirection.Incoming;
                author = SignalDBContext.GetOrCreateContactLocked(envelope.getSource(), timestamp);
            }

            List <SignalAttachment> attachments = new List <SignalAttachment>();
            SignalMessage           message     = new SignalMessage()
            {
                Direction = type,
                Status    = status,
                Author    = author,
                Content   = new SignalMessageContent()
                {
                    Content = body
                },
                ThreadId          = conversation.ThreadId,
                DeviceId          = (uint)envelope.getSourceDevice(),
                Receipts          = 0,
                ComposedTimestamp = composedTimestamp,
                ReceivedTimestamp = timestamp,
                AttachmentsCount  = (uint)attachments.Count,
                Attachments       = attachments
            };

            if (dataMessage.Attachments != null)
            {
                var receivedAttachments = dataMessage.Attachments;
                foreach (var receivedAttachment in receivedAttachments)
                {
                    var pointer         = receivedAttachment.asPointer();
                    SignalAttachment sa = new SignalAttachment()
                    {
                        Message      = message,
                        Status       = (uint)SignalAttachmentStatus.Default,
                        SentFileName = pointer.FileName,
                        ContentType  = "",
                        Key          = pointer.Key,
                        Relay        = pointer.Relay,
                        StorageId    = pointer.Id
                    };
                    attachments.Add(sa);
                }
            }
            SignalLibHandle.Instance.SaveAndDispatchSignalMessage(message, conversation);
        }
Esempio n. 20
0
 private void handleReceipt(SignalServiceEnvelope envelope)
 {
     Log.Debug($"Received receipt: (XXXXX, {envelope.getTimestamp()})");
     DatabaseFactory.getMessageDatabase().incrementDeliveryReceiptCount(envelope.getSource(),
                                                                        (long)envelope.getTimestamp());
 }
Esempio n. 21
0
        private void HandleExpirationUpdateMessage(SignalServiceEnvelope envelope, SignalServiceContent content, SignalServiceDataMessage message, bool isSync, long timestamp)
        {
            SignalMessageDirection type;
            SignalContact          author;
            SignalMessageStatus    status;
            string             prefix;
            SignalConversation conversation;
            long composedTimestamp;

            if (isSync)
            {
                var sent = content.SynchronizeMessage.getSent().ForceGetValue();
                type              = SignalMessageDirection.Synced;
                status            = SignalMessageStatus.Confirmed;
                composedTimestamp = sent.getTimestamp();
                author            = null;
                prefix            = "You have";
                if (message.Group != null)
                {
                    conversation = SignalDBContext.GetOrCreateGroupLocked(Base64.encodeBytes(message.Group.GroupId), 0);
                }
                else
                {
                    conversation = SignalDBContext.GetOrCreateContactLocked(sent.getDestination().ForceGetValue(), 0);
                }
            }
            else
            {
                status            = 0;
                type              = SignalMessageDirection.Incoming;
                author            = SignalDBContext.GetOrCreateContactLocked(envelope.getSource(), timestamp);
                prefix            = $"{author.ThreadDisplayName} has";
                composedTimestamp = envelope.getTimestamp();
                if (message.Group != null)
                {
                    conversation = SignalDBContext.GetOrCreateGroupLocked(Base64.encodeBytes(message.Group.GroupId), 0);
                }
                else
                {
                    conversation = SignalDBContext.GetOrCreateContactLocked(envelope.getSource(), 0);
                }
            }
            SignalDBContext.UpdateExpiresInLocked(conversation, (uint)message.ExpiresInSeconds);
            SignalMessage sm = new SignalMessage()
            {
                Direction = type,
                Type      = SignalMessageType.ExpireUpdate,
                Status    = status,
                Author    = author,
                Content   = new SignalMessageContent()
                {
                    Content = $"{prefix} set the expiration timer to {message.ExpiresInSeconds} seconds."
                },
                ThreadId          = conversation.ThreadId,
                DeviceId          = (uint)envelope.getSourceDevice(),
                Receipts          = 0,
                ComposedTimestamp = composedTimestamp,
                ReceivedTimestamp = timestamp,
            };

            SignalLibHandle.Instance.SaveAndDispatchSignalMessage(sm, conversation);
        }