public void updateUser(Presence presence) {
   boolean newUser = true;
   Contact removeC = null;
   for (Contact c : contactList) {
     if (c.getRosterEntry().getUser().equals(StringUtils.parseBareAddress(presence.getFrom()))) {
       newUser = false;
       if (!(presence.isAvailable() || presence.isAway())) {
         removeC = c;
       }
       break;
     }
   }
   if (removeC != null) {
     contactList.remove(removeC);
   }
   if (newUser) {
     RosterEntry re = roster.getEntry(StringUtils.parseBareAddress(presence.getFrom()));
     Contact c = new Contact();
     if (re.getName() == null || re.getName().trim().equals("")) c.setName(re.getUser());
     else c.setName(re.getName());
     c.setStatus(presence.getStatus());
     c.setRosterEntry(re);
     contactList.add(c);
   }
 }
Example #2
0
  private void loadHistory() {
    // Add VCard Panel
    final VCardPanel vcardPanel = new VCardPanel(participantJID);

    vcardPanel.setPreferredSize(new Dimension(10, 71));
    vcardPanel.setMaximumSize(new Dimension(1100, 71));
    vcardPanel.setMinimumSize(new Dimension(1100, 71));

    getToolBar()
        .add(
            vcardPanel,
            new GridBagConstraints(
                0,
                1,
                1,
                1,
                1.0,
                0.0,
                GridBagConstraints.NORTHWEST,
                GridBagConstraints.HORIZONTAL,
                new Insets(0, 2, 0, 2),
                0,
                0));

    final LocalPreferences localPreferences = SettingsManager.getLocalPreferences();
    if (!localPreferences.isChatHistoryEnabled()) {
      return;
    }

    if (!localPreferences.isPrevChatHistoryEnabled()) {
      return;
    }

    final String bareJID = StringUtils.parseBareAddress(getParticipantJID());
    final ChatTranscript chatTranscript = ChatTranscripts.getCurrentChatTranscript(bareJID);
    final String personalNickname = SparkManager.getUserManager().getNickname();

    for (HistoryMessage message : chatTranscript.getMessages()) {
      String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom());
      String messageBody = message.getBody();
      if (nickname.equals(message.getFrom())) {
        String otherJID = StringUtils.parseBareAddress(message.getFrom());
        String myJID = SparkManager.getSessionManager().getBareAddress();

        if (otherJID.equals(myJID)) {
          nickname = personalNickname;
        } else {
          nickname = StringUtils.parseName(nickname);
        }
      }

      if (ModelUtil.hasLength(messageBody) && messageBody.startsWith("/me ")) {
        messageBody = messageBody.replaceFirst("/me", nickname);
      }

      final Date messageDate = message.getDate();
      getTranscriptWindow().insertHistoryMessage(nickname, messageBody, messageDate);
    }
  }
 @Override
 public void onAvatarChange(
     String from, String avatarId, List<AvatarMetadataExtension.Info> avatarInfos) {
   String jid = StringUtils.parseBareAddress(mUserInfo.getJid());
   String mfrom = StringUtils.parseBareAddress(from);
   if (jid.equalsIgnoreCase(mfrom)) {
     mUserInfo.setAvatarId(avatarId);
   }
 }
Example #4
0
 /**
  * If the given JID is a full JID, take its resource to be the resource we are currently chatting
  * with.
  */
 public void setUserResource(String jid) {
   String bareJid = StringUtils.parseBareAddress(jid);
   if (!jid.equals(bareJid)) {
     setLastKnownResource(jid);
     mRemoteIdFull = jid;
   }
 }
 /** @param packet */
 public void processPacket(Packet packet) {
   PresenceIndicator.getDefault()
       .label
       .setText(
           KenaiUser.getOnlineUserCount() > 0
               ? KenaiUser.getOnlineUserCount() - 1 + ""
               : ""); // NOI18N
   PresenceIndicator.getDefault()
       .label
       .setToolTipText(
           NbBundle.getMessage(
               PresenceIndicator.class,
               "LBL_LoggedIn_Tooltip",
               KenaiUser.getOnlineUserCount() > 0 ? KenaiUser.getOnlineUserCount() - 1 : ""));
   for (MultiUserChat muc :
       KenaiConnection.getDefault(
               KenaiConnection.getKenai(StringUtils.parseBareAddress(packet.getFrom())))
           .getChats()) {
     String chatName = StringUtils.parseName(muc.getRoom());
     assert chatName != null : "muc.getRoom() = " + muc.getRoom(); // NOI18N
     ChatNotifications.getDefault()
         .getMessagingHandle(KenaiConnection.getKenaiProject(muc))
         .setOnlineCount(muc.getOccupantsCount());
   }
 }
 @Override
 public void onClick(View v) {
   if (v == createButton) {
     boolean create = true;
     if (!checkUserName()) {
       username.setError(getString(R.string.create_account_err_username));
       create = false;
     }
     if (TextUtils.isEmpty(serverEdit.getText())) {
       serverEdit.setError("Choose a server");
       create = false;
     }
     if (!checkPasswords()) {
       password.setError(getString(R.string.create_account_err_passwords));
       confirmPassword.setError(getString(R.string.create_account_err_passwords));
       create = false;
     }
     if (create) {
       String jid = String.format("%s@%s", username.getText(), serverEdit.getText());
       jid = StringUtils.parseBareAddress(jid);
       String pass = password.getText().toString();
       task = new CreateAccountTask();
       task.execute(jid, pass);
     }
   }
 }
Example #7
0
 public void addFriend(String userID) {
   if (sRoster != null) {
     if (!sRoster.contains(userID)) {
       try {
         sRoster.createEntry(userID, StringUtils.parseBareAddress(userID), null);
         retrieveFriendList();
       } catch (XMPPException e) {
         System.err.println("Error in adding friend " + e.getMessage());
       }
     } else {
       RosterEntry rosterEntry = sRoster.getEntry(userID);
       RosterPacket.ItemType type = rosterEntry.getType();
       switch (type) {
         case from:
           requestSubscription(userID, sConnection);
           break;
         case to:
           grantSubscription(userID, sConnection);
           break;
         case none:
           grantSubscription(userID, sConnection);
           requestSubscription(userID, sConnection);
           break;
         case both:
         default:
           break;
       }
     }
   }
 }
Example #8
0
  /**
   * Remove records telling what entity caps node a contact has.
   *
   * @param contact the contact
   */
  public void removeContactCapsNode(Contact contact) {
    Caps caps = null;
    String lastRemovedJid = null;

    Iterator<String> iter = userCaps.keySet().iterator();
    while (iter.hasNext()) {
      String jid = iter.next();

      if (StringUtils.parseBareAddress(jid).equals(contact.getAddress())) {
        caps = userCaps.get(jid);
        lastRemovedJid = jid;
        iter.remove();
      }
    }

    // fire only for the last one, at the end the event out
    // of the protocol will be one and for the contact
    if (caps != null) {
      UserCapsNodeListener[] listeners;
      synchronized (userCapsNodeListeners) {
        listeners = userCapsNodeListeners.toArray(NO_USER_CAPS_NODE_LISTENERS);
      }
      if (listeners.length != 0) {
        String nodeVer = caps.getNodeVer();

        for (UserCapsNodeListener listener : listeners)
          listener.userCapsNodeRemoved(lastRemovedJid, nodeVer, false);
      }
    }
  }
Example #9
0
  private void processOfflineMessages() {
    Log.i(LOG_TAG, "Begin retrieval of offline messages from server");

    OfflineMessageManager offlineMessageManager = new OfflineMessageManager(con);
    try {
      if (!offlineMessageManager.supportsFlexibleRetrieval()) {
        Log.d(LOG_TAG, "Offline messages not supported");
        return;
      }

      List<Message> msgs = offlineMessageManager.getMessages();
      for (Message msg : msgs) {
        Intent intent =
            new Intent(MessageService.ACTION_MESSAGE_RECEIVED, null, context, MessageService.class);
        intent.putExtra(
            MessageService.EXTRA_DATA_NAME_FROM, StringUtils.parseBareAddress(msg.getFrom()));
        intent.putExtra(MessageService.EXTRA_DATA_NAME_MESSAGE_BODY, msg.getBody());

        context.startService(intent);
      }

      offlineMessageManager.deleteMessages();
    } catch (Exception e) {
      Log.e(LOG_TAG, "handle offline messages error ", e);
    }

    Log.i(LOG_TAG, "End of retrieval of offline messages from server");
  }
 /**
  * Gets a friend based on his XMPPAddress.
  *
  * @param xmppAddress For example [email protected]
  * @return The corresponding Friend or null if user is not found or he is not a friend of you.
  */
 public Friend getFriendById(String xmppAddress) {
   final RosterEntry entry =
       connection.getRoster().getEntry(StringUtils.parseBareAddress(xmppAddress));
   if (entry != null) {
     return new Friend(this, connection, entry);
   }
   return null;
 }
Example #11
0
 /** 更改用户状态 */
 public void setPresence(int code) {
   if (connection == null) return;
   Presence presence;
   switch (code) {
     case 0:
       presence = new Presence(Presence.Type.available);
       connection.sendPacket(presence);
       Log.v("state", "设置在线");
       break;
     case 1:
       presence = new Presence(Presence.Type.available);
       presence.setMode(Presence.Mode.chat);
       connection.sendPacket(presence);
       Log.v("state", "设置Q我吧");
       System.out.println(presence.toXML());
       break;
     case 2:
       presence = new Presence(Presence.Type.available);
       presence.setMode(Presence.Mode.dnd);
       connection.sendPacket(presence);
       Log.v("state", "设置忙碌");
       System.out.println(presence.toXML());
       break;
     case 3:
       presence = new Presence(Presence.Type.available);
       presence.setMode(Presence.Mode.away);
       connection.sendPacket(presence);
       Log.v("state", "设置离开");
       System.out.println(presence.toXML());
       break;
     case 4:
       Roster roster = connection.getRoster();
       Collection<RosterEntry> entries = roster.getEntries();
       for (RosterEntry entry : entries) {
         presence = new Presence(Presence.Type.unavailable);
         presence.setPacketID(Packet.ID_NOT_AVAILABLE);
         presence.setFrom(connection.getUser());
         presence.setTo(entry.getUser());
         connection.sendPacket(presence);
         System.out.println(presence.toXML());
       }
       // 向同一用户的其他客户端发送隐身状态
       presence = new Presence(Presence.Type.unavailable);
       presence.setPacketID(Packet.ID_NOT_AVAILABLE);
       presence.setFrom(connection.getUser());
       presence.setTo(StringUtils.parseBareAddress(connection.getUser()));
       connection.sendPacket(presence);
       Log.v("state", "设置隐身");
       break;
     case 5:
       presence = new Presence(Presence.Type.unavailable);
       connection.sendPacket(presence);
       Log.v("state", "设置离线");
       break;
     default:
       break;
   }
 }
  /**
   * Sends a reply to a previously received packet that was sent to multiple recipients. Before
   * attempting to send the reply message some checkings are performed. If any of those checkings
   * fail then an XMPPException is going to be thrown with the specific error detail.
   *
   * @param connection the connection to use to send the reply.
   * @param original the previously received packet that was sent to multiple recipients.
   * @param reply the new message to send as a reply.
   * @throws XMPPException if the original message was not sent to multiple recipients, or the
   *     original message cannot be replied or reply should be sent to a room.
   */
  public static void reply(Connection connection, Message original, Message reply)
      throws XMPPException {
    MultipleRecipientInfo info = getMultipleRecipientInfo(original);
    if (info == null) {
      throw new XMPPException("Original message does not contain multiple recipient info");
    }
    if (info.shouldNotReply()) {
      throw new XMPPException("Original message should not be replied");
    }
    if (info.getReplyRoom() != null) {
      throw new XMPPException("Reply should be sent through a room");
    }
    // Any <thread/> element from the initial message MUST be copied into the reply.
    if (original.getThread() != null) {
      reply.setThread(original.getThread());
    }
    MultipleAddresses.Address replyAddress = info.getReplyAddress();
    if (replyAddress != null && replyAddress.getJid() != null) {
      // Send reply to the reply_to address
      reply.setTo(replyAddress.getJid());
      connection.sendPacket(reply);
    } else {
      // Send reply to multiple recipients
      List<String> to = new ArrayList<String>();
      List<String> cc = new ArrayList<String>();
      for (Iterator<MultipleAddresses.Address> it = info.getTOAddresses().iterator();
          it.hasNext(); ) {
        String jid = it.next().getJid();
        to.add(jid);
      }
      for (Iterator<MultipleAddresses.Address> it = info.getCCAddresses().iterator();
          it.hasNext(); ) {
        String jid = it.next().getJid();
        cc.add(jid);
      }
      // Add original sender as a 'to' address (if not already present)
      if (!to.contains(original.getFrom()) && !cc.contains(original.getFrom())) {
        to.add(original.getFrom());
      }
      // Remove the sender from the TO/CC list (try with bare JID too)
      String from = connection.getUser();
      if (!to.remove(from) && !cc.remove(from)) {
        String bareJID = StringUtils.parseBareAddress(from);
        to.remove(bareJID);
        cc.remove(bareJID);
      }

      String serviceAddress = getMultipleRecipienServiceAddress(connection);
      if (serviceAddress != null) {
        // Send packet to target users using multiple recipient service provided by the server
        sendThroughService(connection, reply, to, cc, null, null, null, false, serviceAddress);
      } else {
        // Server does not support JEP-33 so try to send the packet to each recipient
        sendToIndividualRecipients(connection, reply, to, cc, null);
      }
    }
  }
 private User getUserByLogin(String userLogin) {
   for (int i = 0; i < mUserList.size(); i++) {
     final User user = mUserList.get(i);
     if (user.getUserLogin().equalsIgnoreCase(StringUtils.parseBareAddress(userLogin))) {
       return user;
     }
   }
   return null;
 }
Example #14
0
  /**
   * Retrieve the last activity of a particular jid.
   *
   * @param con the current Connection.
   * @param jid the JID of the user.
   * @return the LastActivity packet of the jid.
   * @throws XMPPException thrown if a server error has occured.
   * @deprecated This method only retreives the lapsed time since the last logout of a particular
   *     jid. Replaced by {@link
   *     org.jivesoftware.smackx.iqlast.LastActivityManager#getLastActivity(Connection, String)
   *     getLastActivity}
   */
  public static LastActivity getLastActivity(Connection con, String jid) throws XMPPException {
    LastActivity activity = new LastActivity();
    jid = StringUtils.parseBareAddress(jid);
    activity.setTo(jid);

    LastActivity response =
        (LastActivity) con.createPacketCollectorAndSend(activity).nextResultOrThrow();
    return response;
  }
Example #15
0
  /**
   * Remove this JID from the mapping. If the JID has a resource, only remove it if the resource
   * matches.
   */
  public static void clearLastKnownResource(String jid) {
    String barejid = StringUtils.parseBareAddress(jid);

    if (!jid.equals(barejid)) {
      String fulljid = (String) sResourceTracker.get(barejid);
      if (fulljid == null) return;
      if (!fulljid.equals(jid)) return;
    }

    sResourceTracker.remove(barejid);
  }
 public void userHasLogged(String user) {
   boolean isAnonymous = "".equals(StringUtils.parseName(user));
   String title =
       "Smack Debug Window -- "
           + (isAnonymous ? "" : StringUtils.parseBareAddress(user))
           + "@"
           + connection.getServiceName()
           + ":"
           + connection.getPort();
   title += "/" + StringUtils.parseResource(user);
   frame.setTitle(title);
 }
  public void presenceChanged(Presence p) {
    String from = p.getFrom();
    if (from != null) {
      p = connection.getRoster().getPresence(p.getFrom());
      from = StringUtils.parseBareAddress(from);
      final Friend friend = api.getFriendById(from);
      if (friend != null) {
        for (final FriendListener l : api.getFriendListeners()) {
          final Presence.Type previousType = typeUsers.get(from);
          if (p.getType() == Presence.Type.available
              && (previousType == null || previousType != Presence.Type.available)) {
            l.onFriendJoin(friend);
          } else if (p.getType() == Presence.Type.unavailable
              && (previousType == null || previousType != Presence.Type.unavailable)) {
            l.onFriendLeave(friend);
          }

          final Presence.Mode previousMode = modeUsers.get(from);
          if (p.getMode() == Presence.Mode.chat
              && (previousMode == null || previousMode != Presence.Mode.chat)) {
            l.onFriendAvailable(friend);
          } else if (p.getMode() == Presence.Mode.away
              && (previousMode == null || previousMode != Presence.Mode.away)) {
            l.onFriendAway(friend);
          } else if (p.getMode() == Presence.Mode.dnd
              && (previousMode == null || previousMode != Presence.Mode.dnd)) {
            l.onFriendBusy(friend);
          }

          if (p.getStatus() != null) {
            try {
              final LolStatus previousStatus = statusUsers.get(from);
              final LolStatus newStatus = new LolStatus(p.getStatus());
              if (previousStatus != null && !newStatus.equals(previousStatus)) {
                l.onFriendStatusChange(friend);
              }
            } catch (JDOMException | IOException e) {
            }
          }
        }

        typeUsers.put(from, p.getType());
        modeUsers.put(from, p.getMode());
        if (p.getStatus() != null) {
          try {
            statusUsers.put(from, new LolStatus(p.getStatus()));
          } catch (JDOMException | IOException e) {
          }
        }
      }
    }
  }
Example #18
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    context = getApplicationContext();
    this.connection = Conexion.getInstance();
    this.roster = RosterManager.getRosterInstance();
    chatMan = ContactsActivity.chatMan;
    chat = chatMan.chat;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat);
    destJid = getIntent().getStringExtra("destJid");
    myJid = this.connection.getUser();
    cipher = RosterManager.isSecure(destJid);
    Bundle bundle = getIntent().getExtras();
    passPhrase = bundle.getString(AndroidRsaConstants.PASSPHRASE);

    String parsedDest = StringUtils.parseBareAddress(destJid);
    Log.d(TAG, "Creado chat con " + roster.getEntry(parsedDest).getName() + " cifrado=" + cipher);

    if (chat == null) {
      chatMan.createChat(destJid, messageListener);
      chat = chatMan.getChat();
      if (cipher) {
        Message m = new Message(destJid);
        try {
          chat.sendMessage(m);
        } catch (XMPPException e) {
          e.printStackTrace();
        }
      }
    } else {
      chat.addMessageListener(messageListener);
    }

    adapter = new ChatAdapter(this, listMessages);
    setListAdapter(adapter);
    myListView = getListView();
    myListView.setDivider(null);

    if (cipher) {
      Bitmap bm = AvatarsCache.getAvatar(destJid);
      try {
        cert = Decode.decode(bm);
      } catch (IOException e) {
        e.printStackTrace();
      } catch (CertificateException e) {
        e.printStackTrace();
      }
    }
  }
  /**
   * Calls an individual user by their VCard information.
   *
   * @param jid the users JID.
   */
  public void callByJID(String jid) {
    if (getStatus() == SipRegisterStatus.Registered) {
      final VCard vcard =
          SparkManager.getVCardManager().getVCard(StringUtils.parseBareAddress(jid));

      if (vcard != null) {
        String number = vcard.getPhoneWork("VOICE");
        if (!ModelUtil.hasLength(number)) {
          number = vcard.getPhoneHome("VOICE");
        }

        if (ModelUtil.hasLength(number)) {
          getDefaultGuiManager().dial(number);
        }
      }
    }
  }
  /**
   * Maps the specified <tt>address</tt> to <tt>jid</tt>. The point of this method is to allow us to
   * send all messages destined to the contact with the specified <tt>address</tt> to the
   * <tt>jid</tt> that they last contacted us from.
   *
   * @param threadID the threadID of conversation.
   * @param jid the jid (i.e. address/resource) that the contact with the specified <tt>address</tt>
   *     last contacted us from.
   */
  private void putJidForAddress(String jid, String threadID) {
    synchronized (jids) {
      purgeOldJids();

      StoredThreadID ta = jids.get(jid);

      if (ta == null) {
        ta = new StoredThreadID();
        jids.put(jid, ta);
      }

      recentJIDForAddress.put(StringUtils.parseBareAddress(jid), jid);

      ta.lastUpdatedTime = System.currentTimeMillis();
      ta.threadID = threadID;
    }
  }
 public User setupUser(String uid, boolean addIfNotExists) {
   final RosterEntry re = mRoster.getEntry(StringUtils.parseBareAddress(uid));
   if (re != null) {
     final User user = new User(re, mRoster.getPresence(re.getUser()));
     user.setAvatar(service.getAvatarService().getAvatar(user));
     if (addIfNotExists) {
       setupUser(user);
     }
     return user;
   } else {
     Log.w(TAG, "creating Invalid user for: " + uid);
     final User u = new User();
     u.setUserLogin(uid);
     u.setUserState(UserState.Invalid);
     return u;
   }
 }
Example #22
0
  public UserProfile search(String username) throws SmackInvocationException {
    String name = StringUtils.parseName(username);
    String jid = null;
    if (name == null || name.trim().length() == 0) {
      jid = username + "@" + con.getServiceName();
    } else {
      jid = StringUtils.parseBareAddress(username);
    }

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

    VCard vCard = vCardHelper.loadVCard(jid);
    String nickname = vCard.getNickName();

    return nickname == null ? null : new UserProfile(jid, vCard);
  }
 public User getUser(String uid, boolean addIfNotExists, boolean setupIfNotExists) {
   if (mUserMe.getUserLogin().equalsIgnoreCase(StringUtils.parseBareAddress(uid))) {
     return mUserMe;
   }
   User u = getUserByFullUserLogin(uid);
   if (u != null) {
     return u;
   }
   u = getUserByLogin(uid);
   if (u != null) {
     return u;
   }
   if (setupIfNotExists) {
     return setupUser(uid, addIfNotExists);
   } else {
     return null;
   }
 }
Example #24
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);
        }
      }
    }
Example #25
0
  // carefull, this method does also get called by the SmackListener Thread
  @Override
  public void presenceChanged(Presence presence) {
    String bareUserId = StringUtils.parseBareAddress(presence.getFrom());

    Intent intent = new Intent(MainService.ACTION_XMPP_PRESENCE_CHANGED);
    intent.putExtra("userid", bareUserId);
    intent.putExtra("fullid", presence.getFrom());
    intent.putExtra("state", retrieveState(presence.getMode(), presence.isAvailable()));
    intent.putExtra("status", presence.getStatus());
    sContext.sendBroadcast(intent);

    // TODO Make this a general intent action.NOTIFICATION_ADDRESS_AVAILABLE
    // and handle it for example within XmppPresenceStatus
    // if the notification address is/has become available, update the resource status string
    if (sSettings.containsNotifiedAddress(bareUserId) && presence.isAvailable()) {
      intent = new Intent(MainService.ACTION_COMMAND);
      intent.setClass(sContext, MainService.class);
      intent.putExtra("cmd", "batt");
      intent.putExtra("args", "silent");
      MainService.sendToServiceHandler(intent);
    }
  }
 /**
  * Sends an friend request to an other user.
  *
  * @param userId The userId of the user you want to add (e.g. [email protected]).
  * @param name The name you want to assign to this user.
  * @param friendGroup The FriendGroup you want to put this user in.
  */
 public void addFriendById(String userId, String name, FriendGroup friendGroup) {
   if (name == null && getRiotApi() != null) {
     try {
       name = getRiotApi().getName(userId);
     } catch (final IOException e) {
       e.printStackTrace();
     }
   }
   try {
     connection
         .getRoster()
         .createEntry(
             StringUtils.parseBareAddress(userId),
             name,
             new String[] {
               friendGroup == null ? getDefaultFriendGroup().getName() : friendGroup.getName()
             });
   } catch (NotLoggedInException
       | NoResponseException
       | XMPPErrorException
       | NotConnectedException e) {
     e.printStackTrace();
   }
 }
Example #27
0
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this));
    Colors.updateColors(this);
    startService(new Intent(this, JTalkService.class));
    service = JTalkService.getInstance();
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    setTheme(Colors.isLight ? R.style.AppThemeLight : R.style.AppThemeDark);

    setContentView(R.layout.roster);

    LinearLayout roster = (LinearLayout) findViewById(R.id.roster_linear);
    roster.setBackgroundColor(Colors.BACKGROUND);

    getActionBar().setHomeButtonEnabled(true);

    statusArray = getResources().getStringArray(R.array.statusArray);
    rosterAdapter = new RosterAdapter(this);
    simpleAdapter = new NoGroupsAdapter(this);
    searchAdapter = new SearchAdapter(this);

    int cols = 1;
    if (!prefs.getBoolean("ShowGroups", true) && !prefs.getBoolean("ShowMucGroup", false)) {
      try {
        cols = Integer.parseInt(prefs.getString("RosterColumns", "1"));
      } catch (Exception e) {
        cols = 1;
      }
    }
    gridView = (GridView) findViewById(R.id.users);
    gridView.setNumColumns(cols);
    gridView.setCacheColorHint(0x00000000);
    gridView.setOnItemClickListener(this);
    gridView.setOnItemLongClickListener(this);
    gridView.setAdapter(rosterAdapter);

    if (getIntent().getBooleanExtra("status", false)) {
      RosterDialogs.changeStatusDialog(this, null, null);
    }

    if (getIntent().getBooleanExtra("password", false)) {
      String account = getIntent().getStringExtra("account");
      RosterDialogs.passwordDialog(this, account);
    }

    if (getIntent().getBooleanExtra("subscribtion", false)) {
      String account = getIntent().getStringExtra("account");
      String jid = getIntent().getStringExtra("jid");
      RosterDialogs.subscribtionRequestDialog(this, account, jid);
    }

    File table = new File(Constants.PATH_SMILES + "/default/table.xml");
    if (!table.exists()) {
      new CreateDefaultSmiles().execute();
    } else {
      Cursor cursor =
          getContentResolver()
              .query(
                  JTalkProvider.ACCOUNT_URI,
                  null,
                  AccountDbHelper.ENABLED + " = '" + 1 + "'",
                  null,
                  null);
      if (cursor == null || cursor.getCount() < 1) startActivity(new Intent(this, Accounts.class));
    }

    if (prefs.getBoolean("BUG", false)) {
      new ErrorDialog(this).show();
    }

    String action = getIntent().getAction();
    if (action != null && action.equals(Intent.ACTION_VIEW)) {
      Uri data = getIntent().getData();
      if (data != null && data.getScheme().equals("xmpp")) {
        XMPPUri xmppUri;
        try {
          xmppUri = new XMPPUri(data);
        } catch (IllegalArgumentException e) {
          xmppUri = null;
        }

        List<String> accounts = new ArrayList<String>();
        for (XMPPConnection connection : service.getAllConnections()) {
          accounts.add(StringUtils.parseBareAddress(connection.getUser()));
        }

        if (xmppUri != null && !accounts.isEmpty()) {
          final String xmppJid = xmppUri.getJid();
          final String body = xmppUri.getBody();
          String queryType = xmppUri.getQueryType();

          final ArrayAdapter<String> adapter =
              new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, accounts);

          if (queryType.equals("roster")) {
            RosterDialogs.addDialog(this, xmppUri.getJid());
          } else if (queryType.equals("join")) {
            if (accounts.size() > 1) {
              AlertDialog.Builder builder = new AlertDialog.Builder(this);
              builder.setTitle(R.string.Accounts);
              builder.setAdapter(
                  adapter,
                  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                      String account = adapter.getItem(which);
                      MucDialogs.joinDialog(RosterActivity.this, account, xmppJid, null);
                    }
                  });
              builder.create().show();
            } else MucDialogs.joinDialog(RosterActivity.this, accounts.get(0), xmppJid, null);
          } else {
            service.setText(xmppJid, body);
            if (accounts.size() > 1) {
              service.setText(xmppJid, body);
              AlertDialog.Builder builder = new AlertDialog.Builder(this);
              builder.setTitle(R.string.Accounts);
              builder.setAdapter(
                  adapter,
                  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                      String account = adapter.getItem(which);
                      Intent intent = new Intent(RosterActivity.this, Chat.class);
                      intent.putExtra("account", account);
                      intent.putExtra("jid", xmppJid);
                      startActivity(intent);
                    }
                  });
              builder.create().show();
            } else {
              Intent intent = new Intent(RosterActivity.this, Chat.class);
              intent.putExtra("account", accounts.get(0));
              intent.putExtra("jid", xmppJid);
              startActivity(intent);
            }
          }
        }
      }
    }
  }
    /**
     * 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);
    }
  /** Create the window UI. */
  private void buildUI() {
    Container cPane = getContentPane();
    cPane.setLayout(new GridBagLayout());
    GridBagConstraints c;
    JLabel label;
    String msg;
    JTextField field;

    int row = 0;

    label = new JLabel(sTimeStampFormat.format(mInvite.getTimestamp()));
    label.setFont(new Font("SansSerif", Font.PLAIN, 9));
    c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = row++;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.anchor = GridBagConstraints.EAST;
    c.insets = new Insets(SPACING, MARGIN, 0, MARGIN);
    cPane.add(label, c);

    msg = mInvite.getPlayerJID();
    msg = StringUtils.parseBareAddress(msg);
    field = new JTextField(msg);
    field.setEditable(false);
    field.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4));
    c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = row++;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.anchor = GridBagConstraints.WEST;
    c.insets = new Insets(SPACING, MARGIN, 0, MARGIN);
    cPane.add(field, c);

    String gamename = mInvite.getGameName();
    if (gamename != null) gamename = gamename.trim();

    if (gamename != null && !gamename.equals("")) msg = "  " + localize("MessageInvitedOf");
    else msg = "  " + localize("MessageInvited");
    label = new JLabel(msg);
    c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = row++;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.anchor = GridBagConstraints.WEST;
    c.insets = new Insets(SPACING, MARGIN, 0, MARGIN);
    cPane.add(label, c);

    if (gamename != null && !gamename.equals("")) {
      field = new JTextField(gamename);
      field.setEditable(false);
      field.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4));
      c = new GridBagConstraints();
      c.gridx = 0;
      c.gridy = row++;
      c.gridwidth = GridBagConstraints.REMAINDER;
      c.anchor = GridBagConstraints.WEST;
      c.insets = new Insets(SPACING, MARGIN, 0, MARGIN);
      cPane.add(field, c);
    }

    String message = mInvite.getMessage();
    if (message != null) message = message.trim();

    if (message != null && !message.equals("")) {
      JTextArea textarea = new JTextArea();
      textarea.setEditable(false);
      textarea.setRows(4);
      textarea.setLineWrap(true);
      textarea.setWrapStyleWord(true);
      textarea.setText(message);
      c = new GridBagConstraints();
      c.gridx = 0;
      c.gridy = row++;
      c.gridwidth = GridBagConstraints.REMAINDER;
      c.weightx = 1;
      c.fill = GridBagConstraints.HORIZONTAL;
      c.anchor = GridBagConstraints.WEST;
      c.insets = new Insets(GAP, MARGIN, 0, MARGIN);
      JScrollPane scroller = new JScrollPane(textarea);
      scroller.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4));
      cPane.add(scroller, c);
    }

    label = new JLabel(localize("LabelNickname"));
    c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = row;
    c.anchor = GridBagConstraints.WEST;
    c.insets = new Insets(GAP, MARGIN, 0, MARGIN);
    cPane.add(label, c);

    mNicknameField = new JTextField(20);
    c = new GridBagConstraints();
    c.gridx = 1;
    c.gridy = row++;
    c.weightx = 1;
    c.anchor = GridBagConstraints.WEST;
    c.insets = new Insets(GAP, SPACING, 0, MARGIN);
    cPane.add(mNicknameField, c);

    // Add panel with Cancel and Create buttons
    JPanel buttonPanel = new JPanel(new GridBagLayout());
    c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = row++;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.insets = new Insets(GAP, MARGIN, MARGIN, MARGIN);
    c.anchor = GridBagConstraints.EAST;
    c.weightx = 1;
    cPane.add(buttonPanel, c);

    mAcceptButton = new JButton(localize("ButtonAccept"));
    c = new GridBagConstraints();
    c.gridx = 2;
    c.gridy = 0;
    c.insets = new Insets(0, 0, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    buttonPanel.add(mAcceptButton, c);

    mChatButton = new JButton(localize("ButtonDeclineChat"));
    c = new GridBagConstraints();
    c.gridx = 1;
    c.gridy = 0;
    c.insets = new Insets(0, SPACING, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    buttonPanel.add(mChatButton, c);

    mDeclineButton = new JButton(localize("ButtonDecline"));
    c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = 0;
    c.insets = new Insets(0, SPACING, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    buttonPanel.add(mDeclineButton, c);
  }
Example #30
0
 /** Put this full JID into the mapping. */
 public static void setLastKnownResource(String jid) {
   String barejid = StringUtils.parseBareAddress(jid);
   sResourceTracker.put(barejid, jid);
 }