Example #1
0
        public void processMessage(Chat chat, Message message) {
          if ((message.getBody() != null) && (!message.getType().equals(Message.Type.error))) {
            if (!cipher) {

              Log.i(TAG, "Recibido mensaje plano: " + message.getBody());
              listMessages.add(message);
              refreshAdapter();
              myListView.smoothScrollToPosition(adapter.getCount() - 1);
            } else {

              try {
                PrivateKey pk =
                    RSA.getPrivateKeyDecryted(KeyStore.getInstance().getPk(), passPhrase);
                String decodedMessage = RSA.decipher(message.getBody(), pk);
                Log.i(TAG, "Recibido mensaje cifrado: " + decodedMessage);

                Message m = new Message();
                m.setFrom(message.getFrom());
                m.setTo(message.getTo());

                m.setBody(decodedMessage);
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                m.setSubject(sdf.format(new Date()));
                listMessages.add(m);
                refreshAdapter();
                myListView.smoothScrollToPosition(adapter.getCount() - 1);

              } catch (Exception e) {
                Log.d(TAG, "PETO AL DESCIFRAR");
                e.printStackTrace();
              }
            }
          }
        }
Example #2
0
 public void addToTranscript(String to, String from, String body, Date date) {
   final Message newMessage = new Message();
   newMessage.setTo(to);
   newMessage.setFrom(from);
   newMessage.setBody(body);
   newMessage.setProperty("date", date);
   transcript.add(newMessage);
 }
Example #3
0
  public void send(View view) {
    Message message = new Message(destJid);
    EditText editText = (EditText) findViewById(R.id.textInput);
    String plainText = editText.getText().toString();
    editText.setText("");

    message.setFrom(myJid);
    message.setTo(destJid);

    Message m = new Message();
    m.setFrom(myJid);
    m.setBody(plainText);
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    m.setSubject(sdf.format(new Date()));
    listMessages.add(m);
    refreshAdapter();
    myListView.smoothScrollToPosition(adapter.getCount() - 1);

    if (!cipher) {
      try {
        message.setBody(plainText);
        chatMan.getChat().sendMessage(message);
        Log.d(TAG, "Enviando: " + message.getBody());

      } catch (XMPPException e) {
        Log.d(TAG, "ERROR al enviar mensaje");
      }
    } else {
      try {
        String encodedMessage = RSA.cipher(plainText, cert.getPublicKey());
        message.setBody(encodedMessage);
        chatMan.getChat().sendMessage(message);
        Log.d(TAG, "Enviando cifrado: " + message.getBody() + " " + plainText);

      } catch (Exception e) {
        Log.d(TAG, "PETO ENVIANDO CIFRADOOOO");
        e.printStackTrace();
      }
    }
  }
Example #4
0
 public void addToTranscript(Message message, boolean updateDate) {
   final Message newMessage = new Message();
   newMessage.setTo(message.getTo());
   newMessage.setFrom(message.getFrom());
   newMessage.setBody(message.getBody());
   newMessage.setProperty("date", new Date());
   transcript.add(newMessage);
   if (updateDate && transcriptWindow.getLastUpdated() != null)
     notificationLabel.setText(
         "las msg received at "
             + ChatsyManager.DATE_SECOND_FORMATTER.format(transcriptWindow.getLastUpdated()));
   scrollToBottom();
 }
Example #5
0
  /**
   * Sends a message to the appropriate jid. The message is automatically added to the transcript.
   *
   * @param message the message to send.
   */
  public void sendMessage(Message message) {
    lastActivity = System.currentTimeMillis();

    try {
      getTranscriptWindow()
          .insertMessage(getNickname(), message, ChatManager.TO_COLOR, Color.white);
      getChatInputEditor().selectAll();

      getTranscriptWindow().validate();
      getTranscriptWindow().repaint();
      getChatInputEditor().clear();
    } catch (Exception ex) {
      Log.error("Error sending message", ex);
    }

    // Before sending message, let's add our full jid for full verification
    message.setType(Message.Type.chat);
    message.setTo(participantJID);
    message.setFrom(SparkManager.getSessionManager().getJID());

    // Notify users that message has been sent
    fireMessageSent(message);

    addToTranscript(message, false);

    getChatInputEditor().setCaretPosition(0);
    getChatInputEditor().requestFocusInWindow();
    scrollToBottom();

    // No need to request displayed or delivered as we aren't doing anything
    // with this
    // information.
    MessageEventManager.addNotificationsRequests(message, true, false, false, true);

    // Send the message that contains the notifications request
    try {
      fireOutgoingMessageSending(message);
      SparkManager.getConnection().sendPacket(message);
    } catch (Exception ex) {
      Log.error("Error sending message", ex);
    }
  }
  /**
   * 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;
  }
  /**
   * 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);
  }
  /**
   * 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;
  }