示例#1
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;
   }
 }
  /**
   * Constructor for a Jingle incoming session
   *
   * @param conn the XMPP connection
   * @param responder the responder
   * @param transportManager The transport manager
   * @param initialJingleSessionRequest the initial Jingle Session Request
   */
  protected IncomingJingleSession(
      XMPPConnection conn,
      String responder,
      List payloadTypes,
      JingleTransportManager transportManager,
      JingleSessionRequest initialJingleSessionRequest)
      throws XMPPException {

    super(conn, responder, conn.getUser());

    setSid(initialJingleSessionRequest.getSessionID());

    // Create the states...

    accepting = new Accepting(this);
    pending = new Pending(this);
    active = new Active(this);

    TransportResolver resolver = null;
    try {
      resolver = transportManager.getResolver(this);
    } catch (XMPPException e) {
      e.printStackTrace();
    }

    setMediaNeg(new MediaNegotiator(this, payloadTypes));
    if (resolver.getType().equals(TransportResolver.Type.rawupd)) {
      setTransportNeg(new TransportNegotiator.RawUdp(this, resolver));
    }
    if (resolver.getType().equals(TransportResolver.Type.ice)) {
      setTransportNeg(new TransportNegotiator.Ice(this, resolver));
    }
  }
  /**
   * If the target is not connected to the local SOCKS5 proxy an exception should be thrown.
   *
   * @throws Exception should not happen
   */
  @Test
  public void shouldFailIfTargetIsNotConnectedToLocalSocks5Proxy() throws Exception {

    // start a local SOCKS5 proxy
    Socks5Proxy.setLocalSocks5ProxyPort(proxyPort);
    Socks5Proxy socks5Proxy = Socks5Proxy.getSocks5Proxy();
    socks5Proxy.start();

    // build stream host information for local SOCKS5 proxy
    StreamHost streamHost =
        new StreamHost(connection.getUser(), socks5Proxy.getLocalAddresses().get(0));
    streamHost.setPort(socks5Proxy.getPort());

    // create digest to get the socket opened by target
    String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);

    Socks5ClientForInitiator socks5Client =
        new Socks5ClientForInitiator(streamHost, digest, connection, sessionID, targetJID);

    try {
      socks5Client.getSocket(10000);

      fail("exception should be thrown");
    } catch (SmackException e) {
      assertTrue(e.getMessage().contains("target is not connected to SOCKS5 proxy"));
      protocol.verifyAll(); // assert no XMPP messages were sent
    }

    socks5Proxy.stop();
  }
  @Override
  public void disconnected(boolean onError) {
    final XMPPConnection connection = myFacade.getConnection();

    LOG.info("Jabber disconnected: " + connection.getUser());
    connection.removePacketListener(mySubscribeListener);
    mySubscribeListener = null;
    connection.removePacketListener(myMessageListener);
    myMessageListener = null;

    final Roster roster = connection.getRoster();
    if (roster != null) {
      roster.removeRosterListener(myRosterListener);
    }
    myRosterListener = null;

    myIDEtalkUsers.clear();
    myUser2Presence.clear();
    myUser2Thread.clear();

    if (onError && reconnectEnabledAndNotStarted()) {
      LOG.warn(getMsg("jabber.server.was.disconnected", myReconnectTimeout / 1000));
      myReconnectProcess = myIdeFacade.runOnPooledThread(new MyReconnectRunnable());
    }
  }
  /**
   * Initiator and target should successfully connect to the local SOCKS5 proxy.
   *
   * @throws Exception should not happen
   */
  @Test
  public void shouldSuccessfullyConnectThroughLocalSocks5Proxy() throws Exception {

    // start a local SOCKS5 proxy
    Socks5Proxy.setLocalSocks5ProxyPort(proxyPort);
    Socks5Proxy socks5Proxy = Socks5Proxy.getSocks5Proxy();
    socks5Proxy.start();

    // test data
    final byte[] data = new byte[] {1, 2, 3};

    // create digest
    final String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);

    // allow connection of target with this digest
    socks5Proxy.addTransfer(digest);

    // build stream host information
    final StreamHost streamHost =
        new StreamHost(connection.getUser(), socks5Proxy.getLocalAddresses().get(0));
    streamHost.setPort(socks5Proxy.getPort());

    // target connects to local SOCKS5 proxy
    Thread targetThread =
        new Thread() {

          @Override
          public void run() {
            try {
              Socks5Client targetClient = new Socks5Client(streamHost, digest);
              Socket socket = targetClient.getSocket(10000);
              socket.getOutputStream().write(data);
            } catch (Exception e) {
              fail(e.getMessage());
            }
          }
        };
    targetThread.start();

    Thread.sleep(200);

    // initiator connects
    Socks5ClientForInitiator socks5Client =
        new Socks5ClientForInitiator(streamHost, digest, connection, sessionID, targetJID);

    Socket socket = socks5Client.getSocket(10000);

    // verify test data
    InputStream in = socket.getInputStream();
    for (int i = 0; i < data.length; i++) {
      assertEquals(data[i], in.read());
    }

    targetThread.join();

    protocol.verifyAll(); // assert no XMPP messages were sent

    socks5Proxy.removeTransfer(digest);
    socks5Proxy.stop();
  }
 private void xmppRosterPost(XMPPConnection connection) {
   List<String> jidList = new LinkedList<String>();
   System.err.println("INFO: Reading roster.");
   for (RosterEntry entry : connection.getRoster().getEntries()) {
     jidList.add(entry.getUser());
     System.err.println("INFO: Got " + entry.getUser() + " from roster.");
   }
   System.err.println("INFO: Sending " + jidList.size() + " roster entries to server.");
   BuddylistIQ blIQ = new BuddylistIQ();
   blIQ.setFrom(connection.getUser());
   blIQ.setTo(this.androidbuddy);
   blIQ.setBuddies(jidList);
   blIQ.setIdentity(XMPPUtil.jidWithoutRessource(connection.getUser()));
   blIQ.setNetwork("roster");
   blIQ.setType(IQ.Type.SET);
   connection.sendPacket(blIQ);
 }
  /** Reads the default values from the preferences storage and fills in the text fields. */
  private void restoreFieldValues() {
    // Make a default nickname based on the user ID
    String defNick = mConnection.getUser();
    defNick = defNick.substring(0, defNick.indexOf('@'));

    Preferences prefs = Preferences.userNodeForPackage(getClass()).node(NODENAME);

    mNicknameField.setText(prefs.get(NICKNAME_KEY, defNick));
  }
 /**
  * Returns real full jid, that was assigned while login.
  *
  * @return <code>null</code> if connection is not established.
  */
 public String getRealJid() {
   ConnectionThread connectionThread = getConnectionThread();
   if (connectionThread == null) return null;
   XMPPConnection xmppConnection = connectionThread.getXMPPConnection();
   if (xmppConnection == null) return null;
   String user = xmppConnection.getUser();
   if (user == null) return null;
   return user;
 }
 private void xmppLocationUpdate(XMPPConnection connection, double lat, double lon) {
   System.err.println(
       "INFO: Sending location update: lat "
           + String.valueOf(lat)
           + ", lon "
           + String.valueOf(lon)
           + ".");
   LocationIQ luIQ = new LocationIQ();
   luIQ.setFrom(connection.getUser());
   luIQ.setTo(this.androidbuddy);
   luIQ.setLatitude(lat);
   luIQ.setLongitude(lon);
   luIQ.setAltitude(0.0f);
   luIQ.setType(IQ.Type.SET);
   luIQ.setTimestamp(new Date());
   luIQ.setIdentity(connection.getUser());
   connection.sendPacket(luIQ);
 }
 /**
  * Gets the name of the user that is logged in. An Riot API key has to be provided.
  *
  * @param forcedUpdate True will force to update the name even when it is not null.
  * @return The name of this user or null if something went wrong.
  */
 public String getName(boolean forcedUpdate) {
   if ((name == null || forcedUpdate) && getRiotApi() != null) {
     try {
       name = getRiotApi().getName(connection.getUser());
     } catch (final IOException e) {
       e.printStackTrace();
     }
   }
   return name;
 }
  @Override
  public boolean login() throws RemoteException {
    if (mAdaptee.isAuthenticated()) return true;
    if (!mAdaptee.isConnected()) return false;
    try {

      this.initFeatures(); // pour declarer les features xmpp qu'on
      // supporte

      PacketFilter filter =
          new PacketFilter() {

            @Override
            public boolean accept(Packet packet) {
              if (packet instanceof Presence) {
                Presence pres = (Presence) packet;
                if (pres.getType() == Presence.Type.subscribe) return true;
              }
              return false;
            }
          };

      mAdaptee.addPacketListener(mSubscribePacketListener, filter);

      filter = new PacketTypeFilter(PingExtension.class);
      mAdaptee.addPacketListener(mPingListener, filter);

      mAdaptee.login(mLogin, mPassword, mResource);
      mUserInfo = new UserInfo(mAdaptee.getUser());

      mChatManager = new BeemChatManager(mAdaptee.getChatManager(), mService, mAdaptee.getRoster());
      // nikita: I commented this line because of the logs provided in
      // http://www.beem-project.com/issues/321
      // Also, since the privacylistmanager isn't finished and used, it will be safer to not
      // initialize it
      // mPrivacyListManager = new
      // PrivacyListManagerAdapter(PrivacyListManager.getInstanceFor(mAdaptee));
      mService.initJingle(mAdaptee);
      discoverServerFeatures();

      mRoster = new RosterAdapter(mAdaptee.getRoster(), mService, mAvatarManager);
      mApplication.setConnected(true);
      int mode = mPref.getInt(BeemApplication.STATUS_KEY, 0);
      String status = mPref.getString(BeemApplication.STATUS_TEXT_KEY, "");
      changeStatus(mode, status);
      return true;
    } catch (XMPPException e) {
      Log.e(TAG, "Error while connecting", e);
      mErrorMsg = mService.getString(R.string.error_login_authentication);
      return false;
    }
  }
示例#12
0
  /**
   * Constructor.
   *
   * @param connection The current active XMPPConnection.
   * @param remoteId The ID of the user to chat with. (May have a resource, but this will be used
   *     only as a hint for sending replies.)
   * @exception XMPPException If an error occurs joining the room.
   */
  public ChatWindow(XMPPConnection connection, String remoteId) throws XMPPException {
    mConnection = connection;
    mRemoteIdFull = remoteId;
    mRemoteIdBare = StringUtils.parseBareAddress(remoteId);

    if (!mRemoteIdFull.equals(mRemoteIdBare)) setLastKnownResource(mRemoteIdFull);

    mChatObject = new BetterChat(mConnection, mRemoteIdFull);

    // Get nickname for remote user and use for window title
    RosterEntry entry = mConnection.getRoster().getEntry(mRemoteIdBare);

    if (entry != null) {
      mRemoteNick = entry.getName();
    }

    if (mRemoteNick == null || mRemoteNick.equals("")) {
      mRemoteNick = mRemoteIdBare;
    }

    String val = JavolinApp.resources.getString("ChatWindow_WindowTitle");
    setTitle(JavolinApp.getAppName() + ": " + val + " " + mRemoteNick);

    // Get local user ID and chat color
    mLocalId = StringUtils.parseBareAddress(mConnection.getUser());
    mColorMap = new UserColorMap();
    mColorMap.getUserNameColor(mLocalId); // Give user first color

    // Set up UI
    buildUI();

    setSize(500, 400);
    mSizePosSaver = new SizeAndPositionSaver(this, NODENAME);
    restoreWindowState();

    // Send message when user presses Enter while editing input text
    mSendMessageAction =
        new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            doSendMessage();
          }
        };

    mInputText.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), mSendMessageAction);

    // Handle window events
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    addWindowListener(
        new WindowAdapter() {
          public void windowClosed(WindowEvent we) {
            saveWindowState();
            if (mLog != null) {
              mLog.dispose();
            }
            mColorMap.dispose();
          }

          public void windowOpened(WindowEvent we) {
            // Give focus to input text area when the window is created
            mInputText.requestFocusInWindow();
          }
        });

    /* We do *not* register as a message listener. The Smack Chat object is
     * kind of a crock; there's no documented way to turn off its packet
     * interception when we close this window. And the main JavolinApp
     * listener is already grabbing all CHAT and NORMAL message packets, so
     * there's no need for us to listen -- in fact, it leads to double
     * printing in some cases. */
  }
  public static void initialize(final XMPPConnection theConnection, final History h) {
    final String jid = XmppStringUtils.parseBareJid(theConnection.getUser());
    // Hash fetch service
    theConnection.registerIQRequestHandler(
        new IQRequestHandler() {

          @Override
          public IQ handleIQRequest(IQ iqRequest) {
            HistorySyncQuery query = (HistorySyncQuery) iqRequest;
            if (query.getType() != IQ.Type.get) {
              throw new Error();
            }
            if (!XmppStringUtils.parseBareJid(iqRequest.getFrom()).equals(jid)) {
              return error(query);
            }

            HistorySyncHashes response = query.reply(h);
            return response;
          }

          @Override
          public Mode getMode() {
            return Mode.async;
          }

          @Override
          public Type getType() {
            return Type.get;
          }

          @Override
          public String getElement() {
            return "query";
          }

          @Override
          public String getNamespace() {
            return "http://jlenet.de/histsync";
          }
        });

    // sync service
    theConnection.registerIQRequestHandler(
        new IQRequestHandler() {
          @Override
          public IQ handleIQRequest(IQ iqRequest) {
            HistorySyncSet sync = (HistorySyncSet) iqRequest;
            if (!XmppStringUtils.parseBareJid(iqRequest.getFrom()).equals(jid)) {
              return error(sync);
            }

            if (Debug.ENABLED) {
              System.out.println("sync pack");
            }
            HistoryLeafNode hln =
                (HistoryLeafNode) h.getAnyBlock(sync.getHour() * History.BASE, History.LEVELS);
            if (Debug.ENABLED) {
              System.out.println("Have: " + hln.getMessages().size());
              System.out.println("Got: " + sync.getMessages().size());
            }
            TreeSet<HistoryEntry> forMe = new TreeSet<HistoryEntry>();
            TreeSet<HistoryEntry> forOther = new TreeSet<HistoryEntry>();
            Iterator<HistoryEntry> have = hln.getMessages().iterator();
            Iterator<HistoryEntry> got = sync.getMessages().iterator();
            HistoryEntry currentGot = null;
            HistoryEntry currentHave = null;
            while (have.hasNext() || got.hasNext() || currentHave != null || currentGot != null) {
              if (currentGot == null && got.hasNext()) {
                currentGot = got.next();
              }
              if (currentHave == null && have.hasNext()) {
                currentHave = have.next();
              }
              if (currentHave == null && currentGot == null) {
                // Should never happen;
                System.out.println("this should never happen");
                break;
              }
              if (currentGot == null
                  || (currentHave != null && currentHave.compareTo(currentGot) < 0)) {
                // current Have is alone
                forOther.add(currentHave);
                currentHave = null;
              } else if (currentHave == null || currentHave.compareTo(currentGot) > 0) {
                // current Got is alone
                forMe.add(currentGot);
                currentGot = null;
              } else {
                currentHave = null;
                currentGot = null;
              }
            }
            hln.getMessages().addAll(forMe);
            h.modified(sync.getHour() * History.BASE);
            // Construct response
            HistorySyncSet hss =
                new HistorySyncSet(
                    sync.getHour(), History.beautifyChecksum(hln.getChecksum()), false);
            hss.setMessages(forOther);
            hss.setType(IQ.Type.result);
            hss.setTo(sync.getFrom());
            hss.setStanzaId(sync.getStanzaId());
            h.store();

            if (Debug.ENABLED) {
              System.out.println("now Have: " + hln.getMessages().size());
              System.out.println("adding: " + forMe.size());
              System.out.println("for other: " + forOther.size());
            }
            return hss;
          }

          @Override
          public Mode getMode() {
            return Mode.async;
          }

          @Override
          public Type getType() {
            return Type.set;
          }

          @Override
          public String getElement() {
            return "syncSet";
          }

          @Override
          public String getNamespace() {
            return "http://jlenet.de/histsync#syncSet";
          }
        });
    theConnection.registerIQRequestHandler(
        new IQRequestHandler() {

          @Override
          public IQ handleIQRequest(IQ iqRequest) {
            HistorySyncSet sync = (HistorySyncSet) iqRequest;
            if (!XmppStringUtils.parseBareJid(iqRequest.getFrom()).equals(jid)) {
              return error(sync);
            }
            HistoryLeafNode hln =
                (HistoryLeafNode) h.getAnyBlock(sync.getHour() * History.BASE, History.LEVELS);
            if (Debug.ENABLED) {
              System.out.println("Have: " + hln.getMessages().size());
              System.out.println("Got: " + sync.getMessages().size());
            }

            hln.getMessages().addAll(sync.getMessages());
            h.modified(sync.getHour() * History.BASE);
            h.store();

            byte[] myChecksum = hln.getChecksum();
            String status;
            if (!Arrays.equals(myChecksum, History.parseChecksum(sync.getChecksum()))) {
              status = "success";
            } else {
              status = "mismatch";
            }
            HistorySyncUpdateResponse hss = new HistorySyncUpdateResponse(status);
            hss.setType(IQ.Type.result);
            hss.setTo(sync.getFrom());
            hss.setStanzaId(sync.getStanzaId());
            if (Debug.ENABLED) {
              System.out.println("update was: " + status);
            }
            if (Debug.ENABLED) {
              System.out.println("now Have: " + hln.getMessages().size());
            }
            return hss;
          }

          @Override
          public Type getType() {
            return Type.set;
          }

          @Override
          public Mode getMode() {
            return Mode.async;
          }

          @Override
          public String getElement() {
            return "syncUpdate";
          }

          @Override
          public String getNamespace() {
            return "http://jlenet.de/histsync#syncUpdate";
          }
        });

    ProviderManager.addIQProvider(
        "query", "http://jlenet.de/histsync", new HistorySyncQueryProvider());
    ProviderManager.addIQProvider(
        "hashes", "http://jlenet.de/histsync#hashes", new HistorySyncResponseProvider());

    HistorySyncSetProvider setProvider = new HistorySyncSetProvider();
    ProviderManager.addIQProvider("syncSet", "http://jlenet.de/histsync#syncSet", setProvider);
    ProviderManager.addIQProvider(
        "syncUpdate", "http://jlenet.de/histsync#syncUpdate", setProvider);
    ProviderManager.addIQProvider(
        "syncStatus",
        "http://jlenet.de/histsync#syncStatus",
        new HistorySyncUpdateResponse.Provider());

    ServiceDiscoveryManager manager = ServiceDiscoveryManager.getInstanceFor(theConnection);
    manager.addFeature("http://jlenet.de/histsync#disco");
  }
 public String getLocalJid() throws FriendException {
   synchronized (this) {
     checkLoggedIn();
     return connection.getUser();
   }
 }
示例#15
0
 public static String jidForConnection(XMPPConnection c, String resource) {
   return c.getUser() + "@" + c.getHost() + (resource == null ? "" : "/" + resource);
 }
示例#16
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);
            }
          }
        }
      }
    }
  }
示例#17
0
  /**
   * 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;
  }
示例#18
0
 public String getBareJid() {
   String full = mXMPPConnection.getUser();
   String bare = full.replaceAll("/.*$", "");
   return bare;
 }
示例#19
0
 private AuctionMessageTranslator translatorFor(XMPPConnection connection) {
   // TODO: treaba asta cu announce() care returneaza un AuctionEventListener n-o prea pricep
   return new AuctionMessageTranslator(connection.getUser(), auctionEventListeners.announce());
 }