public MessageMessage toXmppMessage(string fromFullJid, ChatTable chat) { MessageMessage msg; switch (type) { case MessageMessage.TYPE_GROUPCHAT: msg = new MessageMessage(fromFullJid, chat.chatJabberId, message, type, fromUser, true); break; default: if (isEncrypted) { msg = new OmemoMessageMessage(fromFullJid, chat.chatJabberId, message, type, true); } else { msg = new MessageMessage(fromFullJid, chat.chatJabberId, message, type, true); } break; } msg.addDelay(date); msg.chatMessageId = id; return(msg); }
public ChatMessageTable(MessageMessage msg, ChatTable chat) { switch (msg.TYPE) { case MessageMessage.TYPE_ERROR: id = generateErrorMessageId(msg.ID, chat.id); fromUser = msg.getFrom(); break; case MessageMessage.TYPE_GROUPCHAT: id = generateId(msg.ID, chat.id); fromUser = msg.FROM_NICK; break; default: id = generateId(msg.ID, chat.id); fromUser = Utils.getBareJidFromFullJid(msg.getFrom()); break; } stableId = msg.ID; chatId = chat.id; type = msg.TYPE; message = msg.MESSAGE; date = msg.delay; isDummyMessage = false; if (date.Equals(DateTime.MinValue)) { date = DateTime.Now; } state = msg.CC_TYPE == XMPP_API.Classes.Network.XML.CarbonCopyType.SENT ? MessageState.SEND : MessageState.UNREAD; isImage = isMessageAnImageUrl(msg.MESSAGE); isCC = msg.CC_TYPE != XMPP_API.Classes.Network.XML.CarbonCopyType.NONE; isEncrypted = msg is OmemoMessageMessage; isFavorite = false; }
/// <summary> /// Sends all chat messages passed to it. /// </summary> /// <param name="client">The XMPPClient that should be used to send the messages.</param> /// <param name="messages">A list of chat messages to send. They SHOULD be sorted by their chatId for optimal performance.</param> private async Task sendOutsandingChatMessagesAsync(XMPPClient client, IList <ChatMessageTable> messages) { ChatTable chat = null; foreach (ChatMessageTable msgDb in messages) { if (chat is null || !string.Equals(chat.id, msgDb.chatId)) { chat = ChatDBManager.INSTANCE.getChat(msgDb.chatId); if (chat is null) { Logger.Warn("Unable to send outstanding chat message for: " + msgDb.chatId + " - no such chat."); continue; } } MessageMessage msg = msgDb.toXmppMessage(client.getXMPPAccount().getFullJid(), chat); if (msg is OmemoMessageMessage omemoMsg) { await client.sendOmemoMessageAsync(omemoMsg, chat.chatJabberId, client.getXMPPAccount().getBareJid()); } else { await client.sendAsync(msg); } } }
public Message(MessageMessage message) { From = message.From; To = message.To; Content = message.Content; Id = message.Id; RecipientId = message.RecipientId; }
public async Task <IActionResult> AddMessage(MessageMessage message) { if (IsLoginValid(message)) { await repo.AddMessage(message.Message); return(Ok()); } return(BadRequest()); }
/// <summary> /// /// </summary> /// <param name="Message"></param> protected override void HandleMessageMessage(MessageMessage Message) { base.HandleMessageMessage(Message); if (Message.Message.FullString.Contains(ChatSubStrings.IMPROVED)) { imps++; } Log("CHAT", Message.Message.FullString); }
public override BaseMessage ToMessage() { var msg = new MessageMessage(); msg.From = From; msg.To = To; msg.Content = Content; msg.Id = Id; msg.RecipientId = RecipientId; return(msg); }
void SendMessage() { var text = this.tbSendMessage.Text.Trim(); if (text != "") { this.tbSendMessage.Clear(); this.tbSendMessage.Focus(); var msg = new MessageMessage(text); this._mc.Send(msg); } }
private static void KillMessageReceived(MessageMessage messageMessage) { try { var kill = JsonConvert.DeserializeObject <Kill>(messageMessage.Body); InitKillIds(kill); KILLS.Add(kill); } catch (Exception) { LOG.Warn("Could not deserialize to kill: " + messageMessage.Body); } }
//--------------------------------------------------------Constructor:----------------------------------------------------------------\\ #region --Constructors-- public QueryArchiveResultMessage(XmlNode node, XmlNode resultNode, XmlNode forwardedNode, List <AbstractMessage> content) : base(node) { QUERY_ID = resultNode.Attributes["queryid"]?.Value; CONTENT = content; XmlNode delayNode = XMLUtils.getChildNode(forwardedNode, "delay", Consts.XML_XMLNS, Consts.XML_XEP_0203_NAMESPACE); DELAY = MessageMessage.parseDelay(delayNode); foreach (AbstractMessage message in CONTENT) { if (message is MessageMessage msg) { msg.addDelay(DELAY); } } }
public async Task <bool> OnNewChatMessage(MessageMessage msg, string deviceFullJid, Client client) { string fromFullJid = msg.getFrom(); string fromBareJid = Utils.getBareJidFromFullJid(fromFullJid); // Send the response: if (string.Equals(fromBareJid, deviceFullJid)) { MessageMessage response = new MessageMessage(client.dbAccount.fullJid.FullJid(), fromBareJid, msg.MESSAGE, MessageMessage.TYPE_CHAT, true); await client.xmppClient.SendAsync(response); await AddIoTDevice(fromBareJid, client); return(true); } return(false); }
/// <summary> /// /// </summary> /// <param name="Message"></param> protected override void HandleMessageMessage(MessageMessage Message) { base.HandleMessageMessage(Message); string s = Message.Message.FullString; const string prefix = "[###]"; const string ignore1 = "Your safety is now"; // starts with prefix and does not contain ignores if (DisplayMessages && s.IndexOf(prefix) == 0 && s.IndexOf(ignore1) == -1) { SendSplitIRCChannelServerString(Message.Message); } }
private void Start() { try { while (true) { var frame = Frame.ReadFrom(_stream); if (ErrorMessage.IsError(frame)) { //TODO in andere threads verlagern? OnErrorMessageReceived(new ErrorMessage(frame)); continue; } var message = new MessageMessage(frame); List <Action <MessageMessage> > handlers; lock (_messageHandlers) { if (!_messageHandlers.TryGetValue(message.Destination, out handlers)) { return; } handlers = handlers.ToList(); } foreach (var curHandler in handlers) { curHandler.Invoke(message); } } } catch (ThreadAbortException) { } catch (Exception e) { OnDisconnected(e); } Disconnect(); }
//--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\ #region --Set-, Get- Methods-- #endregion //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- public void addMessage(string accountId, AbstractMessage msg) { MessageCacheTable mT = new MessageCacheTable() { accountId = accountId, messageId = msg.ID, }; if (msg is MessageMessage) { MessageMessage message = msg as MessageMessage; message.addDelay(); mT.message = message.toXmlString(); mT.isChatMessage = true; mT.chatMessageId = message.chatMessageId; } else { mT.message = msg.toXmlString(); mT.isChatMessage = false; } dB.InsertOrReplace(mT); }
/// <summary> /// /// </summary> /// <param name="Message"></param> protected override void HandleMessageMessage(MessageMessage Message) { base.HandleMessageMessage(Message); string s = Message.Message.FullString; const string prefix = "[###]"; const string ignore1 = "Your safety is now"; // starts with prefix and does not contain ignores if (s.IndexOf(prefix) == 0 && s.IndexOf(ignore1) == -1 && IrcClient.IsRegistered && IrcChannel != null) { // build a str to log // this has a prefix (e.g. "103: ") and a m59 message string chatstr = IRCChatStyle.GetPrefixString(Config.ChatPrefix) + IRCChatStyle.CreateIRCMessageFromChatMessage(Message.Message); // try to log the chatmessage to IRC IrcClient.LocalUser.SendMessage(IrcChannel, chatstr); } }
public void Message_Value_Test() { ProtobufModel model = new ProtobufModel { IntValue = 100, StringValue = "Hello" }; MemoryStream stream = new MemoryStream(); { //Message.Serialize(stream, model); ((IMessage)(Message <ProtobufModel>)model).WriteTo(stream); //Message.Serialize(stream, model); stream.Position = 0; Assert.Equal(stream.Length, ((IMessage)(Message <ProtobufModel>)model).CalculateSize()); var model2 = new MessageMessage <ProtobufModel>(new ProtobufModel()); ((IMessage)model2).MergeFrom(stream); Assert.Equal(model.IntValue, model2.Source.IntValue); Assert.Equal(model.StringValue, model2.Source.StringValue); } { var message = (Message <ProtobufModel>)model; stream.Position = 0; Message.Serialize(stream, model); stream.Position = 0; var model2 = Message <ProtobufModel> .Deserialize(stream); Assert.Equal(model.IntValue, model2.IntValue); Assert.Equal(model.StringValue, model2.StringValue); } }
//--------------------------------------------------------Constructor:----------------------------------------------------------------\\ #region --Constructors-- public QueryArchiveResultMessage(XmlNode answer) : base(answer) { XmlNode resultNode = XMLUtils.getChildNode(answer, "result", Consts.XML_XMLNS, Consts.XML_XEP_0313_NAMESPACE); if (!(resultNode is null)) { QUERY_ID = resultNode.Attributes["queryid"]?.Value; XmlNode forwardedNode = XMLUtils.getChildNode(resultNode, "forwarded", Consts.XML_XMLNS, Consts.XML_XEP_0297_NAMESPACE); if (!(forwardedNode is null)) { XmlNode messageNode = XMLUtils.getChildNode(forwardedNode, "message"); if (!(messageNode is null)) { MESSAGE = new MessageMessage(messageNode, CarbonCopyType.NONE); XmlNode delayNode = XMLUtils.getChildNode(forwardedNode, "delay", Consts.XML_XMLNS, Consts.XML_XEP_0203_NAMESPACE); if (!(delayNode is null)) { MESSAGE.parseDelay(delayNode); } } } } }
private void C_NewChatMessage(XMPPClient client, XMPP_API.Classes.Network.Events.NewChatMessageEventArgs args) { MessageMessage msg = args.getMessage(); // Handel MUC room subject messages: if (msg is MUCRoomSubjectMessage) { MUCHandler.INSTANCE.onMUCRoomSubjectMessage(msg as MUCRoomSubjectMessage); return; } string from = Utils.getBareJidFromFullJid(msg.getFrom()); // Check if device id is valid and if, decrypt the OMEMO messages: if (msg is OmemoMessageMessage omemoMessage) { // Decryption failed: if (!omemoMessage.decrypt(client.getOmemoHelper(), client.getXMPPAccount().omemoDeviceId)) { return; } } string to = Utils.getBareJidFromFullJid(msg.getTo()); string id; if (msg.CC_TYPE == CarbonCopyType.SENT) { id = ChatTable.generateId(to, from); } else { id = ChatTable.generateId(from, to); } ChatTable chat = ChatDBManager.INSTANCE.getChat(id); bool chatChanged = false; if (chat == null) { chatChanged = true; chat = new ChatTable() { id = id, chatJabberId = from, userAccountId = to, ask = null, inRoster = false, lastActive = msg.getDelay(), muted = false, presence = Presence.Unavailable, status = null, subscription = null, chatType = Equals(msg.TYPE, MessageMessage.TYPE_GROUPCHAT) ? ChatType.MUC : ChatType.CHAT, }; } ChatMessageTable message = new ChatMessageTable(msg, chat); // Handle MUC invite messages: if (msg is DirectMUCInvitationMessage) { DirectMUCInvitationMessage inviteMessage = msg as DirectMUCInvitationMessage; bool doesRoomExist = ChatDBManager.INSTANCE.doesMUCExist(ChatTable.generateId(inviteMessage.ROOM_JID, msg.getTo())); bool doesOutstandingInviteExist = ChatDBManager.INSTANCE.doesOutstandingMUCInviteExist(id, inviteMessage.ROOM_JID); if (doesRoomExist && doesOutstandingInviteExist) { return; } MUCDirectInvitationTable inviteTable = new MUCDirectInvitationTable(inviteMessage, message.id); ChatDBManager.INSTANCE.setMUCDirectInvitation(inviteTable); } bool isMUCMessage = string.Equals(MessageMessage.TYPE_GROUPCHAT, message.type); ChatMessageTable existingMessage = ChatDBManager.INSTANCE.getChatMessageById(message.id); bool doesMessageExist = existingMessage != null; if (isMUCMessage) { MUCChatInfoTable mucInfo = MUCDBManager.INSTANCE.getMUCInfo(chat.id); if (mucInfo != null) { if (Equals(message.fromUser, mucInfo.nickname)) { // Filter MUC messages that already exist: // ToDo: Allow MUC messages being edited and detect it if (doesMessageExist) { return; } else { message.state = MessageState.SEND; } } else { if (doesMessageExist) { message.state = existingMessage.state; } } } } if (chat.lastActive.CompareTo(msg.getDelay()) < 0) { chatChanged = true; chat.lastActive = msg.getDelay(); } if (chatChanged) { ChatDBManager.INSTANCE.setChat(chat, false, true); } // Send XEP-0184 (Message Delivery Receipts) reply: if (msg.RECIPT_REQUESTED && id != null && !Settings.getSettingBoolean(SettingsConsts.DONT_SEND_CHAT_MESSAGE_RECEIVED_MARKERS)) { Task.Run(async() => { DeliveryReceiptMessage receiptMessage = new DeliveryReceiptMessage(client.getXMPPAccount().getIdDomainAndResource(), from, msg.ID); await client.sendAsync(receiptMessage, true); }); } ChatDBManager.INSTANCE.setChatMessage(message, !doesMessageExist, doesMessageExist && !isMUCMessage); // Show toast: if (!doesMessageExist && !chat.muted) { Task.Run(() => { try { if (!msg.toasted) { switch (msg.TYPE) { case MessageMessage.TYPE_GROUPCHAT: case MessageMessage.TYPE_CHAT: if (!message.isCC) { if (message.isEncrypted) { ToastHelper.showChatTextEncryptedToast(message, chat); } else if (message.isImage) { ToastHelper.showChatTextImageToast(message, chat); } else { ToastHelper.showChatTextToast(message, chat); } } break; default: break; } msg.setToasted(); } } catch (Exception e) { Logger.Error("Failed to send toast notification!", e); } }); } }
public void handleMessage(Message msg) { if (msg is MessageMessage) { MessageMessage omsg = (MessageMessage)msg; if (omsg.type == MessageMessage.Type.SOLD_MARKET_SCROLLS) { this.needSoldAucs = true; App.Communicator.send(new MarketplaceSoldListViewMessage()); } } if (msg is OkMessage) { OkMessage omsg = (OkMessage)msg; if (Helpfunktions.Instance.createAuctionMenu) { if (omsg.op == "MarketplaceCreateOffer" && this.sellingCard != null) { Helpfunktions.Instance.cardIDToNumberOwned[this.sellingType]--; Helpfunktions.Instance.cardIDToNumberOwnedTiered[this.sellingType] -= (int)Math.Pow(3, sellingTypeLevel); PlayerStore.Instance.createCardsFilter.filtersChanged = true; PlayerStore.Instance.sellOfferFilter.filtersChanged = true; this.dataOffer = 0; this.sellingCard = null; App.Communicator.send(new MarketplaceOffersViewMessage()); //App.Communicator.send(new MarketplaceSoldListViewMessage()); App.Communicator.sendRequest(new LibraryViewMessage()); } if (omsg.op == "MarketplaceCancelOffer") { Helpfunktions.Instance.cardIDToNumberOwned[this.cancelType]++; Helpfunktions.Instance.cardIDToNumberOwnedTiered[this.cancelType] += (int)Math.Pow(3, cancelTypeLevel); PlayerStore.Instance.createCardsFilter.filtersChanged = true; PlayerStore.Instance.sellOfferFilter.filtersChanged = true; this.dataOffer = 0; App.Communicator.send(new MarketplaceOffersViewMessage()); //App.Communicator.send(new MarketplaceSoldListViewMessage()); App.Communicator.sendRequest(new LibraryViewMessage()); } if (omsg.op == "MarketplaceClaim") { if (transactionBeingClaimed == null) { return; } if (this.workthreadclaimall) { this.claimeditemstaxes += this.transactionBeingClaimed.fee; this.claimeditemsmoney += this.transactionBeingClaimed.sellPrice; System.Threading.Thread.Sleep(150); this.claimlast(); return; } App.AudioScript.PlaySFX("Sounds/hyperduck/UI/ui_coin_tally_end"); CardType cardType = CardTypeManager.getInstance().get(this.transactionBeingClaimed.cardType); this.dataOffer = 0; this.needSoldAucs = true; App.Communicator.send(new MarketplaceOffersViewMessage()); App.Communicator.send(new MarketplaceSoldListViewMessage()); App.Communicator.sendRequest(new LibraryViewMessage()); App.Popups.ShowOk(this, "claimgold", "Gold added", string.Concat(new object[] { "<color=#bbaa88>Tier ", (int)(this.transactionBeingClaimed.level + 1), " ", cardType.name, " sold for ", this.transactionBeingClaimed.sellPrice, " gold!\nEarned <color=#ffd055>", this.transactionBeingClaimed.sellPrice - this.transactionBeingClaimed.fee, " gold</color> (the fence collects ", this.transactionBeingClaimed.fee, ").</color>" }), "Ok"); this.transactionBeingClaimed = null; } } if (Helpfunktions.Instance.playerStoreMenu) { if (omsg.op == "MarketplaceMakeDeal") { App.Communicator.sendRequest(new GetStoreItemsMessage()); App.Communicator.sendRequest(new LibraryViewMessage()); App.Popups.ShowOk(this, "dealmade", "Purchase complete!", clickedItemName + " has been added to your collection.", "Ok"); Helpfunktions.Instance.cardIDToNumberOwned[this.clickedItemtypeid]++; Helpfunktions.Instance.cardIDToNumberOwnedTiered[this.clickedItemtypeid] += (int)Math.Pow(3, clickedItemLevel); PlayerStore.Instance.createCardsFilter.filtersChanged = true; PlayerStore.Instance.sellOfferFilter.filtersChanged = true; clickedItemBuyID = -1; } } } if (msg is FailMessage) { FailMessage failMessage = (FailMessage)msg; if (failMessage.isType(typeof(MarketplaceMakeDealMessage))) { App.Popups.ShowOk(this, "dealNOTmade", "Purchase failed", failMessage.info, "Ok"); PlayerStore.Instance.createCardsFilter.filtersChanged = true; PlayerStore.Instance.sellOfferFilter.filtersChanged = true; clickedItemBuyID = -1; } if (failMessage.isType(typeof(MarketplaceCreateOfferMessage)) && this.sellingCard != null) { App.Popups.ShowOk(this, "cantcreate", "Create failed", failMessage.info, "Ok"); this.sellingCard = null; } if (failMessage.isType(typeof(MarketplaceClaimMessage))) { if (transactionBeingClaimed == null) { return; } if (this.workthreadclaimall) { System.Threading.Thread.Sleep(150); this.claimlast(); return; } this.dataOffer = 0; this.needSoldAucs = true; App.Communicator.send(new MarketplaceOffersViewMessage()); App.Communicator.send(new MarketplaceSoldListViewMessage()); App.Communicator.sendRequest(new LibraryViewMessage()); transactionBeingClaimed = null; } } if (msg is CheckCardDependenciesMessage && sellingCard != null) { CheckCardDependenciesMessage checkCardDependenciesMessage = (CheckCardDependenciesMessage)msg; if (checkCardDependenciesMessage.dependencies == null || checkCardDependenciesMessage.dependencies.Length == 0) { this.GetCreateOfferInfo(); } else { App.Popups.ShowOkCancel(this, "deckinvalidationwarning", "Notice", "Selling this scroll will make the following decks illegal:\n\n" + DeckUtil.GetFormattedDeckNames(checkCardDependenciesMessage.GetDeckNames()), "Ok", "Cancel"); } } if (msg is MarketplaceCreateOfferInfoMessage && sellingCard != null) { MarketplaceCreateOfferInfoMessage marketplaceCreateOfferInfoMessage = (MarketplaceCreateOfferInfoMessage)msg; App.Popups.ShowSellCard(this, "sellcard", this.sellingCard, marketplaceCreateOfferInfoMessage.lowestPrice, marketplaceCreateOfferInfoMessage.suggestedPrice, marketplaceCreateOfferInfoMessage.copiesForSale, marketplaceCreateOfferInfoMessage.tax); } if (msg is MarketplaceOffersSearchViewMessage) { MarketplaceOffersSearchViewMessage marketplaceOffersViewMessage = (MarketplaceOffersSearchViewMessage)msg; clickedItemForSales = marketplaceOffersViewMessage.copiesForSale; clickedItemLevel = marketplaceOffersViewMessage.offer.card.level; clickedItemPrice = marketplaceOffersViewMessage.offer.price; clickedItemBuyID = marketplaceOffersViewMessage.offer.id; clickedItemName = marketplaceOffersViewMessage.offer.card.getName(); clickedItemtypeid = marketplaceOffersViewMessage.offer.card.getType(); } if (msg is MarketplaceOffersViewMessage) { //if (this.dataisreadyOwnOffers) return; MarketplaceOffersViewMessage marketplaceOffersViewMessage = (MarketplaceOffersViewMessage)msg; MarketplaceOffer[] offers = marketplaceOffersViewMessage.offers; this.pstoreOwnAucs.Clear(); DateTime tme = DateTime.Now; tme = tme.AddMilliseconds(1000); for (int i = 0; i < offers.Length; i++) { MarketplaceOffer marketplaceOffer = offers[i]; Auction a = new Auction(App.MyProfile.ProfileInfo.name, tme, Auction.OfferType.SELL, marketplaceOffer.card, "" + marketplaceOffer.id, marketplaceOffer.price); tme = tme.AddMilliseconds(1); //Console.WriteLine("add owm auction: " + a.card.getName() + " " + a.price); this.pstoreOwnAucs.Add(a); } this.dataOffer++; if (this.dataOffer >= 2 || !this.needSoldAucs) { this.dataisreadyOwnOffers = true; } if (this.dataOffer >= 2) { this.needSoldAucs = false; } } if (msg is MarketplaceSoldListViewMessage) { //if (this.dataisreadyOwnOffers) return; MarketplaceSoldListViewMessage marketplaceOffersViewMessage = (MarketplaceSoldListViewMessage)msg; TransactionInfo[] offers = marketplaceOffersViewMessage.sold; this.pstoreSOLDAucs.Clear(); this.soldScrollTransactions.Clear(); DateTime tme = DateTime.Now; for (int i = 0; i < offers.Length; i++) { TransactionInfo marketplaceOffer = offers[i]; if (!marketplaceOffer.claimed) { this.soldScrollTransactions.Add(marketplaceOffer.cardId, marketplaceOffer); } CardType type = CardTypeManager.getInstance().get(marketplaceOffer.cardType); Card c = new Card(marketplaceOffer.cardId, type, true); string aucmessage = "sold " + marketplaceOffer.fee; if (marketplaceOffer.claimed) { aucmessage += " claimed"; continue; } Auction a = new Auction(App.MyProfile.ProfileInfo.name, tme, Auction.OfferType.SELL, c, aucmessage, marketplaceOffer.sellPrice, marketplaceOffer.cardId); tme = tme.AddMilliseconds(1); //Console.WriteLine("add owm auction: " + a.card.getName() + " " + a.price); this.pstoreSOLDAucs.Add(a); } this.dataOffer++; if (this.dataOffer >= 2) { this.dataisreadyOwnOffers = true; } this.needSoldAucs = false; } if (msg is MarketplaceAvailableOffersListViewMessage) { Prices.Instance.getBlackmarketPrices(msg as MarketplaceAvailableOffersListViewMessage); if (this.dataisready) { return; } MarketplaceAvailableOffersListViewMessage marketplaceAvailableOffersListViewMessage = (MarketplaceAvailableOffersListViewMessage)msg; MarketplaceTypeAvailability[] available = marketplaceAvailableOffersListViewMessage.available; this.pstoreAucs.Clear(); DateTime tme = DateTime.Now; for (int i = 0; i < available.Length; i++) { MarketplaceTypeAvailability mta = available[i]; CardType type = CardTypeManager.getInstance().get(mta.type); Card card = new Card(1, type, true); card.level = mta.level; Auction a = new Auction("BlackMarket", tme, Auction.OfferType.SELL, card, "", mta.price); tme = tme.AddMilliseconds(-1); //Console.WriteLine("add auction: " + a.card.getName() + " " + a.price); this.pstoreAucs.Add(a); } this.dataisready = true; } return; }
private async Task SendChatMessageAsync(ChatTable chat, string message) { AccountTable account = AccountDBManager.INSTANCE.getAccount(chat.userAccountId); if (account is null) { Logger.Warn("Unable to send message - no such account: " + chat.userAccountId); return; } string fromBareJid = account.userId + '@' + account.domain; string fromFullJid = fromBareJid + '/' + account.resource; string to = chat.chatJabberId; string chatType = chat.chatType == ChatType.CHAT ? MessageMessage.TYPE_CHAT : MessageMessage.TYPE_GROUPCHAT; bool reciptRequested = true; MessageMessage toSendMsg; if (chat.omemoEnabled) { if (chat.chatType == ChatType.CHAT) { toSendMsg = new OmemoMessageMessage(fromFullJid, to, message, chatType, reciptRequested); } else { // ToDo: Add MUC OMEMO support throw new NotImplementedException("Sending encrypted messages for MUC is not supported right now!"); } } else if (chat.chatType == ChatType.CHAT) { toSendMsg = new MessageMessage(fromFullJid, to, message, chatType, reciptRequested); } else { MUCChatInfoTable mucInfo = MUCDBManager.INSTANCE.getMUCInfo(chat.id); toSendMsg = new MessageMessage(fromFullJid, to, message, chatType, mucInfo.nickname, reciptRequested); } // Create a copy for the DB: ChatMessageTable toSendMsgDB = new ChatMessageTable(toSendMsg, chat) { state = toSendMsg is OmemoMessageMessage ? MessageState.TO_ENCRYPT : MessageState.SENDING }; // Set the chat message id for later identification: toSendMsg.chatMessageId = toSendMsgDB.id; // Update chat last active: chat.lastActive = DateTime.Now; // Update DB: ChatDBManager.INSTANCE.setChatMessage(toSendMsgDB, true, false); ChatDBManager.INSTANCE.setChat(chat, false, true); Logger.Info("Added to send message in background"); if (isRunning) { XMPPClient client = ConnectionHandler.INSTANCE.getClient(fromBareJid); if (client is null) { Logger.Error("Unable to send message in background - no such client: " + fromBareJid); } // Send the message: else if (toSendMsg is OmemoMessageMessage toSendOmemoMsg) { await client.sendOmemoMessageAsync(toSendOmemoMsg, chat.chatJabberId, client.getXMPPAccount().getBareJid()); } else { await client.SendAsync(toSendMsg); } } else { ToastHelper.showWillBeSendLaterToast(chat); } }
/// <summary> /// Create a new Codec /// </summary> public Codec() { Message = new MessageMessage(); ServiceRegister = new ServiceRegisterMessage(); Error = new ErrorMessage(); }
private async void C_NewChatMessage(XMPPClient client, XMPP_API.Classes.Network.Events.NewChatMessageEventArgs args) { MessageMessage msg = args.getMessage(); // Handel MUC room subject messages: if (msg is MUCRoomSubjectMessage) { MUCHandler.INSTANCE.onMUCRoomSubjectMessage(msg as MUCRoomSubjectMessage); return; } string from = Utils.getBareJidFromFullJid(msg.getFrom()); string to = Utils.getBareJidFromFullJid(msg.getTo()); string id; if (msg.CC_TYPE == CarbonCopyType.SENT) { id = ChatTable.generateId(to, from); } else { id = ChatTable.generateId(from, to); } // Check if device id is valid and if, decrypt the OMEMO messages: if (msg is OmemoMessageMessage omemoMessage) { OmemoHelper helper = client.getOmemoHelper(); if (helper is null) { C_OmemoSessionBuildError(client, new OmemoSessionBuildErrorEventArgs(id, OmemoSessionBuildError.KEY_ERROR, new List <OmemoMessageMessage> { omemoMessage })); Logger.Error("Failed to decrypt OMEMO message - OmemoHelper is null"); return; } else if (!client.getXMPPAccount().checkOmemoKeys()) { C_OmemoSessionBuildError(client, new OmemoSessionBuildErrorEventArgs(id, OmemoSessionBuildError.KEY_ERROR, new List <OmemoMessageMessage> { omemoMessage })); Logger.Error("Failed to decrypt OMEMO message - keys are corrupted"); return; } else if (!await omemoMessage.decryptAsync(client.getOmemoHelper(), client.getXMPPAccount().omemoDeviceId)) { return; } } ChatTable chat = ChatDBManager.INSTANCE.getChat(id); bool chatChanged = false; // Spam detection: if (Settings.getSettingBoolean(SettingsConsts.SPAM_DETECTION_ENABLED)) { if (Settings.getSettingBoolean(SettingsConsts.SPAM_DETECTION_FOR_ALL_CHAT_MESSAGES) || chat is null) { if (SpamDBManager.INSTANCE.isSpam(msg.MESSAGE)) { Logger.Warn("Received spam message from " + from); return; } } } if (chat is null) { chatChanged = true; chat = new ChatTable(from, to) { lastActive = msg.getDelay(), chatType = string.Equals(msg.TYPE, MessageMessage.TYPE_GROUPCHAT) ? ChatType.MUC : ChatType.CHAT }; } ChatMessageTable message = new ChatMessageTable(msg, chat); // Handle MUC invite messages: if (msg is DirectMUCInvitationMessage) { DirectMUCInvitationMessage inviteMessage = msg as DirectMUCInvitationMessage; bool doesRoomExist = ChatDBManager.INSTANCE.doesMUCExist(ChatTable.generateId(inviteMessage.ROOM_JID, msg.getTo())); bool doesOutstandingInviteExist = ChatDBManager.INSTANCE.doesOutstandingMUCInviteExist(id, inviteMessage.ROOM_JID); if (doesRoomExist && doesOutstandingInviteExist) { return; } MUCDirectInvitationTable inviteTable = new MUCDirectInvitationTable(inviteMessage, message.id); ChatDBManager.INSTANCE.setMUCDirectInvitation(inviteTable); } bool isMUCMessage = string.Equals(MessageMessage.TYPE_GROUPCHAT, message.type); ChatMessageTable existingMessage = ChatDBManager.INSTANCE.getChatMessageById(message.id); bool doesMessageExist = existingMessage != null; if (isMUCMessage) { MUCChatInfoTable mucInfo = MUCDBManager.INSTANCE.getMUCInfo(chat.id); if (mucInfo != null) { if (Equals(message.fromUser, mucInfo.nickname)) { // Filter MUC messages that already exist: // ToDo: Allow MUC messages being edited and detect it if (doesMessageExist) { return; } else { message.state = MessageState.SEND; } } else { if (doesMessageExist) { message.state = existingMessage.state; } } } } if (chat.lastActive.CompareTo(msg.getDelay()) < 0) { chatChanged = true; chat.lastActive = msg.getDelay(); } if (chatChanged) { ChatDBManager.INSTANCE.setChat(chat, false, true); } // Send XEP-0184 (Message Delivery Receipts) reply: if (msg.RECIPT_REQUESTED && id != null && !Settings.getSettingBoolean(SettingsConsts.DONT_SEND_CHAT_MESSAGE_RECEIVED_MARKERS)) { await Task.Run(async() => { DeliveryReceiptMessage receiptMessage = new DeliveryReceiptMessage(client.getXMPPAccount().getFullJid(), from, msg.ID); await client.sendAsync(receiptMessage); }); } ChatDBManager.INSTANCE.setChatMessage(message, !doesMessageExist, doesMessageExist && !isMUCMessage); // Show toast: if (!doesMessageExist && !chat.muted) { await Task.Run(() => { try { switch (msg.TYPE) { case MessageMessage.TYPE_GROUPCHAT: case MessageMessage.TYPE_CHAT: if (!message.isCC) { if (message.isImage) { ToastHelper.showChatTextImageToast(message, chat); } else { ToastHelper.showChatTextToast(message, chat); } } break; default: break; } } catch (Exception e) { Logger.Error("Failed to send toast notification!", e); } }); } }
public async Task sendMessageAsync(MessageMessage msg) { await connection.sendAsync(msg, true, false); }
public async Task HandleNewChatMessageAsync(MessageMessage msg) { // Handel MUC room subject messages: if (msg is MUCRoomSubjectMessage) { MucHandler.INSTANCE.OnMUCRoomSubjectMessage(msg as MUCRoomSubjectMessage); return; } string from = Utils.getBareJidFromFullJid(msg.getFrom()); string to = Utils.getBareJidFromFullJid(msg.getTo()); string chatBareJid = string.Equals(from, client.dbAccount.bareJid) ? to : from; SemaLock semaLock = DataCache.INSTANCE.NewChatSemaLock(); ChatModel chat = DataCache.INSTANCE.GetChat(client.dbAccount.bareJid, chatBareJid, semaLock); bool newChat = chat is null; bool chatChanged = false; // Spam detection: if (Settings.GetSettingBoolean(SettingsConsts.SPAM_DETECTION_ENABLED)) { if (Settings.GetSettingBoolean(SettingsConsts.SPAM_DETECTION_FOR_ALL_CHAT_MESSAGES) || newChat) { if (SpamHelper.INSTANCE.IsSpam(msg.MESSAGE)) { Logger.Warn("Received spam message from " + chatBareJid); return; } } } // Detect invalid chat messages: if (!string.Equals(msg.TYPE, MessageMessage.TYPE_CHAT) && !string.Equals(msg.TYPE, MessageMessage.TYPE_ERROR) && !string.Equals(msg.TYPE, MessageMessage.TYPE_GROUPCHAT)) { Logger.Warn($"Received an unknown message type ('{msg.TYPE}') form '{chatBareJid}'. Dropping it."); return; } // Add the new chat to the DB since it's expected to be there by for example our OMEMO encryption: if (newChat) { chat = new ChatModel(chatBareJid, client.dbAccount) { lastActive = msg.delay, chatType = string.Equals(msg.TYPE, MessageMessage.TYPE_GROUPCHAT) ? ChatType.MUC : ChatType.CHAT, isChatActive = false // Mark chat as inactive until we can be sure, it's a valid message }; DataCache.INSTANCE.AddChatUnsafe(chat, client); } else { // Mark chat as active: chat.isChatActive = true; chatChanged = true; } semaLock.Dispose(); // Check if device id is valid and if, decrypt the OMEMO messages: if (msg is OmemoEncryptedMessage omemoMessage) { OmemoHelper helper = client.xmppClient.getOmemoHelper(); if (helper is null) { OnOmemoSessionBuildError(client.xmppClient, new OmemoSessionBuildErrorEventArgs(chatBareJid, OmemoSessionBuildError.KEY_ERROR, new List <OmemoEncryptedMessage> { omemoMessage })); Logger.Error("Failed to decrypt OMEMO message - OmemoHelper is null"); return; } else if (!await DecryptOmemoEncryptedMessageAsync(omemoMessage, !newChat && chat.omemoInfo.trustedKeysOnly)) { if (newChat) { // We failed to decrypt, so this chat could be spam. Delete it again... DataCache.INSTANCE.DeleteChat(chat, false, false); Logger.Debug($"Deleting chat '{chat.bareJid}' again, since decrypting the initial OMEMO message failed."); } return; } else if (omemoMessage.IS_PURE_KEY_EXCHANGE_MESSAGE) { return; } } // Valid new chat, so we can change it to active now: chat.isChatActive = true; chatChanged = true; ChatMessageModel message = null; if (!newChat) { message = DataCache.INSTANCE.GetChatMessage(chat.id, msg.ID); } // Filter messages that already exist: // ToDo: Allow MUC messages being edited and detect it if (!(message is null)) { Logger.Debug("Duplicate message received from '" + chatBareJid + "'. Dropping it..."); return; } message = new ChatMessageModel(msg, chat); // Set the image path and file name: if (message.isImage) { await DataCache.PrepareImageModelPathAndNameAsync(message.image); } DataCache.INSTANCE.AddChatMessage(message, chat); // Handle MUC invite messages: if (msg is DirectMUCInvitationMessage inviteMessage) { if (!newChat) { Logger.Info("Ignoring received MUC direct invitation form '" + chatBareJid + "' since we already joined this MUC (" + inviteMessage.ROOM_JID + ")."); return; } // Ensure we add the message to the DB before we add the invite since the invite has the message as a foreign key: using (MainDbContext ctx = new MainDbContext()) { ctx.Add(new MucDirectInvitationModel(inviteMessage, message)); } } bool isMUCMessage = string.Equals(MessageMessage.TYPE_GROUPCHAT, message.type); if (chat.lastActive.CompareTo(msg.delay) < 0) { chatChanged = true; chat.lastActive = msg.delay; } // Send XEP-0184 (Message Delivery Receipts) reply: if (msg.RECIPT_REQUESTED && !Settings.GetSettingBoolean(SettingsConsts.DONT_SEND_CHAT_MESSAGE_RECEIVED_MARKERS)) { await Task.Run(async() => { DeliveryReceiptMessage receiptMessage = new DeliveryReceiptMessage(client.dbAccount.fullJid.FullJid(), from, msg.ID); await client.xmppClient.SendAsync(receiptMessage); }); } if (chatChanged) { chat.Update(); chatChanged = false; } // Show toast: if (!chat.muted) { await Task.Run(() => { try { switch (msg.TYPE) { case MessageMessage.TYPE_GROUPCHAT: case MessageMessage.TYPE_CHAT: if (!message.isCC) { // Create toast: if (message.isImage) { ToastHelper.ShowChatTextImageToast(message, chat); } else { ToastHelper.ShowChatTextToast(message, chat); } // Update badge notification count: ToastHelper.UpdateBadgeNumber(); } break; default: break; } } catch (Exception e) { Logger.Error("Failed to send toast notification!", e); } }); } }
//--------------------------------------------------------Constructor:----------------------------------------------------------------\\ #region --Constructors-- /// <summary> /// Basic Constructor /// </summary> /// <history> /// 29/08/2017 Created [Fabian Sauter] /// </history> public NewChatMessageEventArgs(MessageMessage message) { MESSAGE = message; }
private void sendMessage() { if (!string.IsNullOrWhiteSpace(message_tbx.Text)) { if (IsDummy) { addDummyMessage(message_tbx.Text, Chat.userAccountId, MessageState.SEND); sendDummyMessages++; switch (sendDummyMessages) { case 1: accImg_aiwp.Presence = Presence.Online; break; case 3: sendBotMessage(Localisation.getLocalizedString("chat_details_dummy_answer_3_img"), true, 3000); sendBotMessage(Localisation.getLocalizedString("chat_details_dummy_answer_3"), false, 4000); accImg_aiwp.Presence = Presence.Chat; break; case 4: sendBotMessage(Localisation.getLocalizedString("chat_details_dummy_answer_4"), false, 3000); accImg_aiwp.Presence = Presence.Online; break; case 7: sendBotMessage(Localisation.getLocalizedString("chat_details_dummy_answer_7"), false, 3000); break; case 11: sendBotMessage(Localisation.getLocalizedString("chat_details_dummy_answer_11"), false, 3000); break; case 15: sendBotMessage(Localisation.getLocalizedString("chat_details_dummy_answer_15"), false, 3000); accImg_aiwp.Presence = Presence.Xa; break; case 20: sendBotMessage(Localisation.getLocalizedString("chat_details_dummy_answer_20"), false, 3000); break; case 30: sendBotMessage(Localisation.getLocalizedString("chat_details_dummy_answer_30"), false, 3000); break; case 50: sendBotMessage(Localisation.getLocalizedString("chat_details_dummy_answer_50_1"), false, 3000); sendBotMessage(Localisation.getLocalizedString("chat_details_dummy_answer_50_2"), false, 4000); sendBotMessage(Localisation.getLocalizedString("chat_details_dummy_answer_50_3"), false, 5000); sendBotMessage(Localisation.getLocalizedString("chat_details_dummy_answer_50_4"), false, 6000); sendBotMessage(Localisation.getLocalizedString("chat_details_dummy_answer_50_5"), false, 7000); sendBotMessage(Localisation.getLocalizedString("chat_details_dummy_answer_50_6"), false, 8000); sendBotMessage(Localisation.getLocalizedString("chat_details_dummy_answer_50_7"), true, 9000); Task.Run(async() => { await Task.Delay(9000); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { storeChatState(ChatState.GONE); accImg_aiwp.Presence = Presence.Unavailable; }); }); break; } } else { MessageMessage sendMessage; string messageText = message_tbx.Text; // Remove all tailing whitespaces, tabs and newlines: messageText = messageText.TrimEnd(TRIM_CHARS).TrimStart(TRIM_CHARS); // For MUC messages also pass the nickname: bool toEncrypt = false; if (Chat.chatType == ChatType.MUC && MUCInfo != null) { sendMessage = new MessageMessage(Client.getXMPPAccount().getIdAndDomain(), Chat.chatJabberId, messageText, getChatType(), MUCInfo.nickname, false); } else { if (Chat.omemoEnabled) { sendMessage = new OmemoMessageMessage(Client.getXMPPAccount().getIdAndDomain(), Chat.chatJabberId, messageText, getChatType(), true); toEncrypt = true; } else { sendMessage = new MessageMessage(Client.getXMPPAccount().getIdAndDomain(), Chat.chatJabberId, messageText, getChatType(), true); } } ChatMessageTable sendMessageTable = new ChatMessageTable(sendMessage, Chat) { state = toEncrypt ? MessageState.TO_ENCRYPT : MessageState.SENDING }; // Set chatMessageId: sendMessage.chatMessageId = sendMessageTable.id; // Add message to DB and update chat last active: Chat.lastActive = DateTime.Now; ChatTable chatCpy = Chat; Task.Run(() => { ChatDBManager.INSTANCE.setChatMessage(sendMessageTable, true, false); ChatDBManager.INSTANCE.setChat(chatCpy, false, true); }); if (sendMessage is OmemoMessageMessage omemoMsg) { Client.sendOmemoMessage(omemoMsg, Chat.chatJabberId, Client.getXMPPAccount().getIdAndDomain()); } else { Task t = Client.sendMessageAsync(sendMessage); } } message_tbx.Text = ""; } }
private async Task SendChatMessageAsync(ChatDataTemplate chat, string message) { MessageMessage toSendMsg; string from = chat.Client.getXMPPAccount().getFullJid(); string to = chat.Chat.chatJabberId; string chatType = chat.Chat.chatType == ChatType.CHAT ? MessageMessage.TYPE_CHAT : MessageMessage.TYPE_GROUPCHAT; bool reciptRequested = true; if (chat.Chat.omemoEnabled) { if (chat.Chat.chatType == ChatType.CHAT) { toSendMsg = new OmemoMessageMessage(from, to, message, chatType, reciptRequested); } else { // ToDo: Add MUC OMEMO support throw new NotImplementedException("Sending encrypted messages for MUC is not supported right now!"); } } else { if (chat.Chat.chatType == ChatType.CHAT) { toSendMsg = new MessageMessage(from, to, message, chatType, reciptRequested); } else { toSendMsg = new MessageMessage(from, to, message, chatType, chat.MucInfo.nickname, reciptRequested); } } // Create a copy for the DB: ChatMessageTable toSendMsgDB = new ChatMessageTable(toSendMsg, chat.Chat) { state = toSendMsg is OmemoMessageMessage ? MessageState.TO_ENCRYPT : MessageState.SENDING }; // Set the chat message id for later identification: toSendMsg.chatMessageId = toSendMsgDB.id; // Update chat last active: chat.Chat.lastActive = DateTime.Now; // Update DB: await Task.Run(() => { ChatDBManager.INSTANCE.setChatMessage(toSendMsgDB, true, false); ChatDBManager.INSTANCE.setChat(chat.Chat, false, true); }); // Send the message: if (toSendMsg is OmemoMessageMessage toSendOmemoMsg) { await chat.Client.sendOmemoMessageAsync(toSendOmemoMsg, chat.Chat.chatJabberId, chat.Client.getXMPPAccount().getBareJid()); } else { await chat.Client.sendAsync(toSendMsg); } }
private async Task SendChatMessageAsync(ChatModel chat, string message) { string fromFullJid; using (MainDbContext ctx = new MainDbContext()) { fromFullJid = ctx.Accounts.Where(a => string.Equals(a.bareJid, chat.accountBareJid)).Select(a => a.fullJid.FullJid()).FirstOrDefault(); } if (fromFullJid is null) { Logger.Error($"Failed to send message from background. Account '{chat.bareJid}' does not exist."); return; } string to = chat.bareJid; string chatType = chat.chatType == ChatType.CHAT ? MessageMessage.TYPE_CHAT : MessageMessage.TYPE_GROUPCHAT; bool reciptRequested = true; MessageMessage toSendMsg; if (chat.omemoInfo.enabled) { if (chat.chatType == ChatType.CHAT) { toSendMsg = new OmemoEncryptedMessage(fromFullJid, to, message, chatType, reciptRequested); } else { // ToDo: Add MUC OMEMO support throw new NotImplementedException("Sending encrypted messages for MUC is not supported right now!"); } } else if (chat.chatType == ChatType.CHAT) { toSendMsg = new MessageMessage(fromFullJid, to, message, chatType, reciptRequested); } else { toSendMsg = new MessageMessage(fromFullJid, to, message, chatType, chat.muc.nickname, reciptRequested); } // Create a copy for the DB: ChatMessageModel toSendMsgDB = new ChatMessageModel(toSendMsg, chat) { state = toSendMsg is OmemoEncryptedMessage ? MessageState.TO_ENCRYPT : MessageState.SENDING }; // Set the image path and file name: if (toSendMsgDB.isImage) { await DataCache.PrepareImageModelPathAndNameAsync(toSendMsgDB.image); } // Set the chat message id for later identification: toSendMsg.chatMessageId = toSendMsgDB.id; // Update chat last active: chat.lastActive = DateTime.Now; // Update DB: chat.Update(); DataCache.INSTANCE.AddChatMessage(toSendMsgDB, chat); Logger.Info("Added to send message in background"); if (isRunning) { Client client = ConnectionHandler.INSTANCE.GetClient(chat.bareJid).client; if (client is null) { Logger.Error($"Failed to send message from background. Client '{chat.bareJid}' does not exist."); } // Send the message: else if (toSendMsg is OmemoEncryptedMessage toSendOmemoMsg) { await client.xmppClient.sendOmemoMessageAsync(toSendOmemoMsg, chat.bareJid, client.dbAccount.bareJid, client.dbAccount.omemoInfo.trustedKeysOnly, chat.omemoInfo.trustedKeysOnly); } else { await client.xmppClient.SendAsync(toSendMsg); } } else { ToastHelper.ShowWillBeSendLaterToast(chat); } }