Ejemplo n.º 1
0
 Occupant(Presence presence) {
   super();
   MUCUser mucUser = (MUCUser) presence.getExtension("x", "http://jabber.org/protocol/muc#user");
   MUCUser.Item item = mucUser.getItem();
   this.jid = item.getJid();
   this.affiliation = item.getAffiliation();
   this.role = item.getRole();
   // Get the nickname from the FROM attribute of the presence
   this.nick = StringUtils.parseResource(presence.getFrom());
 }
 @Override
 public void presenceChanged(Presence presence) {
   final User user = getUser(presence.getFrom(), true, false);
   if (user == null) {
     return;
   }
   user.setUserState(new UserState(presence));
   user.setAvatar(service.getAvatarService().getAvatar(user));
   user.setRessource(StringUtils.parseResource(presence.getFrom()));
   service.sendRosterUpdated(user);
 }
Ejemplo n.º 3
0
 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);
 }
Ejemplo n.º 4
0
  /**
   * Creates new account.
   *
   * @param user full or bare jid.
   * @param password
   * @param accountType xmpp account type can be replaced depend on server part.
   * @param syncable
   * @param storePassword
   * @param useOrbot
   * @return assigned account name.
   * @throws NetworkException if user or server part are invalid.
   */
  public String addAccount(
      String user,
      String password,
      AccountType accountType,
      boolean syncable,
      boolean storePassword,
      boolean useOrbot)
      throws NetworkException {
    if (accountType.getProtocol().isOAuth()) {
      int index = 1;
      while (true) {
        user = String.valueOf(index);
        boolean found = false;
        for (AccountItem accountItem : accountItems.values())
          if (accountItem
                  .getConnectionSettings()
                  .getServerName()
                  .equals(accountType.getFirstServer())
              && accountItem.getConnectionSettings().getUserName().equals(user)) {
            found = true;
            break;
          }
        if (!found) break;
        index++;
      }
    }

    if (user == null) throw new NetworkException(R.string.EMPTY_USER_NAME);

    if (user.indexOf("@") == -1) {
      if ("".equals(accountType.getFirstServer()))
        throw new NetworkException(R.string.EMPTY_SERVER_NAME);
      else user += "@" + accountType.getFirstServer();
    }

    String serverName = StringUtils.parseServer(user);
    String userName = StringUtils.parseName(user);
    String resource = StringUtils.parseResource(user);
    String host = accountType.getHost();
    int port = accountType.getPort();
    boolean tlsRequired = accountType.isTLSRequired();
    if (useOrbot) tlsRequired = true;

    if ("".equals(serverName)) {
      throw new NetworkException(R.string.EMPTY_SERVER_NAME);
    } else if (!accountType.isAllowServer() && !serverName.equals(accountType.getFirstServer()))
      throw new NetworkException(R.string.INCORRECT_USER_NAME);

    if ("".equals(userName)) throw new NetworkException(R.string.EMPTY_USER_NAME);
    if ("".equals(resource)) resource = "android" + StringUtils.randomString(8);

    if (accountType.getId() == R.array.account_type_xmpp) {
      host = serverName;
      for (AccountType check : accountTypes)
        if (check.getServers().contains(serverName)) {
          accountType = check;
          host = check.getHost();
          port = check.getPort();
          tlsRequired = check.isTLSRequired();
          break;
        }
    }

    AccountItem accountItem;
    for (; ; ) {
      if (getAccount(userName + '@' + serverName + '/' + resource) == null) break;
      resource = "android" + StringUtils.randomString(8);
    }

    accountItem =
        addAccount(
            accountType.getProtocol(),
            true,
            host,
            port,
            serverName,
            userName,
            storePassword,
            password,
            resource,
            getNextColorIndex(),
            0,
            StatusMode.available,
            SettingsManager.statusText(),
            true,
            true,
            tlsRequired ? TLSMode.required : TLSMode.enabled,
            false,
            useOrbot ? ProxyType.orbot : ProxyType.none,
            "localhost",
            8080,
            "",
            "",
            syncable,
            null,
            null,
            ArchiveMode.available);
    onAccountChanged(accountItem.getAccount());
    if (accountItems.size() > 1 && SettingsManager.contactsEnableShowAccounts())
      SettingsManager.enableContactsShowAccount();
    return accountItem.getAccount();
  }
  /*
   * 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);
    }
  }
Ejemplo n.º 6
0
  // Modified for cargo
  public ChatRoomImpl(
      final String participantJID,
      final String participantNickname,
      String title,
      CargoOffer cargoOffer) {
    this.active = true;
    this.participantJID = participantJID;
    this.participantNickname = participantNickname;

    String[] results = this.participantJID.split("@");
    this.participantNicknameOnly = results[0];

    // Loads the current history for this user.
    loadHistory();

    // Register PacketListeners
    PacketFilter fromFilter = new FromMatchesFilter(participantJID);
    PacketFilter orFilter =
        new OrFilter(new PacketTypeFilter(Presence.class), new PacketTypeFilter(Message.class));
    PacketFilter andFilter = new AndFilter(orFilter, fromFilter);

    SparkManager.getConnection().addPacketListener(this, andFilter);

    // The roomname will be the participantJID
    this.roomname = participantJID;

    // Use the agents username as the Tab Title
    this.tabTitle = title;

    // The name of the room will be the node of the user jid + conversation.
    this.roomTitle = participantNickname;

    // Add RoomInfo
    this.getSplitPane().setRightComponent(null);
    getSplitPane().setDividerSize(0);

    presence = PresenceManager.getPresence(participantJID);

    roster = SparkManager.getConnection().getRoster();

    RosterEntry entry = roster.getEntry(participantJID);

    tabIcon = PresenceManager.getIconFromPresence(presence);

    infoButton =
        new CargoChatRoomButton("", SparkRes.getImageIcon(SparkRes.SPARK_IKONKA_WIZYTOWKA));
    infoButton.setToolTipText(Res.getString("message.view.information.about.this.user"));
    infoButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

    // Create basic toolbar.
    getToolBar().addChatRoomButton(infoButton);

    // If the user is not in the roster, then allow user to add them.
    // addToRosterButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.ADD_IMAGE_24x24));

    addToRosterButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.SPARK_IKONKA_DODAJ));
    addToRosterButton.setRolloverIcon(SparkRes.getImageIcon(SparkRes.SPARK_IKONKA_DODAJ));
    addToRosterButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    addToRosterButton.setBorderPainted(false);
    addToRosterButton.setRolloverEnabled(false);
    addToRosterButton.setContentAreaFilled(false);
    addToRosterButton.setIgnoreRepaint(true);
    addToRosterButton.setOpaque(false);
    addToRosterButton.setBorder(null);
    addToRosterButton.setBorderPainted(false);
    addToRosterButton.setMargin(new Insets(0, 0, 0, 0));

    MouseListener[] mouseListeners2 = addToRosterButton.getMouseListeners();
    for (MouseListener mouseListener : mouseListeners2) {
      if (mouseListener instanceof MouseAdapter) {
        addToRosterButton.removeMouseListener(mouseListener);
      }
    }

    if (entry == null && !StringUtils.parseResource(participantJID).equals(participantNickname)) {
      addToRosterButton.setToolTipText(Res.getString("message.add.this.user.to.your.roster"));
      getToolBar().addChatRoomButton(addToRosterButton);

      addToRosterButton.addActionListener(this);
    }

    // Show VCard.
    infoButton.addActionListener(this);

    // If this is a private chat from a group chat room, do not show
    // toolbar.
    if (StringUtils.parseResource(participantJID).equals(participantNickname)) {
      getToolBar().setVisible(false);
    }

    typingTimerTask =
        new TimerTask() {
          public void run() {
            if (!sendTypingNotification) {
              return;
            }
            long now = System.currentTimeMillis();
            if (now - lastTypedCharTime > 2000) {
              if (!sendNotification) {
                // send cancel
                SparkManager.getMessageEventManager()
                    .sendCancelledNotification(getParticipantJID(), threadID);
                sendNotification = true;
              }
            }
          }
        };

    TaskEngine.getInstance().scheduleAtFixedRate(typingTimerTask, 2000, 2000);
    lastActivity = System.currentTimeMillis();

    super.setCargoOffer(cargoOffer);

    this.addMessageEventListener(
        new MessageEventListener() {

          @Override
          public void sendingMessage(Message message) {
            message.setProperty(CARGO_OFFER_PROPERTY, getCargoOffer().getId());
          }

          @Override
          public void receivingMessage(Message message) {}
        });

    this.addMessageListener(
        new org.jivesoftware.spark.ui.MessageListener() {

          @Override
          public void messageReceived(ChatRoom room, Message message) {
            Long cargoOfferId = (Long) message.getProperty(CARGO_OFFER_PROPERTY);
            setCargoOffer(CargoDataManager.getInstance().getCargoOfferById(cargoOfferId));

            if (getCargoOffer() != null) {
              if (acceptedOfferButton != null) {
                getEditorBar().remove(acceptedOfferButton);
              }

              JButton acceptOfferButtonTemp =
                  getAcceptOfferButton(participantNicknameOnly, getCargoOffer());
              acceptedOfferButton = acceptOfferButtonTemp;
              getEditorBar().add(acceptedOfferButton);

            } else {
              Long newCargoOfferId = null;
              if (message.getProperty(CARGO_OFFER_PROPERTY) != null) {
                newCargoOfferId = (Long) message.getProperty(CARGO_OFFER_PROPERTY);
              }

              if (newCargoOfferId != null) {
                CargoOffer co = CargoDataManager.getInstance().getCargoOfferById(newCargoOfferId);
                setCargoOffer(co);

                if (acceptedOfferButton != null) {
                  getEditorBar().remove(acceptedOfferButton);
                }
                JButton acceptOfferButton =
                    getAcceptOfferButton(participantNicknameOnly, getCargoOffer());
                acceptedOfferButton = acceptOfferButton;
                getEditorBar().add(acceptedOfferButton);
              }
            }
          }

          @Override
          public void messageSent(ChatRoom room, Message message) {
            // TODO Auto-generated method stub
            String ooo = "oeoeu";
          }
        });
  }