private static Message rawMessage(MessageContent content, Chat chat, boolean encrypted) {
    Message smackMessage = new Message();

    // text
    String text = content.getPlainText();
    if (!text.isEmpty()) smackMessage.setBody(content.getPlainText());

    // attachment
    MessageContent.Attachment att = content.getAttachment().orElse(null);
    if (att != null) {
      OutOfBandData oobData =
          new OutOfBandData(att.getURL().toString(), att.getMimeType(), att.getLength(), encrypted);
      smackMessage.addExtension(oobData);

      MessageContent.Preview preview = content.getPreview().orElse(null);
      if (preview != null) {
        String data = EncodingUtils.bytesToBase64(preview.getData());
        BitsOfBinary bob = new BitsOfBinary(preview.getMimeType(), data);
        smackMessage.addExtension(bob);
      }
    }

    // group command
    if (chat instanceof KonGroupChat) {
      KonGroupChat groupChat = (KonGroupChat) chat;
      KonGroupData gid = groupChat.getGroupData();
      MessageContent.GroupCommand groupCommand = content.getGroupCommand().orElse(null);
      smackMessage.addExtension(
          groupCommand != null
              ? ClientUtils.groupCommandToGroupExtension(groupChat, groupCommand)
              : new GroupExtension(gid.id, gid.owner.string()));
    }

    return smackMessage;
  }
Ejemplo n.º 2
0
  /**
   * @see net.sf.kraken.session.TransportSession#sendChatState(org.xmpp.packet.JID,
   *     net.sf.kraken.type.ChatStateType)
   */
  @Override
  public void sendChatState(JID jid, ChatStateType chatState) {
    final Presence presence = conn.getRoster().getPresence(jid.toString());
    if (presence == null || presence.getType().equals(Presence.Type.unavailable)) {
      // don't send chat state to contacts that are offline.
      return;
    }
    Chat chat = conn.getChatManager().createChat(getTransport().convertJIDToID(jid), listener);
    try {
      ChatState state = ChatState.active;
      switch (chatState) {
        case active:
          state = ChatState.active;
          break;
        case composing:
          state = ChatState.composing;
          break;
        case paused:
          state = ChatState.paused;
          break;
        case inactive:
          state = ChatState.inactive;
          break;
        case gone:
          state = ChatState.gone;
          break;
      }

      Message message = new Message();
      message.addExtension(new ChatStateExtension(state));
      chat.sendMessage(message);
    } catch (XMPPException e) {
      // Ignore
    }
  }
Ejemplo n.º 3
0
        public void processMessage(Message message)
        {
            for (Chat chat = chatManager.getThreadChat(message.getThread()); chat == null || !updateChatState(chat, ChatState.active);)
            {
                return;
            }

            message.addExtension(new ChatStateExtension(ChatState.active));
        }
Ejemplo n.º 4
0
 private void sendFeature(String account, String user, String session, Feature feature) {
   Message message = new Message(user, Message.Type.normal);
   message.setThread(session);
   message.addExtension(feature);
   try {
     ConnectionManager.getInstance().sendStanza(account, message);
   } catch (NetworkException e) {
   }
 }
Ejemplo n.º 5
0
  public void sendOfflineMessages() {
    Cursor cursor =
        contentResolver.query(
            ChatProvider.CONTENT_URI, SEND_OFFLINE_PROJECTION, SEND_OFFLINE_SELECTION, null, null);
    final int ID = cursor.getColumnIndexOrThrow(ChatConstants._ID);
    final int JABBER_ID = cursor.getColumnIndexOrThrow(ChatConstants.JID);
    final int MESSAGE = cursor.getColumnIndexOrThrow(ChatConstants.MESSAGE);
    final int DATE = cursor.getColumnIndexOrThrow(ChatConstants.DATE);
    final int PACKET_ID = cursor.getColumnIndexOrThrow(ChatConstants.PACKET_ID);

    ContentValues mark_sent = new ContentValues();
    mark_sent.put(ChatConstants.DELIVERY_STATUS, ChatConstants.DS_SENT_OR_READ);
    while (cursor.moveToNext()) {
      int id = cursor.getInt(ID);
      String toJID = cursor.getString(JABBER_ID);
      String message = cursor.getString(MESSAGE);
      String packetID = cursor.getString(PACKET_ID);
      long dateTs = cursor.getLong(DATE);
      final Message newMsg = new Message(toJID, Message.Type.chat);
      newMsg.setBody(message);
      DelayInformation delay = new DelayInformation(new Date(dateTs));
      newMsg.addExtension(delay);
      newMsg.addExtension(new DelayInfo(delay));
      newMsg.addExtension(new DeliveryReceiptRequest());
      if ((packetID != null) && (packetID.length() > 0)) {
        newMsg.setPacketID(packetID);
      } else {
        packetID = newMsg.getPacketID();
        mark_sent.put(ChatConstants.PACKET_ID, packetID);
      }
      Uri rowuri =
          Uri.parse(
              Constant.CONTENT_PATH
                  + ChatProvider.AUTHORITY
                  + "/"
                  + ChatProvider.TABLE_NAME
                  + "/"
                  + id);
      contentResolver.update(rowuri, mark_sent, null, null);
      extXMPPConnection.sendPacket(newMsg);
    }
    cursor.close();
  }
  /**
   * Sends a roster to userID. All the entries of the roster will be sent to the target user.
   *
   * @param roster the roster to send
   * @param targetUserID the user that will receive the roster entries
   */
  public void send(Roster roster, String targetUserID) {
    // Create a new message to send the roster
    Message msg = new Message(targetUserID);
    // Create a RosterExchange Package and add it to the message
    RosterExchange rosterExchange = new RosterExchange(roster);
    msg.addExtension(rosterExchange);

    // Send the message that contains the roster
    con.sendPacket(msg);
  }
Ejemplo n.º 7
0
 /**
  * Adds an XHTML body to the message.
  *
  * @param message the message that will receive the XHTML body
  * @param body the string to add as an XHTML body to the message
  */
 public static void addBody(Message message, String body) {
   XHTMLExtension xhtmlExtension = (XHTMLExtension) message.getExtension("html", namespace);
   if (xhtmlExtension == null) {
     // Create an XHTMLExtension and add it to the message
     xhtmlExtension = new XHTMLExtension();
     message.addExtension(xhtmlExtension);
   }
   // Add the required bodies to the message
   xhtmlExtension.addBody(body);
 }
  private Message doSendMessage(XmlMessage xmlMessage, User user, String threadId) {
    Element element = new Element(xmlMessage.getTagName(), xmlMessage.getTagNamespace());
    xmlMessage.fillRequest(element);

    Message message = createBaseMessage(user, element.getText());
    message.setThread(threadId);
    message.addExtension(new JDOMExtension(element));
    myFacade.getConnection().sendPacket(message);

    return message;
  }
 private void processAndSendResponse(Element element, Message message) {
   Element response = new Element(RESPONSE, Transport.NAMESPACE);
   XmlResponseProvider provider = XmlResponseProvider.getProvider(element, getBroadcaster());
   if (provider.processAndFillResponse(
       response, element, JabberTransport.this, getFrom(message))) {
     Message responseMessage = new Message(getFrom(message));
     responseMessage.addExtension(new JDOMExtension(response));
     responseMessage.setThread(message.getThread());
     myFacade.getConnection().sendPacket(responseMessage);
   }
 }
Ejemplo n.º 10
0
 /**
  * @see net.sf.kraken.session.TransportSession#sendBuzzNotification(org.xmpp.packet.JID, String)
  */
 @Override
 public void sendBuzzNotification(JID jid, String message) {
   Chat chat = conn.getChatManager().createChat(getTransport().convertJIDToID(jid), listener);
   try {
     Message m = new Message();
     m.setTo(getTransport().convertJIDToID(jid));
     m.addExtension(new BuzzExtension());
     chat.sendMessage(m);
   } catch (XMPPException e) {
     // Ignore
   }
 }
Ejemplo n.º 11
0
 public void sendOfflineMessages() {
   Cursor cursor =
       mContentResolver.query(
           ChatProvider.CONTENT_URI, SEND_OFFLINE_PROJECTION, SEND_OFFLINE_SELECTION, null, null);
   final int _ID_COL = cursor.getColumnIndexOrThrow(ChatConstants._ID);
   final int JID_COL = cursor.getColumnIndexOrThrow(ChatConstants.JID);
   final int MSG_COL = cursor.getColumnIndexOrThrow(ChatConstants.MESSAGE);
   final int TS_COL = cursor.getColumnIndexOrThrow(ChatConstants.DATE);
   final int PACKETID_COL = cursor.getColumnIndexOrThrow(ChatConstants.PACKET_ID);
   ContentValues mark_sent = new ContentValues();
   mark_sent.put(ChatConstants.DELIVERY_STATUS, ChatConstants.DS_SENT_OR_READ);
   while (cursor.moveToNext()) {
     int _id = cursor.getInt(_ID_COL);
     String toJID = cursor.getString(JID_COL);
     String message = cursor.getString(MSG_COL);
     String packetID = cursor.getString(PACKETID_COL);
     long ts = cursor.getLong(TS_COL);
     Log.d(TAG, "sendOfflineMessages: " + toJID + " > " + message);
     final Message newMessage = new Message(toJID, Message.Type.chat);
     newMessage.setBody(message);
     DelayInformation delay = new DelayInformation(new Date(ts));
     newMessage.addExtension(delay);
     newMessage.addExtension(new DelayInfo(delay));
     newMessage.addExtension(new DeliveryReceiptRequest());
     if ((packetID != null) && (packetID.length() > 0)) {
       newMessage.setPacketID(packetID);
     } else {
       packetID = newMessage.getPacketID();
       mark_sent.put(ChatConstants.PACKET_ID, packetID);
     }
     Uri rowuri =
         Uri.parse(
             "content://" + ChatProvider.AUTHORITY + "/" + ChatProvider.TABLE_NAME + "/" + _id);
     mContentResolver.update(rowuri, mark_sent, null, null);
     mXMPPConnection.sendPacket(
         newMessage); // must be after marking delivered, otherwise it may override the
     // SendFailListener
   }
   cursor.close();
 }
Ejemplo n.º 12
0
  /**
   * Sends a roster group to userID. All the entries of the group will be sent to the target user.
   *
   * @param rosterGroup the roster group to send
   * @param targetUserID the user that will receive the roster entries
   */
  public void send(RosterGroup rosterGroup, String targetUserID) {
    // Create a new message to send the roster
    Message msg = new Message(targetUserID);
    // Create a RosterExchange Package and add it to the message
    RosterExchange rosterExchange = new RosterExchange();
    for (RosterEntry entry : rosterGroup.getEntries()) {
      rosterExchange.addRosterEntry(entry);
    }
    msg.addExtension(rosterExchange);

    // Send the message that contains the roster
    con.sendPacket(msg);
  }
Ejemplo n.º 13
0
 /**
  * Sends invitation.
  *
  * @param account
  * @param room
  * @param user
  * @throws NetworkException
  */
 public void invite(String account, String room, String user) throws NetworkException {
   RoomChat roomChat = getRoomChat(account, room);
   if (roomChat == null || roomChat.getState() != RoomState.available) {
     Application.getInstance().onError(R.string.NOT_CONNECTED);
     return;
   }
   Message message = new Message(room);
   MUCUser mucUser = new MUCUser();
   MUCUser.Invite invite = new MUCUser.Invite();
   invite.setTo(user);
   invite.setReason("");
   mucUser.setInvite(invite);
   message.addExtension(mucUser);
   ConnectionManager.getInstance().sendPacket(account, message);
   roomChat.putInvite(message.getPacketID(), user);
   roomChat.newAction(roomChat.getNickname(), user, ChatAction.invite_sent);
 }
Ejemplo n.º 14
0
 private void checkEvents(String from, String packetID, MessageEvent messageEvent) {
   if (messageEvent.isDelivered() || messageEvent.isDisplayed()) {
     // Create the message to send
     Message msg = new Message(from);
     // Create a MessageEvent Package and add it to the message
     MessageEvent event = new MessageEvent();
     if (messageEvent.isDelivered()) {
       event.setDelivered(true);
     }
     if (messageEvent.isDisplayed()) {
       event.setDisplayed(true);
     }
     event.setPacketID(packetID);
     msg.addExtension(event);
     // Send the packet
     SparkManager.getConnection().sendPacket(msg);
   }
 }
  /**
   * Joining a Core to an Interest Group
   *
   * @param coreName name of the core to add to the interest group
   * @param uuid identifier for the interest group
   * @param name human-readable name of the interest group
   * @param owningJID JID of the core that owns the interest group
   * @return
   */
  public static Message sendUpdateToOwner(
      String coreName, String uuid, String from, String topic, String contents) {

    StringBuffer sb = new StringBuffer();
    ArbitraryPacketExtension ext = new ArbitraryPacketExtension(ELEMENT_NAME, NAMESPACE);
    Message msg = new Message();
    msg.setTo("InterestManager@" + coreName + "/manager");
    msg.setFrom(from);

    sb.append("<" + ELEMENT_NAME + " xmlns='" + NAMESPACE + "'>");
    sb.append("<uuid>" + uuid + "</uuid>");
    sb.append("<topic>" + topic + "</topic>");
    sb.append("<interestgroupmgmt_content>");
    sb.append(contents);
    sb.append("</interestgroupmgmt_content>");
    sb.append("</" + ELEMENT_NAME + ">");

    ext.setXML(sb.toString());
    msg.addExtension(ext);

    return msg;
  }
Ejemplo n.º 16
0
 public void sendMessage(String toJID, String message) {
   final Message newMessage = new Message(toJID, Message.Type.chat);
   newMessage.setBody(message);
   newMessage.addExtension(new DeliveryReceiptRequest());
   if (isAuthenticated()) {
     addChatMessageToDB(
         ChatConstants.OUTGOING,
         toJID,
         message,
         ChatConstants.DS_SENT_OR_READ,
         System.currentTimeMillis(),
         newMessage.getPacketID());
     extXMPPConnection.sendPacket(newMessage);
   } else {
     addChatMessageToDB(
         ChatConstants.OUTGOING,
         toJID,
         message,
         ChatConstants.DS_NEW,
         System.currentTimeMillis(),
         newMessage.getPacketID());
   }
 }
Ejemplo n.º 17
0
 public void sendReceipt(String toJID, String id) {
   Log.d(TAG, "sending XEP-0184 ack to " + toJID + " id=" + id);
   final Message ack = new Message(toJID, Message.Type.normal);
   ack.addExtension(new DeliveryReceipt(id));
   mXMPPConnection.sendPacket(ack);
 }
 /**
  * Mark a message as "private", so it will not be carbon-copied.
  *
  * @param msg Message object to mark private
  * @deprecated use {@link Private#addTo(Message)}
  */
 @Deprecated
 public static void disableCarbons(Message msg) {
   msg.addExtension(Private.INSTANCE);
 }
Ejemplo n.º 19
0
 /**
  * Mark a message as "private", so it will not be carbon-copied.
  *
  * @param msg Message object to mark private
  */
 public static void disableCarbons(Message msg) {
   msg.addExtension(new CarbonExtension.Private());
 }
  boolean sendMessage(OutMessage message, boolean sendChatState) {
    // check for correct receipt status and reset it
    KonMessage.Status status = message.getStatus();
    assert status == KonMessage.Status.PENDING || status == KonMessage.Status.ERROR;
    message.setStatus(KonMessage.Status.PENDING);

    if (!mClient.isConnected()) {
      LOGGER.info("not sending message(s), not connected");
      return false;
    }

    MessageContent content = message.getContent();
    MessageContent.Attachment att = content.getAttachment().orElse(null);
    if (att != null && !att.hasURL()) {
      LOGGER.warning("attachment not uploaded");
      message.setStatus(KonMessage.Status.ERROR);
      return false;
    }

    boolean encrypted =
        message.getCoderStatus().getEncryption() != Coder.Encryption.NOT
            || message.getCoderStatus().getSigning() != Coder.Signing.NOT;

    Chat chat = message.getChat();

    Message protoMessage = encrypted ? new Message() : rawMessage(content, chat, false);

    protoMessage.setType(Message.Type.chat);
    protoMessage.setStanzaId(message.getXMPPID());
    String threadID = chat.getXMPPID();
    if (!threadID.isEmpty()) protoMessage.setThread(threadID);

    // extensions

    // TODO with group chat? (for muc "NOT RECOMMENDED")
    if (!chat.isGroupChat()) protoMessage.addExtension(new DeliveryReceiptRequest());

    if (sendChatState) protoMessage.addExtension(new ChatStateExtension(ChatState.active));

    if (encrypted) {
      byte[] encryptedData =
          content.isComplex() || chat.isGroupChat()
              ? Coder.encryptStanza(message, rawMessage(content, chat, true).toXML().toString())
                  .orElse(null)
              : Coder.encryptMessage(message).orElse(null);
      // check also for security errors just to be sure
      if (encryptedData == null || !message.getCoderStatus().getErrors().isEmpty()) {
        LOGGER.warning("encryption failed");
        message.setStatus(KonMessage.Status.ERROR);
        mControl.handleSecurityErrors(message);
        return false;
      }
      protoMessage.addExtension(new E2EEncryption(encryptedData));
    }

    // transmission specific
    Transmission[] transmissions = message.getTransmissions();
    ArrayList<Message> sendMessages = new ArrayList<>(transmissions.length);
    for (Transmission transmission : message.getTransmissions()) {
      Message sendMessage = protoMessage.clone();
      JID to = transmission.getJID();
      if (!to.isValid()) {
        LOGGER.warning("invalid JID: " + to);
        return false;
      }
      sendMessage.setTo(to.string());
      sendMessages.add(sendMessage);
    }

    return mClient.sendPackets(sendMessages.toArray(new Message[0]));
  }
Ejemplo n.º 21
0
 /**
  * Marks a message "private", so that it will not be carbon-copied, by adding private packet
  * extension to the message.
  *
  * @param message the message to add the private extension to
  */
 public static void addTo(Message message) {
   message.addExtension(INSTANCE);
 }
Ejemplo n.º 22
0
 public Packet toPacket() {
   Message message = new Message();
   message.addExtension(this);
   return message;
 }
Ejemplo n.º 23
0
 public void sendReceipt(String toJID, String id) {
   final Message ack = new Message(toJID, Message.Type.normal);
   ack.addExtension(new DeliveryReceipt(id));
   extXMPPConnection.sendPacket(ack);
 }
Ejemplo n.º 24
0
  /**
   * Parses a message packet.
   *
   * @param parser the XML parser, positioned at the start of a message packet.
   * @return a Message packet.
   * @throws Exception if an exception occurs while parsing the packet.
   */
  public static Packet parseMessage(XmlPullParser parser) throws Exception {
    Message message = new Message();
    String id = parser.getAttributeValue("", "id");
    message.setPacketID(id == null ? Packet.ID_NOT_AVAILABLE : id);
    message.setTo(parser.getAttributeValue("", "to"));
    message.setFrom(parser.getAttributeValue("", "from"));
    message.setType(Message.Type.fromString(parser.getAttributeValue("", "type")));
    String language = getLanguageAttribute(parser);

    // determine message's default language
    String defaultLanguage = null;
    if (language != null && !"".equals(language.trim())) {
      message.setLanguage(language);
      defaultLanguage = language;
    } else {
      defaultLanguage = Packet.getDefaultLanguage();
    }

    // Parse sub-elements. We include extra logic to make sure the values
    // are only read once. This is because it's possible for the names to appear
    // in arbitrary sub-elements.
    boolean done = false;
    String thread = null;
    Map<String, Object> properties = null;
    while (!done) {
      int eventType = parser.next();
      if (eventType == XmlPullParser.START_TAG) {
        String elementName = parser.getName();
        String namespace = parser.getNamespace();
        if (elementName.equals("subject")) {
          String xmlLang = getLanguageAttribute(parser);
          if (xmlLang == null) {
            xmlLang = defaultLanguage;
          }

          String subject = parseContent(parser);

          if (message.getSubject(xmlLang) == null) {
            message.addSubject(xmlLang, subject);
          }
        } else if (elementName.equals("body")) {
          String xmlLang = getLanguageAttribute(parser);
          if (xmlLang == null) {
            xmlLang = defaultLanguage;
          }

          String body = parseContent(parser);

          if (message.getBody(xmlLang) == null) {
            message.addBody(xmlLang, body);
          }
        } else if (elementName.equals("thread")) {
          if (thread == null) {
            thread = parser.nextText();
          }
        } else if (elementName.equals("error")) {
          message.setError(parseError(parser));
        } else if (elementName.equals("properties") && namespace.equals(PROPERTIES_NAMESPACE)) {
          properties = parseProperties(parser);
        }
        // Otherwise, it must be a packet extension.
        else {
          message.addExtension(
              PacketParserUtils.parsePacketExtension(elementName, namespace, parser));
        }
      } else if (eventType == XmlPullParser.END_TAG) {
        if (parser.getName().equals("message")) {
          done = true;
        }
      }
    }

    message.setThread(thread);
    // Set packet properties.
    if (properties != null) {
      for (String name : properties.keySet()) {
        message.setProperty(name, properties.get(name));
      }
    }
    return message;
  }
  /**
   * Helper function used to send a message to a contact, with the given extensions attached.
   *
   * @param to The contact to send the message to.
   * @param toResource The resource to send the message to or null if no resource has been specified
   * @param message The message to send.
   * @param extensions The XMPP extensions that should be attached to the message before sending.
   * @return The MessageDeliveryEvent that resulted after attempting to send this message, so the
   *     calling function can modify it if needed.
   */
  private MessageDeliveredEvent sendMessage(
      Contact to, ContactResource toResource, Message message, PacketExtension[] extensions) {
    if (!(to instanceof ContactJabberImpl))
      throw new IllegalArgumentException("The specified contact is not a Jabber contact." + to);

    assertConnected();

    org.jivesoftware.smack.packet.Message msg = new org.jivesoftware.smack.packet.Message();

    String toJID = null;

    if (toResource != null) {
      if (toResource.equals(ContactResource.BASE_RESOURCE)) {
        toJID = to.getAddress();
      } else toJID = ((ContactResourceJabberImpl) toResource).getFullJid();
    }

    if (toJID == null) {
      toJID = to.getAddress();
    }

    msg.setPacketID(message.getMessageUID());
    msg.setTo(toJID);

    for (PacketExtension ext : extensions) {
      msg.addExtension(ext);
    }

    if (logger.isTraceEnabled())
      logger.trace("Will send a message to:" + toJID + " chat.jid=" + toJID);

    MessageDeliveredEvent msgDeliveryPendingEvt =
        new MessageDeliveredEvent(message, to, toResource);

    MessageDeliveredEvent[] transformedEvents =
        messageDeliveryPendingTransform(msgDeliveryPendingEvt);

    if (transformedEvents == null || transformedEvents.length == 0) return null;

    for (MessageDeliveredEvent event : transformedEvents) {
      String content = event.getSourceMessage().getContent();

      if (message.getContentType().equals(HTML_MIME_TYPE)) {
        msg.setBody(Html2Text.extractText(content));

        // Check if the other user supports XHTML messages
        // make sure we use our discovery manager as it caches calls
        if (jabberProvider.isFeatureListSupported(toJID, HTML_NAMESPACE)) {
          // Add the XHTML text to the message
          XHTMLManager.addBody(msg, OPEN_BODY_TAG + content + CLOSE_BODY_TAG);
        }
      } else {
        // this is plain text so keep it as it is.
        msg.setBody(content);
      }

      // msg.addExtension(new Version());

      if (event.isMessageEncrypted() && isCarbonEnabled) {
        msg.addExtension(new CarbonPacketExtension.PrivateExtension());
      }

      MessageEventManager.addNotificationsRequests(msg, true, false, false, true);

      String threadID = getThreadIDForAddress(toJID);
      if (threadID == null) threadID = nextThreadID();

      msg.setThread(threadID);
      msg.setType(org.jivesoftware.smack.packet.Message.Type.chat);
      msg.setFrom(jabberProvider.getConnection().getUser());

      jabberProvider.getConnection().sendPacket(msg);

      putJidForAddress(toJID, threadID);
    }

    return new MessageDeliveredEvent(message, to, toResource);
  }