public void onAcceptFile(FriendMessage message)
        {
            if (TransferManager.getIncomingTransfer(message.transferId) != null)
            {
                Logging.warn("Incoming file transfer {0} already prepared.", message.transferId);
                return;
            }

            //displaySpixiAlert("File", uid, "Ok");
            string file_name = System.IO.Path.GetFileName(message.filePath);

            var ft = new FileTransfer();

            ft.fileName = file_name;
            ft.fileSize = message.fileSize;
            ft.uid      = message.transferId;

            ft = TransferManager.prepareIncomingFileTransfer(ft.getBytes(), friend.walletAddress);

            if (ft != null)
            {
                TransferManager.acceptFile(friend, ft.uid);
                updateFile(ft.uid, "0", false);
            }
        }
Beispiel #2
0
        public bool setMessageReceived(byte[] id)
        {
            FriendMessage msg = messages.Find(x => x.id.SequenceEqual(id));

            if (msg == null)
            {
                Logging.error("Error trying to set received indicator, message does not exist");
                return(false);
            }

            if (msg.localSender)
            {
                if (!msg.confirmed)
                {
                    msg.confirmed = true;
                    Node.localStorage.writeMessages(walletAddress, messages);
                }

                if (chat_page != null)
                {
                    chat_page.updateMessage(msg);
                }
            }

            return(true);
        }
Beispiel #3
0
        private void onRequest(string recipient, string amount)
        {
            byte[] recipient_bytes = Base58Check.Base58CheckEncoding.DecodePlain(recipient);
            Friend friend          = FriendList.getFriend(recipient_bytes);

            if (friend != null && (new IxiNumber(amount)) > 0)
            {
                FriendMessage friend_message = FriendList.addMessageWithType(null, FriendMessageType.requestFunds, friend.walletAddress, amount, true);

                SpixiMessage spixi_message = new SpixiMessage(SpixiMessageCode.requestFunds, Encoding.UTF8.GetBytes(amount));

                StreamMessage message = new StreamMessage();
                message.type        = StreamMessageCode.info;
                message.recipient   = Base58Check.Base58CheckEncoding.DecodePlain(recipient);
                message.sender      = Node.walletStorage.getPrimaryAddress();
                message.transaction = new byte[1];
                message.sigdata     = new byte[1];
                message.data        = spixi_message.getBytes();
                message.id          = friend_message.id;

                StreamProcessor.sendMessage(friend, message);

                Navigation.PopAsync(Config.defaultXamarinAnimations);
            }// else error?
        }
Beispiel #4
0
        public bool setMessageRead(int channel, byte[] id)
        {
            var tmp_messages = getMessages(channel);

            if (tmp_messages == null)
            {
                return(false);
            }

            FriendMessage msg = tmp_messages.Find(x => x.id.SequenceEqual(id));

            if (msg == null)
            {
                Logging.error("Error trying to set read indicator, message does not exist");
                return(false);
            }

            if (msg.localSender)
            {
                if (!msg.read)
                {
                    msg.read = true;
                    Node.localStorage.requestWriteMessages(walletAddress, channel);
                }

                if (chat_page != null)
                {
                    chat_page.updateMessage(msg);
                }
            }

            return(true);
        }
Beispiel #5
0
        public FriendMetaData(byte[] bytes)
        {
            using (MemoryStream m = new MemoryStream(bytes))
            {
                using (BinaryReader reader = new BinaryReader(m))
                {
                    int version = reader.ReadInt32();

                    int bot_info_len = reader.ReadInt32();
                    if (bot_info_len > 0)
                    {
                        botInfo = new BotInfo(reader.ReadBytes(bot_info_len));
                    }

                    int msg_count = reader.ReadInt32();
                    for (int i = 0; i < msg_count; i++)
                    {
                        int channel = reader.ReadInt32();
                        int msg_len = reader.ReadInt32();
                        lastReceivedMessageIds.Add(channel, reader.ReadBytes(msg_len));
                    }

                    int last_message_len = reader.ReadInt32();
                    if (last_message_len > 0)
                    {
                        lastMessage = new FriendMessage(reader.ReadBytes(last_message_len));
                    }

                    lastMessageChannel = reader.ReadInt32();

                    unreadMessageCount = reader.ReadInt32();
                }
            }
        }
Beispiel #6
0
        public static void addMessageWithType(FriendMessageType type, byte[] wallet_address, string message)
        {
            foreach (Friend friend in friends)
            {
                if (friend.walletAddress.SequenceEqual(wallet_address))
                {
                    DateTime dt = DateTime.Now;
                    // TODO: message date should be fetched, not generated here
                    FriendMessage friend_message = new FriendMessage(message, String.Format("{0:t}", dt), true, type);
                    friend.messages.Add(friend_message);

                    // If a chat page is visible, insert the message directly
                    if (friend.chat_page != null)
                    {
                        friend.chat_page.insertMessage(friend_message);
                    }
                    else
                    {
                        //CrossLocalNotifications.Current.Show(string.Format("New message from {0}",friend.nickname), message, 100, DateTime.Now.AddSeconds(1));
                    }

                    // Write to chat history
                    Node.localStorage.writeMessagesFile(wallet_address, friend.messages);

                    return;
                }
            }

            // No matching contact found in friendlist
            // Add the contact, then issue the message again
            // TODO: need to fetch the stage 1 public key somehow here
            // Ignoring such messages for now
            //addFriend(wallet_address, "pubkey", "Unknown");
            //addMessage(wallet_address, message);
        }
Beispiel #7
0
        public bool setMessageSent(int channel, byte[] id)
        {
            var tmp_messages = getMessages(channel);

            if (tmp_messages == null)
            {
                return(false);
            }
            FriendMessage msg = tmp_messages.Find(x => x.id.SequenceEqual(id));

            if (msg == null)
            {
                Logging.error("Error trying to set sent indicator, message from {0} for channel {1} does not exist", Base58Check.Base58CheckEncoding.EncodePlain(walletAddress), channel.ToString());
                return(false);
            }

            if (msg.localSender)
            {
                if (!msg.sent)
                {
                    msg.sent = true;
                    Node.localStorage.requestWriteMessages(walletAddress, channel);
                }

                if (chat_page != null)
                {
                    chat_page.updateMessage(msg);
                }
            }

            return(true);
        }
        public void onConfirmPaymentRequest(FriendMessage msg, string amount)
        {
            // TODO: extract the date from the corresponding message
            DateTime dt        = DateTime.Now;
            string   date_text = String.Format("{0:t}", dt);

            Navigation.PushAsync(new WalletContactRequestPage(msg, friend, amount, date_text), Config.defaultXamarinAnimations);
        }
Beispiel #9
0
        // Set last message as read
        public void setLastRead()
        {
            if (messages.Count < 1)
            {
                return;
            }
            FriendMessage last_message = messages[messages.Count - 1];

            last_message.read = true;
        }
Beispiel #10
0
        // Set last message as read
        public void setLastRead()
        {
            if (messages.Count < 1)
            {
                return;
            }
            FriendMessage last_message = messages[messages.Count - 1];

            if (!last_message.localSender)
            {
                last_message.read = true;
            }
        }
Beispiel #11
0
        private void sendPayment(string txfee)
        {
            Logging.info("Preparing to send payment");
            //Navigation.PopAsync(Config.defaultXamarinAnimations);

            // Create an ixian transaction and send it to the dlt network
            IxiNumber fee = ConsensusConfig.transactionPrice;

            byte[] from   = Node.walletStorage.getPrimaryAddress();
            byte[] pubKey = Node.walletStorage.getPrimaryPublicKey();
            Logging.info("Preparing tx");

            Transaction transaction = new Transaction((int)Transaction.Type.Normal, fee, to_list, from, null, pubKey, IxianHandler.getHighestKnownNetworkBlockHeight());

            Logging.info("Broadcasting tx");

            IxianHandler.addTransaction(transaction);
            Logging.info("Adding to cache");

            // Add the unconfirmed transaction to the cache
            TransactionCache.addUnconfirmedTransaction(transaction);
            Logging.info("Showing payment details");

            // Send message to recipients
            foreach (var entry in to_list)
            {
                Friend friend = FriendList.getFriend(entry.Key);

                if (friend != null)
                {
                    FriendMessage friend_message = FriendList.addMessageWithType(null, FriendMessageType.sentFunds, entry.Key, transaction.id, true);

                    SpixiMessage spixi_message = new SpixiMessage(SpixiMessageCode.sentFunds, Encoding.UTF8.GetBytes(transaction.id));

                    StreamMessage message = new StreamMessage();
                    message.type        = StreamMessageCode.info;
                    message.recipient   = friend.walletAddress;
                    message.sender      = Node.walletStorage.getPrimaryAddress();
                    message.transaction = new byte[1];
                    message.sigdata     = new byte[1];
                    message.data        = spixi_message.getBytes();
                    message.id          = friend_message.id;

                    StreamProcessor.sendMessage(friend, message);
                }
            }

            // Show the payment details
            Navigation.PushAsync(new WalletSentPage(transaction, false), Config.defaultXamarinAnimations);
        }
Beispiel #12
0
        public static FriendMessage addMessageWithType(byte[] id, FriendMessageType type, byte[] wallet_address, string message, bool local_sender = false)
        {
            foreach (Friend friend in friends)
            {
                if (friend.walletAddress.SequenceEqual(wallet_address))
                {
                    Node.shouldRefreshContacts = true;

                    if (!friend.online)
                    {
                        using (MemoryStream mw = new MemoryStream())
                        {
                            using (BinaryWriter writer = new BinaryWriter(mw))
                            {
                                writer.Write(wallet_address.Length);
                                writer.Write(wallet_address);

                                CoreProtocolMessage.broadcastProtocolMessage(new char[] { 'M' }, ProtocolMessageCode.getPresence, mw.ToArray(), null);
                            }
                        }
                    }
                    // TODO: message date should be fetched, not generated here
                    FriendMessage friend_message = new FriendMessage(id, message, Clock.getTimestamp(), local_sender, type);
                    friend.messages.Add(friend_message);

                    // If a chat page is visible, insert the message directly
                    if (friend.chat_page != null)
                    {
                        friend.chat_page.insertMessage(friend_message);
                    }
                    else
                    {
                        //CrossLocalNotifications.Current.Show(string.Format("New message from {0}",friend.nickname), message, 100, DateTime.Now.AddSeconds(1));
                    }

                    // Write to chat history
                    Node.localStorage.writeMessagesFile(wallet_address, friend.messages);

                    return(friend_message);
                }
            }

            // No matching contact found in friendlist
            // Add the contact, then issue the message again
            // TODO: need to fetch the stage 1 public key somehow here
            // Ignoring such messages for now
            //addFriend(wallet_address, "pubkey", "Unknown");
            //addMessage(wallet_address, message);
            return(null);
        }
        public void onViewPayment(string msg_id)
        {
            FriendMessage msg = friend.messages.Find(x => x.id.SequenceEqual(Crypto.stringToHash(msg_id)));

            if (msg.type == FriendMessageType.sentFunds || msg.message.StartsWith(":"))
            {
                string id = msg.message;
                if (id.StartsWith(":"))
                {
                    id = id.Substring(1);
                }

                Transaction transaction = null;
                foreach (Transaction tx in TransactionCache.transactions)
                {
                    if (tx.id.Equals(id, StringComparison.Ordinal))
                    {
                        transaction = tx;
                        break;
                    }
                }

                if (transaction == null)
                {
                    foreach (Transaction tx in TransactionCache.unconfirmedTransactions)
                    {
                        if (tx.id.Equals(id, StringComparison.Ordinal))
                        {
                            transaction = tx;
                            break;
                        }
                    }

                    if (transaction == null)
                    {
                        return;
                    }
                }

                Navigation.PushAsync(new WalletSentPage(transaction), Config.defaultXamarinAnimations);

                return;
            }

            if (msg.type == FriendMessageType.requestFunds && !msg.localSender)
            {
                onConfirmPaymentRequest(msg, msg.message);
            }
        }
Beispiel #14
0
        // Check if the last message is unread. Returns true if it is unread.
        public bool checkLastUnread()
        {
            if (messages.Count < 1)
            {
                return(false);
            }
            FriendMessage last_message = messages[messages.Count - 1];

            if (last_message.read == false)
            {
                return(true);
            }

            return(false);
        }
        public WalletContactRequestPage(FriendMessage request_msg, Friend fr, string am, string dt)
        {
            InitializeComponent();
            NavigationPage.SetHasNavigationBar(this, false);

            friend = fr;
            amount = am;
            date   = dt;
            if (request_msg != null)
            {
                requestMsg = request_msg;
            }

            loadPage(webView, "wallet_contact_request.html");
        }
        public async System.Threading.Tasks.Task onSendFile()
        {
            try
            {
                FileData fileData = await CrossFilePicker.Current.PickFile();

                if (fileData == null)
                {
                    return; // User canceled file picking
                }
                string fileName = fileData.FileName;
                string filePath = fileData.FilePath;

                FileTransfer transfer = TransferManager.prepareFileTransfer(fileName, fileData.GetStream(), filePath);
                Logging.info("File Transfer uid: " + transfer.uid);

                SpixiMessage spixi_message = new SpixiMessage(SpixiMessageCode.fileHeader, transfer.getBytes());

                StreamMessage message = new StreamMessage();
                message.type        = StreamMessageCode.data;
                message.recipient   = friend.walletAddress;
                message.sender      = Node.walletStorage.getPrimaryAddress();
                message.transaction = new byte[1];
                message.sigdata     = new byte[1];
                message.data        = spixi_message.getBytes();

                StreamProcessor.sendMessage(friend, message);


                string message_data = string.Format("{0}:{1}", transfer.uid, transfer.fileName);

                // store the message and display it
                FriendMessage friend_message = FriendList.addMessageWithType(message.id, FriendMessageType.fileHeader, friend.walletAddress, message_data, true);

                friend_message.transferId = transfer.uid;
                friend_message.filePath   = transfer.filePath;

                Node.localStorage.writeMessages(friend.walletAddress, friend.messages);
            }
            catch (Exception ex)
            {
                Logging.error("Exception choosing file: " + ex.ToString());
            }
        }
Beispiel #17
0
        public WalletContactRequestPage(FriendMessage request_msg, Friend fr, string am, string dt)
        {
            InitializeComponent();
            NavigationPage.SetHasNavigationBar(this, false);

            friend = fr;
            amount = am;
            date   = dt;
            if (request_msg != null)
            {
                requestMsg = request_msg;
            }

            // Load the platform specific home page url
            var source = new UrlWebViewSource();

            source.Url     = string.Format("{0}html/wallet_contact_request.html", DependencyService.Get <IBaseUrl>().Get());
            webView.Source = source;
        }
Beispiel #18
0
        public static void handleRequestFundsResponse(byte[] id, byte[] sender_wallet, string msg_id_tx_id)
        {
            // Retrieve the corresponding contact
            Friend friend = FriendList.getFriend(sender_wallet);

            if (friend == null)
            {
                return;
            }

            string[] msg_id_tx_id_split = msg_id_tx_id.Split(':');
            byte[]   msg_id             = null;
            string   tx_id = null;

            if (msg_id_tx_id_split.Length == 2)
            {
                msg_id = Crypto.stringToHash(msg_id_tx_id_split[0]);
                tx_id  = msg_id_tx_id_split[1];
            }
            else
            {
                msg_id = Crypto.stringToHash(msg_id_tx_id);
            }

            FriendMessage msg = friend.messages.Find(x => x.id.SequenceEqual(msg_id));

            if (msg == null)
            {
                return;
            }
            if (tx_id != null)
            {
                msg.message = ":" + tx_id;
            }
            else
            {
                msg.message = "::" + msg.message; // declined
            }

            // Write to chat history
            Node.localStorage.writeMessagesFile(friend.walletAddress, friend.messages);
        }
Beispiel #19
0
        private void sendPayment(string txfee)
        {
            Logging.info("Preparing to send payment");
            //Navigation.PopAsync(Config.defaultXamarinAnimations);

            Logging.info("Broadcasting tx");

            IxianHandler.addTransaction(transaction);
            Logging.info("Adding to cache");

            // Add the unconfirmed transaction to the cache
            TransactionCache.addUnconfirmedTransaction(transaction);
            Logging.info("Showing payment details");

            // Send message to recipients
            foreach (var entry in to_list)
            {
                Friend friend = FriendList.getFriend(entry.Key);

                if (friend != null)
                {
                    FriendMessage friend_message = FriendList.addMessageWithType(null, FriendMessageType.sentFunds, entry.Key, transaction.id, true);

                    SpixiMessage spixi_message = new SpixiMessage(SpixiMessageCode.sentFunds, Encoding.UTF8.GetBytes(transaction.id));

                    StreamMessage message = new StreamMessage();
                    message.type        = StreamMessageCode.info;
                    message.recipient   = friend.walletAddress;
                    message.sender      = Node.walletStorage.getPrimaryAddress();
                    message.transaction = new byte[1];
                    message.sigdata     = new byte[1];
                    message.data        = spixi_message.getBytes();
                    message.id          = friend_message.id;

                    StreamProcessor.sendMessage(friend, message);
                }
            }

            // Show the payment details
            Navigation.PushAsync(new WalletSentPage(transaction, false), Config.defaultXamarinAnimations);
        }
        public void updateMessagesReadStatus()
        {
            if (friend == null)
            {
                return;
            }
            lock (friend.messages)
            {
                int max_msg_count = 0;
                if (friend.messages.Count > 50)
                {
                    max_msg_count = friend.messages.Count - 50;
                }

                for (int i = friend.messages.Count - 1; i >= max_msg_count; i--)
                {
                    FriendMessage msg = friend.messages[i];
                    updateMessageReadStatus(msg);
                }
            }
        }
Beispiel #21
0
 public bool addReaction(byte[] sender_address, SpixiMessageReaction reaction_data, int channel)
 {
     if (!reaction_data.reaction.StartsWith("tip:") && !reaction_data.reaction.StartsWith("like:"))
     {
         Logging.warn("Invalid reaction data: " + reaction_data.reaction);
         return(false);
     }
     if (reaction_data.reaction.Length > 128)
     {
         Logging.warn("Invalid reaction data length: " + reaction_data.reaction);
         return(false);
     }
     lock (messages)
     {
         var tmp_messages = getMessages(channel);
         if (tmp_messages == null)
         {
             return(false);
         }
         FriendMessage fm = tmp_messages.Find(x => x.id.SequenceEqual(reaction_data.msgId));
         if (fm != null)
         {
             if (fm.reactions.Count >= 10)
             {
                 Logging.warn("Too many reactions on message " + Crypto.hashToString(reaction_data.msgId));
                 return(false);
             }
             if (fm.addReaction(sender_address, reaction_data.reaction))
             {
                 Node.localStorage.requestWriteMessages(walletAddress, channel);
                 if (chat_page != null)
                 {
                     chat_page.updateReactions(fm.id, channel);
                 }
                 return(true);
             }
         }
     }
     return(false);
 }
Beispiel #22
0
 public bool deleteMessage(byte[] msg_id, int channel)
 {
     lock (messages)
     {
         var tmp_messages = getMessages(channel);
         if (tmp_messages == null)
         {
             return(false);
         }
         FriendMessage fm = tmp_messages.Find(x => x.id.SequenceEqual(msg_id));
         if (fm != null)
         {
             tmp_messages.Remove(fm);
             Node.localStorage.requestWriteMessages(walletAddress, channel);
             if (chat_page != null)
             {
                 chat_page.deleteMessage(msg_id, channel);
             }
             return(true);
         }
     }
     return(false);
 }
Beispiel #23
0
        public static void completeFileTransfer(byte[] sender, string uid)
        {
            Friend friend = FriendList.getFriend(sender);

            if (friend == null)
            {
                return;
            }

            FileTransfer transfer = TransferManager.getIncomingTransfer(uid);

            if (transfer == null)
            {
                transfer = TransferManager.getOutgoingTransfer(uid);
                if (transfer == null)
                {
                    return;
                }
            }

            transfer.fileStream.Dispose();
            transfer.completed = true;

            removePacketsForFileTransfer(uid);

            FriendMessage fm = friend.messages.Find(x => x.transferId == uid);

            fm.completed = true;
            fm.filePath  = transfer.filePath;

            Node.localStorage.writeMessages(friend.walletAddress, friend.messages);

            if (friend.chat_page != null)
            {
                friend.chat_page.updateFile(uid, "100", true);
            }
        }
        private void updateMessageReadStatus(FriendMessage message)
        {
            if (!message.read && !message.localSender && App.isInForeground)
            {
                Node.shouldRefreshContacts = true;

                message.read = true;
                Node.localStorage.writeMessages(friend.walletAddress, friend.messages);

                if (!friend.bot)
                {
                    // Send read confirmation
                    StreamMessage msg_received = new StreamMessage();
                    msg_received.type        = StreamMessageCode.info;
                    msg_received.sender      = IxianHandler.getWalletStorage().getPrimaryAddress();
                    msg_received.recipient   = friend.walletAddress;
                    msg_received.data        = new SpixiMessage(SpixiMessageCode.msgRead, message.id).getBytes();
                    msg_received.transaction = new byte[1];
                    msg_received.sigdata     = new byte[1];

                    StreamProcessor.sendMessage(friend, msg_received, true, false, false);
                }
            }
        }
        private void onNavigating(object sender, WebNavigatingEventArgs e)
        {
            string current_url = HttpUtility.UrlDecode(e.Url);

            e.Cancel = true;

            if (current_url.Equals("ixian:onload", StringComparison.Ordinal))
            {
                onLoad();
            }
            else if (current_url.Equals("ixian:back", StringComparison.Ordinal))
            {
                friend.chat_page = null;

                Navigation.PopAsync(Config.defaultXamarinAnimations);
            }
            else if (current_url.Equals("ixian:request", StringComparison.Ordinal))
            {
                Navigation.PushAsync(new WalletReceivePage(friend), Config.defaultXamarinAnimations);
            }
            else if (current_url.Equals("ixian:details", StringComparison.Ordinal))
            {
                Navigation.PushAsync(new ContactDetails(friend, true), Config.defaultXamarinAnimations);
            }
            else if (current_url.Equals("ixian:send", StringComparison.Ordinal))
            {
                Navigation.PushAsync(new WalletSendPage(friend.walletAddress), Config.defaultXamarinAnimations);
            }
            else if (current_url.Equals("ixian:accept", StringComparison.Ordinal))
            {
                onAcceptFriendRequest();
            }
            else if (current_url.Equals("ixian:call", StringComparison.Ordinal))
            {
                displaySpixiAlert("Voice Call", "Coming soon.\nCheck regularly for new version on www.spixi.io", "Ok");
            }
            else if (current_url.Equals("ixian:sendfile", StringComparison.Ordinal))
            {
                onSendFile();
            }
            else if (current_url.Contains("ixian:acceptfile:"))
            {
                string[] split = current_url.Split(new string[] { "ixian:acceptfile:" }, StringSplitOptions.None);
                string   id    = split[1];

                FriendMessage fm = friend.messages.Find(x => x.transferId == id);
                if (fm != null)
                {
                    onAcceptFile(fm);
                }
                else
                {
                    Logging.error("Cannot find message with transfer id: {0}", id);
                }
            }
            else if (current_url.Contains("ixian:openfile:"))
            {
                string[] split = current_url.Split(new string[] { "ixian:openfile:" }, StringSplitOptions.None);
                string   id    = split[1];

                FriendMessage fm = friend.messages.Find(x => x.transferId == id);

                // Open file in default app. May not work, check https://forums.xamarin.com/discussion/103042/how-to-open-pdf-or-txt-file-in-default-app-on-xamarin-forms
                //Device.OpenUri(new Uri(transfer.filePath));
                DependencyService.Get <IFileOperations>().open(fm.filePath);
            }
            else if (current_url.Contains("ixian:chat:"))
            {
                string[] split = current_url.Split(new string[] { "ixian:chat:" }, StringSplitOptions.None);
                string   msg   = split[1];

                /*if(msg == "/draw") // TODO TODO TODO experimental test
                 * {
                 *  byte[][] user_addresses = new byte[][] { friend.walletAddress };
                 *  CustomAppPage custom_app_page = new CustomAppPage(IxianHandler.getWalletStorage().getPrimaryAddress(), user_addresses, "custom_app.html");
                 *  Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
                 *  {
                 *      Navigation.PushAsync(custom_app_page, Config.defaultXamarinAnimations);
                 *  });
                 *
                 *  SpixiMessage spixi_msg = new SpixiMessage();
                 *  spixi_msg.type = SpixiMessageCode.appRequest;
                 *  spixi_msg.data = (new SpixiAppData(custom_app_page.sessionId, null)).getBytes();
                 *
                 *  StreamMessage new_msg = new StreamMessage();
                 *  new_msg.type = StreamMessageCode.data;
                 *  new_msg.recipient = friend.walletAddress;
                 *  new_msg.sender = Node.walletStorage.getPrimaryAddress();
                 *  new_msg.transaction = new byte[1];
                 *  new_msg.sigdata = new byte[1];
                 *  new_msg.data = spixi_msg.getBytes();
                 *  new_msg.encryptionType = StreamMessageEncryptionCode.none;
                 *
                 *  StreamProcessor.sendMessage(friend, new_msg);
                 *
                 *  return;
                 * }*/
                onSend(msg);
            }
            else if (current_url.Contains("ixian:viewPayment:"))
            {
                string[] split = current_url.Split(new string[] { "ixian:viewPayment:" }, StringSplitOptions.None);
                string   id    = split[1];
                onViewPayment(id);
            }
            else
            {
                // Otherwise it's just normal navigation
                e.Cancel = false;
                return;
            }
            e.Cancel = true;
        }
        public void insertMessage(FriendMessage message)
        {
            if (friend.approved == false)
            {
                if (message.type == FriendMessageType.requestAdd)
                {
                    // Call webview methods on the main UI thread only
                    Utils.sendUiCommand(webView, "showContactRequest", "1");
                    message.read = true;
                    return;
                }
            }
            else
            {
                // Don't show if the friend is already approved
                if (message.type == FriendMessageType.requestAdd)
                {
                    return;
                }
            }

            string prefix  = "addMe";
            string avatar  = "";
            string address = "";
            string nick    = "";

            if (!message.localSender)
            {
                if (friend.bot)
                {
                    if (message.senderAddress != null)
                    {
                        address = Base58Check.Base58CheckEncoding.EncodePlain(message.senderAddress);
                    }

                    nick = message.senderNick;
                    if (nick == "")
                    {
                        if (message.senderAddress != null && friend.contacts.ContainsKey(message.senderAddress))
                        {
                            nick = friend.contacts[message.senderAddress].nick;
                        }
                    }

                    if (nick == "")
                    {
                        nick = address;
                    }
                }

                prefix = "addThem";
                if (message.senderAddress != null)
                {
                    avatar = Node.localStorage.getAvatarPath(Base58Check.Base58CheckEncoding.EncodePlain(message.senderAddress));
                }
                else
                {
                    avatar = Node.localStorage.getAvatarPath(Base58Check.Base58CheckEncoding.EncodePlain(friend.walletAddress));
                }
                if (avatar == null)
                {
                    avatar = "img/spixiavatar.png";
                }
            }

            if (message.type == FriendMessageType.requestFunds)
            {
                string status      = "WAITING CONFIRMATION";
                string status_icon = "fa-clock";

                string amount = message.message;

                string txid = "";

                bool enableView = false;

                if (!message.localSender)
                {
                    enableView = true;
                }

                if (message.message.StartsWith("::"))
                {
                    status      = "DECLINED";
                    status_icon = "fa-exclamation-circle";
                    amount      = message.message.Substring(2);
                    txid        = Crypto.hashToString(message.id);
                    enableView  = false;
                }
                else if (message.message.StartsWith(":"))
                {
                    status = "PENDING";
                    txid   = message.message.Substring(1);

                    bool        confirmed   = true;
                    Transaction transaction = TransactionCache.getTransaction(txid);
                    if (transaction == null)
                    {
                        transaction = TransactionCache.getUnconfirmedTransaction(txid);
                        confirmed   = false;
                    }

                    amount = "?";

                    if (transaction != null)
                    {
                        amount = transaction.amount.ToString();

                        if (confirmed)
                        {
                            status      = "CONFIRMED";
                            status_icon = "fa-check-circle";
                        }
                    }
                    else
                    {
                        // TODO think about how to make this more private
                        CoreProtocolMessage.broadcastGetTransaction(txid, 0, null);
                    }
                    enableView = true;
                }


                if (message.localSender)
                {
                    Utils.sendUiCommand(webView, "addPaymentRequest", Crypto.hashToString(message.id), txid, address, nick, avatar, "Payment request SENT", amount, status, status_icon, message.timestamp.ToString(), message.localSender.ToString(), message.confirmed.ToString(), message.read.ToString(), enableView.ToString());
                }
                else
                {
                    Utils.sendUiCommand(webView, "addPaymentRequest", Crypto.hashToString(message.id), txid, address, nick, avatar, "Payment request RECEIVED", amount, status, status_icon, message.timestamp.ToString(), "", message.confirmed.ToString(), message.read.ToString(), enableView.ToString());
                }
            }

            if (message.type == FriendMessageType.sentFunds)
            {
                bool        confirmed   = true;
                Transaction transaction = TransactionCache.getTransaction(message.message);
                if (transaction == null)
                {
                    transaction = TransactionCache.getUnconfirmedTransaction(message.message);
                    confirmed   = false;
                }

                string status      = "PENDING";
                string status_icon = "fa-clock";

                string amount = "?";

                if (transaction != null)
                {
                    if (confirmed)
                    {
                        status      = "CONFIRMED";
                        status_icon = "fa-check-circle";
                    }
                    if (message.localSender)
                    {
                        amount = transaction.amount.ToString();
                    }
                    else
                    {
                        amount = HomePage.calculateReceivedAmount(transaction).ToString();
                    }
                }
                else
                {
                    // TODO think about how to make this more private
                    CoreProtocolMessage.broadcastGetTransaction(message.message, 0, null);
                }

                // Call webview methods on the main UI thread only
                if (message.localSender)
                {
                    Utils.sendUiCommand(webView, "addPaymentRequest", Crypto.hashToString(message.id), message.message, address, nick, avatar, "Payment SENT", amount, status, status_icon, message.timestamp.ToString(), message.localSender.ToString(), message.confirmed.ToString(), message.read.ToString(), "True");
                }
                else
                {
                    Utils.sendUiCommand(webView, "addPaymentRequest", Crypto.hashToString(message.id), message.message, address, nick, avatar, "Payment RECEIVED", amount, status, status_icon, message.timestamp.ToString(), "", message.confirmed.ToString(), message.read.ToString(), "True");
                }
            }


            if (message.type == FriendMessageType.fileHeader)
            {
                string[] split = message.message.Split(new string[] { ":" }, StringSplitOptions.None);
                if (split != null && split.Length > 1)
                {
                    string uid  = split[0];
                    string name = split[1];

                    string progress = "0";
                    if (message.completed)
                    {
                        progress = "100";
                    }
                    Utils.sendUiCommand(webView, "addFile", Crypto.hashToString(message.id), address, nick, avatar, uid, name, message.timestamp.ToString(), message.localSender.ToString(), message.confirmed.ToString(), message.read.ToString(), progress, message.completed.ToString());
                }
            }

            if (message.type == FriendMessageType.standard)
            {
                // Normal chat message
                // Call webview methods on the main UI thread only
                Utils.sendUiCommand(webView, prefix, Crypto.hashToString(message.id), address, nick, avatar, message.message, message.timestamp.ToString(), message.confirmed.ToString(), message.read.ToString());
            }
            updateMessageReadStatus(message);
        }
Beispiel #27
0
 public void setLastMessage(FriendMessage msg, int channel)
 {
     lastMessage        = new FriendMessage(msg.getBytes());
     lastMessageChannel = channel;
 }
 public void updateMessage(FriendMessage message)
 {
     Utils.sendUiCommand(webView, "updateMessage", Crypto.hashToString(message.id), message.message, message.confirmed.ToString(), message.read.ToString());
 }
Beispiel #29
0
        public void loadChats()
        {
            // Check if there are any changes from last time first
            int unread = 0;

            foreach (Friend friend in FriendList.friends)
            {
                int umc = friend.getUnreadMessageCount();
                if (umc > 0)
                {
                    unread += umc;
                }
            }

            if (unread > 0)
            {
                Utils.sendUiCommand(webView, "setUnreadIndicator", unread.ToString());
            }
            else
            {
                Utils.sendUiCommand(webView, "setUnreadIndicator", "0");
            }

            if (!Node.shouldRefreshContacts)
            {
                //  No changes detected, stop here
                return;
            }

            Utils.sendUiCommand(webView, "clearChats");
            Utils.sendUiCommand(webView, "clearUnreadActivity");

            foreach (Friend friend in FriendList.friends)
            {
                if (!friend.approved || friend.getUnreadMessageCount() > 0)
                {
                    string str_online = "false";
                    if (friend.online)
                    {
                        str_online = "true";
                    }

                    // Generate the excerpt depending on message type
                    FriendMessage lastmsg = friend.messages.Last();
                    string        excerpt = lastmsg.message;
                    if (lastmsg.type == FriendMessageType.requestFunds)
                    {
                        if (lastmsg.localSender)
                        {
                            excerpt = "Payment Request Sent";
                        }
                        else
                        {
                            excerpt = "Payment Request Received";
                        }
                    }
                    else if (lastmsg.type == FriendMessageType.sentFunds)
                    {
                        if (lastmsg.localSender)
                        {
                            excerpt = "Payment Sent";
                        }
                        else
                        {
                            excerpt = "Payment Received";
                        }
                    }
                    else if (lastmsg.type == FriendMessageType.requestAdd)
                    {
                        excerpt = "Contact Request";
                    }

                    Utils.sendUiCommand(webView, "addChat",
                                        Base58Check.Base58CheckEncoding.EncodePlain(friend.walletAddress), friend.nickname, Clock.getRelativeTime(lastmsg.timestamp), "img/spixiavatar.png", str_online, excerpt, friend.getUnreadMessageCount().ToString());

                    Utils.sendUiCommand(webView, "addUnreadActivity",
                                        Base58Check.Base58CheckEncoding.EncodePlain(friend.walletAddress), friend.nickname, Clock.getRelativeTime(lastmsg.timestamp), "img/spixiavatar.png", str_online, excerpt);
                }
            }


            foreach (Friend friend in FriendList.friends)
            {
                if (friend.getMessageCount() > 0 && friend.getUnreadMessageCount() < 1)
                {
                    string str_online = "false";
                    if (friend.online)
                    {
                        str_online = "true";
                    }

                    // Generate the excerpt depending on message type
                    FriendMessage lastmsg = friend.messages.Last();
                    string        excerpt = lastmsg.message;
                    if (lastmsg.type == FriendMessageType.requestFunds)
                    {
                        if (lastmsg.localSender)
                        {
                            excerpt = "Payment Request Sent";
                        }
                        else
                        {
                            excerpt = "Payment Request Received";
                        }
                    }
                    else if (lastmsg.type == FriendMessageType.sentFunds)
                    {
                        if (lastmsg.localSender)
                        {
                            excerpt = "Payment Sent";
                        }
                        else
                        {
                            excerpt = "Payment Received";
                        }
                    }
                    else if (lastmsg.type == FriendMessageType.requestAdd)
                    {
                        excerpt = "Contact Request";
                    }


                    Utils.sendUiCommand(webView, "addChat",
                                        Base58Check.Base58CheckEncoding.EncodePlain(friend.walletAddress), friend.nickname, Clock.getRelativeTime(lastmsg.timestamp), "img/spixiavatar.png", str_online, excerpt, "0");
                }
            }
        }
Beispiel #30
0
        public static FriendMessage addMessageWithType(byte[] id, FriendMessageType type, byte[] wallet_address, string message, bool local_sender = false, byte[] sender_address = null, long timestamp = 0, bool fire_local_notification = true)
        {
            Friend friend = getFriend(wallet_address);

            if (friend == null)
            {
                // No matching contact found in friendlist
                // Add the contact, then issue the message again?
                // TODO: need to fetch the stage 1 public key somehow here
                // Ignoring such messages for now
                //addFriend(wallet_address, "pubkey", "Unknown");
                //addMessage(wallet_address, message);

                Logging.warn("Received message but contact isn't in our contact list.");
                return(null);
            }

            Node.shouldRefreshContacts = true;

            if (!friend.online)
            {
                using (MemoryStream mw = new MemoryStream())
                {
                    using (BinaryWriter writer = new BinaryWriter(mw))
                    {
                        writer.Write(wallet_address.Length);
                        writer.Write(wallet_address);

                        CoreProtocolMessage.broadcastProtocolMessage(new char[] { 'M' }, ProtocolMessageCode.getPresence, mw.ToArray(), null);
                    }
                }
            }

            string sender_nick = "";

            if (friend.bot && sender_address != null)
            {
                if (IxianHandler.getWalletStorage().isMyAddress(sender_address))
                {
                    local_sender = true;
                }
                if (!local_sender)
                {
                    if (friend.contacts.ContainsKey(sender_address) && friend.contacts[sender_address].nick != "")
                    {
                        sender_nick = friend.contacts[sender_address].nick;
                    }
                    else
                    {
                        if (!friend.contacts.ContainsKey(sender_address) || friend.contacts[sender_address].publicKey == null)
                        {
                            StreamProcessor.requestPubKey(friend, sender_address);
                        }
                        StreamProcessor.requestNickname(friend, sender_address);
                    }
                }
            }
            else
            {
                sender_nick = friend.nickname;
            }

            if (timestamp == 0)
            {
                timestamp = Clock.getTimestamp();
            }

            FriendMessage friend_message = new FriendMessage(id, message, timestamp, local_sender, type, sender_address, sender_nick);

            if (friend.bot)
            {
                if (local_sender)
                {
                    friend_message.read = true;
                }
                else
                {
                    friend.lastReceivedMessageId = id;
                    saveToStorage();
                }
            }

            lock (friend.messages)
            {
                // TODO should be optimized
                if (id != null && friend.messages.Find(x => x.id != null && x.id.SequenceEqual(id)) != null)
                {
                    Logging.warn("Message with id {0} was already in message list.", Crypto.hashToString(id));
                    return(null);
                }
                friend.messages.Add(friend_message);
            }

            // If a chat page is visible, insert the message directly
            if (friend.chat_page != null)
            {
                friend.chat_page.insertMessage(friend_message);
            }

            // Send a local push notification if Spixi is not in the foreground
            if (fire_local_notification && !local_sender)
            {
                if (App.isInForeground == false || friend.chat_page == null)
                {
                    // don't fire notification for nickname and avatar
                    if (!friend_message.id.SequenceEqual(new byte[] { 4 }) && !friend_message.id.SequenceEqual(new byte[] { 5 }))
                    {
                        DependencyService.Get <IPushService>().showLocalNotification("Spixi", "New Message", Base58Check.Base58CheckEncoding.EncodePlain(friend.walletAddress));
                    }
                }
            }

            ISystemAlert alert = DependencyService.Get <ISystemAlert>();

            if (alert != null)
            {
                alert.flash();
            }

            // Write to chat history
            Node.localStorage.writeMessages(wallet_address, friend.messages);

            return(friend_message);
        }