예제 #1
0
  /**
   * Handles a message received from the remote party.
   *
   * @param msg The Message object that was received.
   */
  private void doMessageReceived(Message msg) {
    assert (SwingUtilities.isEventDispatchThread()) : "not in UI thread";

    if (msg.getType() == Message.Type.ERROR) {
      JOptionPane.showMessageDialog(
          this,
          msg.getError().getMessage(),
          JavolinApp.getAppName() + ": Error",
          JOptionPane.ERROR_MESSAGE);
    } else if (msg.getType() == Message.Type.HEADLINE) {
      // Do nothing
    } else {
      String jid = msg.getFrom();
      if (jid != null) setUserResource(jid);

      Date date = null;
      PacketExtension ext = msg.getExtension("x", "jabber:x:delay");
      if (ext != null && ext instanceof DelayInformation) {
        date = ((DelayInformation) ext).getStamp();
      }

      mLog.message(mRemoteIdFull, mRemoteNick, msg.getBody(), date);
      Audio.playMessage();
    }
  }
예제 #2
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();
              }
            }
          }
        }
    /**
     * Returns <tt>true</tt> if <tt>packet</tt> is a <tt>Message</tt> and false otherwise.
     *
     * @param packet the packet that we need to check.
     * @return <tt>true</tt> if <tt>packet</tt> is a <tt>Message</tt> and false otherwise.
     */
    public boolean accept(Packet packet) {
      if (!(packet instanceof org.jivesoftware.smack.packet.Message)) return false;

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

      return !msg.getType().equals(org.jivesoftware.smack.packet.Message.Type.groupchat);
    }
예제 #4
0
  @Override
  public void processPacket(Packet packet) {
    Session session;

    Message message = (Message) packet;

    if (message.getType() == Message.Type.chat) {
      String sessionId = message.getFrom();
      String text = message.getBody();

      if (!sessionManager.hasSession(sessionId)) {
        session = sessionManager.createSession(sessionId, this);
        session.setProperty("xmppDebugDestination", sessionId);
        session.setProperty("xmppDestination", sessionId);
      } else {
        session = sessionManager.getSession(sessionId);
      }

      if (text.startsWith("d:")) {
        System.out.println(
            "Setting debug for sessionID (" + sessionId + ") to " + text.substring(2));
        session.setProperty("xmppDebugDestination", text.substring(2));
      }
      if (text.startsWith("D:")) {
        session.setProperty("xmppDebugDestination", "*****@*****.**");
        System.out.println(
            "Setting debug for sessionID (" + sessionId + ") to [email protected]");
      } else {
        session.pushInput(text);
      }
    }
  }
 /** {@inheritDoc} */
 public boolean accept(Packet packet) {
   if (!(packet instanceof Message)) {
     return false;
   } else {
     Message m = (Message) packet;
     if (logger.isDebugEnabled()) {
       logger.debug("Got a message in operation filter " + m.toXML());
     }
     return m.getType().equals(Message.Type.chat) && this.isValidOperation(m);
   }
 }
 @Override
 public boolean accept(Stanza stanza) {
   if (stanza instanceof Message) {
     Message msg = (Message) stanza;
     // All messages from agents are type normal
     if (Message.Type.normal.equals(msg.getType())
         && messagePattern.matcher(msg.getBody()).matches()) {
       return true;
     }
   }
   return false;
 }
예제 #7
0
 @Override
 public void onPacket(ConnectionItem connection, String bareAddress, Packet packet) {
   if (!(connection instanceof AccountItem)) return;
   String account = ((AccountItem) connection).getAccount();
   if (bareAddress == null || !(packet instanceof Message)) return;
   Message message = (Message) packet;
   if (message.getType() != Message.Type.normal && message.getType() != Message.Type.chat) return;
   MUCUser mucUser = MUC.getMUCUserExtension(packet);
   if (mucUser == null || mucUser.getInvite() == null) return;
   RoomChat roomChat = getRoomChat(account, bareAddress);
   if (roomChat == null || !roomChat.getState().inUse()) {
     String inviter = mucUser.getInvite().getFrom();
     if (inviter == null) inviter = bareAddress;
     inviteProvider.add(
         new RoomInvite(
             account,
             bareAddress,
             inviter,
             mucUser.getInvite().getReason(),
             mucUser.getPassword()),
         true);
   }
 }
예제 #8
0
    public void processPacket(Packet packet) throws SmackException.NotConnectedException {
      if (packet instanceof Message) {
        Message message = (Message) packet;
        // 聊天消息
        if (message.getType() == Message.Type.chat) {
          String whoAccountStr = StringUtils.parseBareAddress(message.getFrom());
          String whoNameStr = "";

          // 查询联系人的名称
          Cursor cursor =
              imService
                  .getContentResolver()
                  .query(
                      ContactsProvider.CONTACT_URI,
                      null,
                      ContactsProvider.ContactColumns.ACCOUNT + " = ?",
                      new String[] {whoAccountStr},
                      null);
          if (cursor != null && cursor.moveToFirst()) {
            cursor.moveToPosition(0);
            whoNameStr =
                cursor.getString(cursor.getColumnIndex(ContactsProvider.ContactColumns.NAME));
          }

          String bodyStr = message.getBody();
          String typeStr = "chat";

          // 插入消息
          ContentValues values = new ContentValues();
          values.put(SMSProvider.SMSColumns.BODY, bodyStr);
          values.put(SMSProvider.SMSColumns.TYPE, typeStr);
          values.put(SMSProvider.SMSColumns.TIME, System.currentTimeMillis());

          values.put(SMSProvider.SMSColumns.WHO_ID, whoAccountStr);

          values.put(SMSProvider.SMSColumns.SESSION_ID, whoAccountStr);
          values.put(SMSProvider.SMSColumns.SESSION_NAME, whoNameStr);

          imService.getContentResolver().insert(SMSProvider.SMS_URI, values);
        }
      }
    }
    private void doProcessPacket(Packet packet) {
      final Message message = ((Message) packet);
      if (message.getType() == Message.Type.ERROR) {
        UIUtil.invokeLater(
            () -> {
              String from =
                  (message.getFrom() != null) ? getMsg("from.0.lf", message.getFrom()) : "";
              LOG.warn(
                  getMsg(
                      "jabber.error.text",
                      from,
                      (message.getError() == null ? "N/A" : message.getError().toString())));
            });
        return;
      }

      if (myIgnoreList.isIgnored(packet.getFrom())) {
        return;
      }

      Element element = null;
      for (PacketExtension o : message.getExtensions()) {
        if (o instanceof JDOMExtension) {
          element = ((JDOMExtension) o).getElement();
        }
      }

      if (element != null && !RESPONSE.equals(element.getName())) {
        processAndSendResponse(element, message);
      } else if (element == null && message.getBody() != null) {
        // Some simple Jabber Message
        MessageEvent event =
            EventFactory.createMessageEvent(
                JabberTransport.this, getFrom(message), message.getBody());
        if (message.getThread() != null) {
          myUser2Thread.put(getFrom(message), message.getThread());
        }

        getBroadcaster().fireEvent(event);
      }
    }
예제 #10
0
 /**
  * Instantiates a new message.
  *
  * @param smackMsg the smack msg
  */
 protected Message(final org.jivesoftware.smack.packet.Message smackMsg) {
   this(smackMsg.getTo());
   if (smackMsg.getType().equals(org.jivesoftware.smack.packet.Message.Type.error)) {
     type = MSG_TYPE_ERROR;
   } else {
     type = MSG_TYPE_CHAT;
   }
   from = smackMsg.getFrom();
   if (type == MSG_TYPE_ERROR) {
     final XMPPError er = smackMsg.getError();
     final String msg = er.getMessage();
     if (msg != null) {
       body = msg;
     } else {
       body = er.getCondition();
     }
   } else {
     body = smackMsg.getBody();
     subject = smackMsg.getSubject();
     thread = smackMsg.getThread();
   }
 }
예제 #11
0
 @Override
 protected void assertXmppMessage(Message message) {
   assertEquals(Message.Type.chat, message.getType());
   assertEquals(TEST_MESSAGE, message.getBody());
 }
    /**
     * Handles incoming messages and dispatches whatever events are necessary.
     *
     * @param packet the packet that we need to handle (if it is a message).
     */
    public void processPacket(Packet packet) {
      if (!(packet instanceof org.jivesoftware.smack.packet.Message)) return;

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

      boolean isForwardedSentMessage = false;
      if (msg.getBody() == null) {

        CarbonPacketExtension carbonExt =
            (CarbonPacketExtension) msg.getExtension(CarbonPacketExtension.NAMESPACE);
        if (carbonExt == null) return;

        isForwardedSentMessage =
            (carbonExt.getElementName() == CarbonPacketExtension.SENT_ELEMENT_NAME);
        List<ForwardedPacketExtension> extensions =
            carbonExt.getChildExtensionsOfType(ForwardedPacketExtension.class);
        if (extensions.isEmpty()) return;
        ForwardedPacketExtension forwardedExt = extensions.get(0);
        msg = forwardedExt.getMessage();
        if (msg == null || msg.getBody() == null) return;
      }

      Object multiChatExtension = msg.getExtension("x", "http://jabber.org/protocol/muc#user");

      // its not for us
      if (multiChatExtension != null) return;

      String userFullId = isForwardedSentMessage ? msg.getTo() : msg.getFrom();

      String userBareID = StringUtils.parseBareAddress(userFullId);

      boolean isPrivateMessaging = false;
      ChatRoom privateContactRoom = null;
      OperationSetMultiUserChatJabberImpl mucOpSet =
          (OperationSetMultiUserChatJabberImpl)
              jabberProvider.getOperationSet(OperationSetMultiUserChat.class);
      if (mucOpSet != null) privateContactRoom = mucOpSet.getChatRoom(userBareID);

      if (privateContactRoom != null) {
        isPrivateMessaging = true;
      }

      if (logger.isDebugEnabled()) {
        if (logger.isDebugEnabled())
          logger.debug("Received from " + userBareID + " the message " + msg.toXML());
      }

      Message newMessage = createMessage(msg.getBody(), DEFAULT_MIME_TYPE, msg.getPacketID());

      // check if the message is available in xhtml
      PacketExtension ext = msg.getExtension("http://jabber.org/protocol/xhtml-im");

      if (ext != null) {
        XHTMLExtension xhtmlExt = (XHTMLExtension) ext;

        // parse all bodies
        Iterator<String> bodies = xhtmlExt.getBodies();
        StringBuffer messageBuff = new StringBuffer();
        while (bodies.hasNext()) {
          String body = bodies.next();
          messageBuff.append(body);
        }

        if (messageBuff.length() > 0) {
          // we remove body tags around message cause their
          // end body tag is breaking
          // the visualization as html in the UI
          String receivedMessage =
              messageBuff
                  .toString()
                  // removes body start tag
                  .replaceAll("\\<[bB][oO][dD][yY].*?>", "")
                  // removes body end tag
                  .replaceAll("\\</[bB][oO][dD][yY].*?>", "");

          // for some reason &apos; is not rendered correctly
          // from our ui, lets use its equivalent. Other
          // similar chars(< > & ") seem ok.
          receivedMessage = receivedMessage.replaceAll("&apos;", "&#39;");

          newMessage = createMessage(receivedMessage, HTML_MIME_TYPE, msg.getPacketID());
        }
      }

      PacketExtension correctionExtension = msg.getExtension(MessageCorrectionExtension.NAMESPACE);
      String correctedMessageUID = null;
      if (correctionExtension != null) {
        correctedMessageUID =
            ((MessageCorrectionExtension) correctionExtension).getCorrectedMessageUID();
      }

      Contact sourceContact =
          opSetPersPresence.findContactByID((isPrivateMessaging ? userFullId : userBareID));
      if (msg.getType() == org.jivesoftware.smack.packet.Message.Type.error) {
        // error which is multichat and we don't know about the contact
        // is a muc message error which is missing muc extension
        // and is coming from the room, when we try to send message to
        // room which was deleted or offline on the server
        if (isPrivateMessaging && sourceContact == null) {
          if (privateContactRoom != null) {
            XMPPError error = packet.getError();
            int errorResultCode = ChatRoomMessageDeliveryFailedEvent.UNKNOWN_ERROR;

            if (error != null && error.getCode() == 403) {
              errorResultCode = ChatRoomMessageDeliveryFailedEvent.FORBIDDEN;
            }

            String errorReason = error.getMessage();

            ChatRoomMessageDeliveryFailedEvent evt =
                new ChatRoomMessageDeliveryFailedEvent(
                    privateContactRoom, null, errorResultCode, errorReason, new Date(), newMessage);
            ((ChatRoomJabberImpl) privateContactRoom).fireMessageEvent(evt);
          }

          return;
        }

        if (logger.isInfoEnabled()) logger.info("Message error received from " + userBareID);

        int errorResultCode = MessageDeliveryFailedEvent.UNKNOWN_ERROR;
        if (packet.getError() != null) {
          int errorCode = packet.getError().getCode();

          if (errorCode == 503) {
            org.jivesoftware.smackx.packet.MessageEvent msgEvent =
                (org.jivesoftware.smackx.packet.MessageEvent)
                    packet.getExtension("x", "jabber:x:event");
            if (msgEvent != null && msgEvent.isOffline()) {
              errorResultCode = MessageDeliveryFailedEvent.OFFLINE_MESSAGES_NOT_SUPPORTED;
            }
          }
        }

        if (sourceContact == null) {
          sourceContact = opSetPersPresence.createVolatileContact(userFullId, isPrivateMessaging);
        }

        MessageDeliveryFailedEvent ev =
            new MessageDeliveryFailedEvent(
                newMessage, sourceContact, correctedMessageUID, errorResultCode);

        // ev = messageDeliveryFailedTransform(ev);

        if (ev != null) fireMessageEvent(ev);
        return;
      }
      putJidForAddress(userFullId, msg.getThread());

      // In the second condition we filter all group chat messages,
      // because they are managed by the multi user chat operation set.
      if (sourceContact == null) {
        if (logger.isDebugEnabled())
          logger.debug("received a message from an unknown contact: " + userBareID);
        // create the volatile contact
        sourceContact = opSetPersPresence.createVolatileContact(userFullId, isPrivateMessaging);
      }

      Date timestamp = new Date();
      // Check for XEP-0091 timestamp (deprecated)
      PacketExtension delay = msg.getExtension("x", "jabber:x:delay");
      if (delay != null && delay instanceof DelayInformation) {
        timestamp = ((DelayInformation) delay).getStamp();
      }
      // check for XEP-0203 timestamp
      delay = msg.getExtension("delay", "urn:xmpp:delay");
      if (delay != null && delay instanceof DelayInfo) {
        timestamp = ((DelayInfo) delay).getStamp();
      }

      ContactResource resource = ((ContactJabberImpl) sourceContact).getResourceFromJid(userFullId);

      EventObject msgEvt = null;
      if (!isForwardedSentMessage)
        msgEvt =
            new MessageReceivedEvent(
                newMessage,
                sourceContact,
                resource,
                timestamp,
                correctedMessageUID,
                isPrivateMessaging,
                privateContactRoom);
      else msgEvt = new MessageDeliveredEvent(newMessage, sourceContact, timestamp);
      // msgReceivedEvt = messageReceivedTransform(msgReceivedEvt);
      if (msgEvt != null) fireMessageEvent(msgEvt);
    }
  /*
   * Handle a single smack packet, discarding anything but Message.
   * @param packet The smack packet.
   * (non-Javadoc)
   * @see org.jivesoftware.smack.PacketListener#processPacket(org.jivesoftware.smack.packet.Packet)
   */
  @Override
  public void processPacket(Packet packet) {

    Log.i("processPacket", packet.toXML());
    if (packet instanceof Presence) {

      double inLat = 0, inLong = 0;
      boolean isMUC = false, isGEO = false;

      Presence presence = (Presence) packet;

      // In a MUC, the "FROM" is the Resource
      String presenceFrom = StringUtils.parseResource(presence.getFrom());
      String presenceTo = StringUtils.parseName(presence.getTo());

      // if presence packet is from yourself, just bail
      if (presenceFrom.equals(presenceTo)) return;

      for (PacketExtension extension : presence.getExtensions()) {
        if (extension instanceof GeoLoc) {
          GeoLoc loc = (GeoLoc) extension;

          inLat = loc.getLat();
          inLong = loc.getLon();

          isGEO = true;

          Log.d("CNL", "ERIK: GEOLOC EXTENSION FOUND, LAT: " + inLat);
        }
        if (extension instanceof MUCUser) {
          // MUCUser muc = (MUCUser) extension;   no need to create this object
          isMUC = true;

          Log.d("CNL", "ERIK: MUC EXTENSION FOUND, presence type=" + presence.getType());
        }
      }

      //  If a MUC available presence packet comes in, add/update database
      if (isMUC == true && presence.getType().toString().equals("available") && isGEO == true) {

        updateDatabase(presenceFrom, inLat, inLong, null);
      }

      // if a MUC Unavailable presence packet comes in, remove user from database
      else if (isMUC == true && presence.getType().toString().equals("unavailable")) {

        if (this.database.delete("user_info", "name='" + presenceFrom + "'", null) > 0) {
          Log.d("CNL", "ERIK: DATABASE UPDATED, USER " + presenceFrom + " DELETED");
        } else Log.d("CNL", "ERIK: DATABASE SEARCHED, USER " + presenceFrom + " NOT FOUND");
      }
    }

    if (packet instanceof IQ) {
      IQ iq = (IQ) packet;
      Log.d("CNL", "ERIK: IQ PACKET RECEIVED: " + iq.getExtensions());
    }

    if (packet instanceof Message) {
      Message msg = (Message) packet;
      String text = msg.getBody();

      if (text == null || text.trim().length() == 0) {
        Log.d("CNL", "ERIK: MESSAGE PACKET LACKS A MESSAGE!!!");
        return;
      }

      // Extract name
      String messageFrom = StringUtils.parseResource(msg.getFrom());

      // Extract lat and lon from message
      double inLat = getLat(msg);
      double inLon = getLon(msg);
      Boolean isEmergency = null;
      if (text.startsWith(this.context.getString(R.string.emergency_message))) {
        isEmergency = Boolean.TRUE;
      } else if (text.startsWith(this.context.getString(R.string.cancel_message))) {
        isEmergency = Boolean.FALSE;
      }

      Log.i("CNL", "recovered name=[" + messageFrom + "], lat/lon=" + inLat + "," + inLon);

      updateDatabase(messageFrom, inLat, inLon, isEmergency);

      String bareFrom = XMPPUtils.getBareJid(msg.getFrom());
      String msgFrom = StringUtils.parseResource(msg.getFrom());
      String bareTo = XMPPUtils.getBareJid(msg.getTo());
      String msgTo = StringUtils.parseName(msg.getTo());

      if (msg.getType().toString().equals("groupchat")) {
        Log.d(
            "CNL",
            "ERIK: MUC MESSAGE PACKET RECEIVED, CONTAINS EXTENSIONS: " + msg.getExtensions());
        if (msgFrom.equals(msgTo)) return;

        // Picture receiving code here.............................!!!!!!!!!!

        for (PacketExtension extension : msg.getExtensions()) {
          if (extension instanceof DataPacketExtension) {
            DataPacketExtension data = (DataPacketExtension) extension;

            byte[] imageBytes = data.getDecodedData();
            String imagePath = Environment.getExternalStorageDirectory() + "/mmmc/";

            // String imageName = text;
            File f = new File(imagePath, text);
            OutputStream out = null;

            try {
              out = new BufferedOutputStream(new FileOutputStream(f));
              out.write(imageBytes);
            } catch (IOException ioe) {
              ioe.printStackTrace();
            } finally {
              if (out != null) {
                try {
                  out.close();
                } catch (IOException e) {
                  e.printStackTrace();
                }
              }
            }

            // Log.d("CNL", "ERIK: MUC EXTENSION FOUND");
            ContentValues values = new ContentValues();
            values.put("ts", System.currentTimeMillis());
            values.put("jid", bareFrom);

            // don't put who it's from, put the resource it came from (user in a MUC)
            values.put("src", msgFrom);

            values.put("dst", msg.getTo());
            values.put("via", bareTo);
            values.put("msg", "Picture received: " + text.trim());
            this.database.insert("msg", "_id", values);

            Log.d("CNL", "ERIK: DATA EXTENSION FOUND, IMAGE SAVED");
            return;
          }
        }

        // Log.d("CNL", "ERIK: MUC EXTENSION FOUND");

        // Insert new message into database
        ContentValues values = new ContentValues();
        values.put("ts", System.currentTimeMillis());
        values.put("jid", bareFrom);

        // don't put who it's from, put the resource it came from (user in a MUC)
        values.put("src", msgFrom);

        values.put("dst", msg.getTo());
        values.put("via", bareTo);
        values.put("msg", text.trim());
        this.database.insert("msg", "_id", values);
      } else Log.d("CNL", "ERIK: NON-MUC MESSAGE PACKET RECEIVED: " + bareFrom);

      Builder builder = new Uri.Builder();
      builder.scheme("content");
      builder.authority("jabber-chat-db");
      builder.appendPath(bareTo);
      builder.appendPath(bareFrom);
      this.context.getContentResolver().notifyChange(builder.build(), null);
      setNotification(bareFrom, bareTo);
    }
  }