/**
  * Checks if we are in this list of Affiliates
  *
  * @param affCol
  * @return
  */
 private boolean affiliateCheck(Collection<Affiliate> affCol) {
   Set<String> ids = new HashSet<String>();
   for (Affiliate a : affCol) {
     ids.add(a.getJid());
   }
   return ids.contains(mSettings.getLogin());
 }
 private XmppMuc(Context context) {
   mCtx = context;
   mSettings = SettingsManager.getSettingsManager(context);
   mMucHelper = MUCHelper.getMUCHelper(context);
   mDiscussionHistory = new DiscussionHistory();
   // this should disable history replay on MUC rooms
   mDiscussionHistory.setMaxChars(0);
 }
 /**
  * Checks if the notification address is available return also true if no roster is loaded
  *
  * @return
  */
 public boolean isNotificationAddressAvailable() {
   if (sRoster != null) {
     // getPresence retrieves eventually the status of the notified Address in an internal data
     // structure cache
     // thus avoiding an extra data packet
     for (String notifiedAddress : sSettings.getNotifiedAddresses()) {
       Presence presence = sRoster.getPresence(notifiedAddress);
       if (presence.isAvailable()) {
         return true;
       }
     }
     return false;
   }
   return true;
 }
  CommandHandlerBase(MainService mainService, int cmdType, Object... commands) {
    if (sMainService == null) {
      sMainService = mainService;
      sSettingsMgr = SettingsManager.getSettingsManager(sContext);
      sContext = mainService.getBaseContext();
      Cmd.setContext(sContext);
    }
    mCommandMap = new HashMap<String, Cmd>();
    for (Object o : commands) {
      Cmd c = (Cmd) o;
      mCommandMap.put(c.getName(), c);
    }
    mCmdType = cmdType;
    mAnswerTo = null;

    initializeSubCommands();
  }
  // 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);
    }
  }
  /**
   * Invites the user to a room for the given contact name and number if the user (or someone else)
   * writes to this room, a SMS is send to the number
   *
   * @param number
   * @return true if successful, otherwise false
   * @throws XMPPException
   */
  public MultiUserChat inviteRoom(String number, String contact, int mode) throws Exception {
    MultiUserChat muc;
    if (!mRooms.containsKey(number)) {
      Log.i("No existing chat room with " + contact + ". Creating a new one...");
      muc = createRoom(number, contact, mode);
      mRooms.put(number, muc);

    } else {
      muc = mRooms.get(number);
      Log.i("Opening existing room for " + contact);
      if (muc != null) {
        Collection<Occupant> occupants = muc.getParticipants();

        // Logging participants
        for (Occupant occupant : occupants) {
          Log.d(occupant.getJid() + " already in the room");
        }

        // Invite notified addresses if needed
        for (String notifiedAddress : mSettings.getNotifiedAddresses().getAll()) {
          boolean found = false;
          for (Occupant occupant : occupants) {
            if (occupant.getJid().startsWith(notifiedAddress + "/")) {
              found = true;
              break;
            }
          }
          if (!found) {
            Log.d("Inviting notified address '" + notifiedAddress + "' in the room for " + contact);
            muc.invite(notifiedAddress, "SMS conversation with " + contact);
          }
        }
      }
    }
    return muc;
  }
 private XmppBuddies(Context context) {
   sContext = context;
   sSettings = SettingsManager.getSettingsManager(context);
 }
 private void checkNotificationAddressRoster() {
   for (String notifiedAddress : sSettings.getNotifiedAddresses()) {
     addFriend(notifiedAddress);
   }
 }
  /**
   * Creates a new MUC AND invites the user room name will be extended with an random number for
   * security purposes
   *
   * @param number
   * @param name - the name of the contact to chat via SMS with
   * @return
   * @throws XMPPException
   */
  private MultiUserChat createRoom(String number, String name, int mode) throws Exception {
    MultiUserChat multiUserChat;
    Integer randomInt;

    // With "@conference.jabber.org" messages are sent several times...
    // Jwchat seems to work fine and is the default
    final String roomJID;
    final String subjectInviteStr;

    do {
      randomInt = mRndGen.nextInt();
    } while (mRoomNumbers.contains(randomInt));

    String normalizedName = name.replaceAll(" ", "_").replaceAll("[\\W]|�", "");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
      normalizedName =
          Normalizer.normalize(normalizedName, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");
    }
    String cleanLogin = mSettings.getLogin().replaceAll("@", "_");
    String roomUID = normalizedName + "_" + ROOM_START_TAG + randomInt + "_" + cleanLogin;

    switch (mode) {
      case MODE_SMS:
        roomJID = roomUID + "_SMS_" + "@" + getMUCServer();
        subjectInviteStr = mCtx.getString(R.string.xmpp_muc_sms) + name;
        break;

      case MODE_SHELL:
        roomJID = roomUID + "_Shell_" + number + "@" + getMUCServer();
        subjectInviteStr = mCtx.getString(R.string.xmpp_muc_shell) + name + " " + number;
        name = "Shell " + number;
        break;

      default:
        roomJID = null;
        subjectInviteStr = null;
        break;
    }
    Log.i("Creating room " + roomJID + " " + getRoomInt(roomJID));

    // See issue 136
    try {
      multiUserChat = new MultiUserChat(mConnection, roomJID);
    } catch (Exception e) {
      Log.e("MUC creation failed: ", e);
      throw new Exception("MUC creation failed for " + roomJID + ": " + e.getLocalizedMessage(), e);
    }

    try {
      multiUserChat.createOrJoin(name);
    } catch (Exception e) {
      Log.e("MUC creation failed: ", e);
      throw new Exception("MUC creation failed for " + name + ": " + e.getLocalizedMessage(), e);
    }

    try {
      // Since this is a private room, make the room not public and set user as owner of the room.
      Form submitForm = multiUserChat.getConfigurationForm().createAnswerForm();
      submitForm.setAnswer("muc#roomconfig_publicroom", false);
      submitForm.setAnswer("muc#roomconfig_roomname", name);
      try {
        submitForm.setAnswer("muc#roomconfig_roomdesc", name);
      } catch (Exception ex) {
        Log.w("Unable to configure room description to " + name, ex);
      }

      try {
        submitForm.setAnswer("muc#roomconfig_whois", "anyone");
      } catch (Exception ex) {
        Log.w("Unable to configure setting whois");
      }

      try {
        List<String> owners = new ArrayList<String>();
        if (mConnection.getUser() != null) {
          owners.add(mConnection.getUser());
        } else {
          owners.add(mSettings.getLogin());
        }
        Collections.addAll(owners, mSettings.getNotifiedAddresses().getAll());
        submitForm.setAnswer("muc#roomconfig_roomowners", owners);
        submitForm.setAnswer("muc#roomconfig_membersonly", true);
      } catch (Exception ex) {
        // Password protected MUC fallback code begins here
        Log.w(
            "Unable to configure room owners on Server "
                + getMUCServer()
                + ". Falling back to room passwords",
            ex);
        // See http://xmpp.org/registrar/formtypes.html#http:--jabber.org-protocol-mucroomconfig
        try {
          if (submitForm.getField("muc#roomconfig_passwordprotectedroom") != null) {
            submitForm.setAnswer("muc#roomconfig_passwordprotectedroom", true);
          }
          submitForm.setAnswer("muc#roomconfig_roomsecret", mSettings.roomPassword);
        } catch (IllegalArgumentException iae) {
          // If a server doesn't provide even password protected MUC, the setAnswer
          // call will result in an IllegalArgumentException, which we wrap into an XMPPException
          // See also Issue 247 http://code.google.com/p/gtalksms/issues/detail?id=247
          throw iae;
        }
      }

      Log.d(submitForm.getDataFormToSend().toXML().toString());
      multiUserChat.sendConfigurationForm(submitForm);
      multiUserChat.changeSubject(subjectInviteStr);
    } catch (XMPPException e1) {
      Log.w("Unable to send conference room configuration form.", e1);
      send(mCtx.getString(R.string.chat_sms_muc_conf_error, e1.getMessage()));
      // then we also should not send an invite as the room will be locked
      throw e1;
    }

    for (String notifiedAddress : mSettings.getNotifiedAddresses().getAll()) {
      multiUserChat.invite(notifiedAddress, subjectInviteStr);
    }

    registerRoom(multiUserChat, number, name, randomInt, mode);
    return multiUserChat;
  }