private Packet getPresenceForMode(FriendPresence.Mode mode) {
   org.jivesoftware.smack.packet.Presence presence =
       new org.jivesoftware.smack.packet.Presence(
           org.jivesoftware.smack.packet.Presence.Type.available);
   presence.setMode(org.jivesoftware.smack.packet.Presence.Mode.valueOf(mode.name()));
   if (jabberSettings.advertiseLimeWireStatus()) {
     presence.setStatus("on LimeWire");
   }
   return presence;
 }
Esempio n. 2
0
  public void setStatusFromConfig() {
    CarbonManager.getInstanceFor(extXMPPConnection)
        .sendCarbonsEnabled(configuration.messageCarbons);

    Presence presence = new Presence(Presence.Type.available);
    Mode mode = Mode.valueOf(configuration.statusMode);
    presence.setMode(mode);
    presence.setStatus(configuration.statusMessage);
    presence.setPriority(configuration.priority);
    extXMPPConnection.sendPacket(presence);
    configuration.presence_required = false;
  }
Esempio n. 3
0
  public void setStatusFromConfig() {
    // TODO: only call this when carbons changed, not on every presence change
    CarbonManager.getInstanceFor(mXMPPConnection).sendCarbonsEnabled(mConfig.messageCarbons);

    Presence presence = new Presence(Presence.Type.available);
    Mode mode = Mode.valueOf(mConfig.statusMode);
    presence.setMode(mode);
    presence.setStatus(mConfig.statusMessage);
    presence.setPriority(mConfig.priority);
    mXMPPConnection.sendPacket(presence);
    mConfig.presence_required = false;
  }
Esempio n. 4
0
 /**
  * Returns a (legacy/Smack-based) Presence stanza that represents the current presence of this
  * session. The Presence includes relevant Mode, Status and VCardUpdate information.
  *
  * <p>This method uses the fields {@link TransportSession#presence} and {@link
  * TransportSession#verboseStatus} to generate the result.
  *
  * @return A Presence packet representing the current presence state of this session.
  */
 public Presence constructCurrentLegacyPresencePacket() {
   final org.jivesoftware.smack.packet.Presence presence =
       new org.jivesoftware.smack.packet.Presence(
           org.jivesoftware.smack.packet.Presence.Type.available);
   final Presence.Mode pMode =
       ((XMPPTransport) getTransport()).convertGatewayStatusToXMPP(this.presence);
   if (pMode != null) {
     presence.setMode(pMode);
   }
   if (verboseStatus != null && verboseStatus.trim().length() > 0) {
     presence.setStatus(verboseStatus);
   }
   final Avatar avatar = getAvatar();
   if (avatar != null) {
     final VCardUpdateExtension ext = new VCardUpdateExtension();
     ext.setPhotoHash(avatar.getLegacyIdentifier());
     presence.addExtension(ext);
   }
   return presence;
 }
 /** {@inheritDoc} */
 @Override
 public void changeStatusAndPriority(int status, String msg, int priority) {
   Presence pres = new Presence(Presence.Type.available);
   String m;
   if (msg != null) m = msg;
   else m = mPreviousStatus;
   pres.setStatus(m);
   mPreviousStatus = m;
   Presence.Mode mode = Status.getPresenceModeFromStatus(status);
   if (mode != null) {
     pres.setMode(mode);
     mPreviousMode = status;
   } else {
     pres.setMode(Status.getPresenceModeFromStatus(mPreviousMode));
   }
   int p = priority;
   if (priority < SMACK_PRIORITY_MIN) p = SMACK_PRIORITY_MIN;
   if (priority > SMACK_PRIORITY_MAX) p = SMACK_PRIORITY_MAX;
   mPreviousPriority = p;
   pres.setPriority(p);
   mAdaptee.sendPacket(pres);
   updateNotification(m);
 }
Esempio n. 6
0
  /** @see net.sf.kraken.session.TransportSession#logIn(net.sf.kraken.type.PresenceType, String) */
  @Override
  public void logIn(PresenceType presenceType, String verboseStatus) {
    final org.jivesoftware.smack.packet.Presence presence =
        new org.jivesoftware.smack.packet.Presence(
            org.jivesoftware.smack.packet.Presence.Type.available);
    if (JiveGlobals.getBooleanProperty(
            "plugin.gateway." + getTransport().getType() + ".avatars", true)
        && getAvatar() != null) {
      Avatar avatar = getAvatar();
      // Same thing in this case, so lets go ahead and set them.
      avatar.setLegacyIdentifier(avatar.getXmppHash());
      VCardUpdateExtension ext = new VCardUpdateExtension();
      ext.setPhotoHash(avatar.getLegacyIdentifier());
      presence.addExtension(ext);
    }
    final Presence.Mode pMode =
        ((XMPPTransport) getTransport()).convertGatewayStatusToXMPP(presenceType);
    if (pMode != null) {
      presence.setMode(pMode);
    }
    if (verboseStatus != null && verboseStatus.trim().length() > 0) {
      presence.setStatus(verboseStatus);
    }
    setPendingPresenceAndStatus(presenceType, verboseStatus);

    if (!this.isLoggedIn()) {
      listener = new XMPPListener(this);
      presenceHandler = new XMPPPresenceHandler(this);
      runThread =
          new Thread() {
            @Override
            public void run() {
              String userName = generateUsername(registration.getUsername());
              conn = new XMPPConnection(config);
              try {
                conn.getSASLAuthentication()
                    .registerSASLMechanism("DIGEST-MD5", MySASLDigestMD5Mechanism.class);
                if (getTransport().getType().equals(TransportType.facebook)
                    && registration.getUsername().equals("{PLATFORM}")) {
                  conn.getSASLAuthentication()
                      .registerSASLMechanism(
                          "X-FACEBOOK-PLATFORM", FacebookConnectSASLMechanism.class);
                  conn.getSASLAuthentication().supportSASLMechanism("X-FACEBOOK-PLATFORM", 0);
                }

                Roster.setDefaultSubscriptionMode(SubscriptionMode.manual);
                conn.connect();
                conn.addConnectionListener(listener);
                try {
                  conn.addPacketListener(
                      presenceHandler,
                      new PacketTypeFilter(org.jivesoftware.smack.packet.Presence.class));
                  // Use this to filter out anything we don't care about
                  conn.addPacketListener(
                      listener,
                      new OrFilter(
                          new PacketTypeFilter(GoogleMailBoxPacket.class),
                          new PacketExtensionFilter(
                              GoogleNewMailExtension.ELEMENT_NAME,
                              GoogleNewMailExtension.NAMESPACE)));
                  conn.login(userName, registration.getPassword(), xmppResource);
                  conn.sendPacket(presence); // send initial presence.
                  conn.getChatManager().addChatListener(listener);
                  conn.getRoster().addRosterListener(listener);

                  if (JiveGlobals.getBooleanProperty(
                          "plugin.gateway." + getTransport().getType() + ".avatars",
                          !TransportType.facebook.equals(getTransport().getType()))
                      && getAvatar() != null) {
                    new Thread() {
                      @Override
                      public void run() {
                        Avatar avatar = getAvatar();

                        VCard vCard = new VCard();
                        try {
                          vCard.load(conn);
                          vCard.setAvatar(
                              Base64.decode(avatar.getImageData()), avatar.getMimeType());
                          vCard.save(conn);
                        } catch (XMPPException e) {
                          Log.debug("XMPP: Error while updating vcard for avatar change.", e);
                        } catch (NotFoundException e) {
                          Log.debug("XMPP: Unable to find avatar while setting initial.", e);
                        }
                      }
                    }.start();
                  }

                  setLoginStatus(TransportLoginStatus.LOGGED_IN);
                  syncUsers();

                  if (getTransport().getType().equals(TransportType.gtalk)
                      && JiveGlobals.getBooleanProperty(
                          "plugin.gateway.gtalk.mailnotifications", true)) {
                    conn.sendPacket(
                        new IQWithPacketExtension(
                            generateFullJID(getRegistration().getUsername()),
                            new GoogleUserSettingExtension(null, true, null),
                            IQ.Type.SET));
                    conn.sendPacket(
                        new IQWithPacketExtension(
                            generateFullJID(getRegistration().getUsername()),
                            new GoogleMailNotifyExtension()));
                    mailCheck = new MailCheck();
                    timer.schedule(mailCheck, timerInterval, timerInterval);
                  }
                } catch (XMPPException e) {
                  Log.debug(
                      getTransport().getType()
                          + " user's login/password does not appear to be correct: "
                          + getRegistration().getUsername(),
                      e);
                  setFailureStatus(ConnectionFailureReason.USERNAME_OR_PASSWORD_INCORRECT);
                  sessionDisconnectedNoReconnect(
                      LocaleUtils.getLocalizedString("gateway.xmpp.passwordincorrect", "kraken"));
                }
              } catch (XMPPException e) {
                Log.debug(
                    getTransport().getType()
                        + " user is not able to connect: "
                        + getRegistration().getUsername(),
                    e);
                setFailureStatus(ConnectionFailureReason.CAN_NOT_CONNECT);
                sessionDisconnected(
                    LocaleUtils.getLocalizedString("gateway.xmpp.connectionfailed", "kraken"));
              }
            }
          };
      runThread.start();
    }
  }
  /**
   * Parses a presence packet.
   *
   * @param parser the XML parser, positioned at the start of a presence packet.
   * @return a Presence packet.
   * @throws Exception if an exception occurs while parsing the packet.
   */
  public static Presence parsePresence(XmlPullParser parser) throws Exception {
    Presence.Type type = Presence.Type.available;
    String typeString = parser.getAttributeValue("", "type");
    if (typeString != null && !typeString.equals("")) {
      try {
        type = Presence.Type.valueOf(typeString);
      } catch (IllegalArgumentException iae) {
        System.err.println("Found invalid presence type " + typeString);
      }
    }
    Presence presence = new Presence(type);
    presence.setTo(parser.getAttributeValue("", "to"));
    presence.setFrom(parser.getAttributeValue("", "from"));
    String id = parser.getAttributeValue("", "id");
    presence.setPacketID(id == null ? Packet.ID_NOT_AVAILABLE : id);

    String language = getLanguageAttribute(parser);
    if (language != null && !"".equals(language.trim())) {
      presence.setLanguage(language);
    }
    presence.setPacketID(id == null ? Packet.ID_NOT_AVAILABLE : id);

    // Parse sub-elements
    boolean done = false;
    while (!done) {
      int eventType = parser.next();
      if (eventType == XmlPullParser.START_TAG) {
        String elementName = parser.getName();
        String namespace = parser.getNamespace();
        if (elementName.equals("status")) {
          presence.setStatus(parser.nextText());
        } else if (elementName.equals("priority")) {
          try {
            int priority = Integer.parseInt(parser.nextText());
            presence.setPriority(priority);
          } catch (NumberFormatException nfe) {
            // Ignore.
          } catch (IllegalArgumentException iae) {
            // Presence priority is out of range so assume priority to be zero
            presence.setPriority(0);
          }
        } else if (elementName.equals("show")) {
          String modeText = parser.nextText();
          try {
            presence.setMode(Presence.Mode.valueOf(modeText));
          } catch (IllegalArgumentException iae) {
            System.err.println("Found invalid presence mode " + modeText);
          }
        } else if (elementName.equals("error")) {
          presence.setError(parseError(parser));
        } else if (elementName.equals("properties") && namespace.equals(PROPERTIES_NAMESPACE)) {
          Map<String, Object> properties = parseProperties(parser);
          // Set packet properties.
          for (String name : properties.keySet()) {
            presence.setProperty(name, properties.get(name));
          }
        }
        // Otherwise, it must be a packet extension.
        else {
          try {
            presence.addExtension(
                PacketParserUtils.parsePacketExtension(elementName, namespace, parser));
          } catch (Exception e) {
            System.err.println("Failed to parse extension packet in Presence packet.");
          }
        }
      } else if (eventType == XmlPullParser.END_TAG) {
        if (parser.getName().equals("presence")) {
          done = true;
        }
      }
    }
    return presence;
  }
Esempio n. 8
0
 public void updateStateMessage(String status) {
   Presence presence = new Presence(Presence.Type.available);
   presence.setStatus(status);
   connection.sendPacket(presence);
 }
  public static Boolean doUserCommand(String command, String jid, String admin)
      throws XMPPException, IOException, NumberFormatException, ClassNotFoundException,
          SQLException, ParseException {
    Boolean ans = false;
    String msg = null;

    if (command.startsWith("!report") && !ans) {
      command = new StringBuffer(command).delete(0, 7).toString();
      msg = command + " - " + jid;
      XmppNet.sendMessage(admin, msg);
      ans = true;
    }

    if (command.startsWith("!list") && !ans) {
      java.util.Date today = new java.util.Date();
      long time = (System.currentTimeMillis());
      msg = Sql.listOfTimer(jid, time);
      XmppNet.sendMessage(jid, msg);
      ans = true;
    }

    if (command.startsWith("!remind") && !ans) {
      command = command.replaceAll("!remind ", "");
      java.util.Date today = new java.util.Date();
      long time = (System.currentTimeMillis());
      StringTokenizer st = new StringTokenizer(command, "@");
      String noteU = "";

      while (st.hasMoreTokens()) {
        command = st.nextToken();
        if (!st.hasMoreElements()) {
          NullNoteEx(jid);
        }
        noteU = st.nextToken();
      }
      SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
      Date dt = null;
      try {
        dt = sdf.parse(command);
      } catch (ParseException e) {
        msg = "Wrong date!";
        XmppNet.sendMessage(jid, msg);
        ans = true;
      }

      long dt1 = dt.getTime() / 1000;
      if (!ans) {
        if (dt1 > (time / 1000)) {
          Sql.add(dt1, jid, Main.id, noteU);
          msg = "Timer is set!";
        } else {
          msg = "Wrong date";
        }
      }
      XmppNet.sendMessage(jid, msg);
      ans = true;
      Main.id++;
    }

    if (command.startsWith("!note") && !ans) {
      command = command.replaceAll("!note ", "");
      Long time = 0L;
      if (!ans) {
        Sql.add(time, jid, Main.id, command);
      }
      ans = true;
      msg = "Writed!";
      XmppNet.sendMessage(jid, msg);
      Main.id++;
    }

    if (command.startsWith("!my") && !ans) {
      msg = Sql.listOfNote(jid);
      ans = true;
      XmppNet.sendMessage(jid, msg);
      Main.id++;
    }

    if (command.startsWith("!del") && !ans) {
      command = command.replaceAll("!del #", "");
      if (!ans) {
        Sql.deleteNote(jid, command);
      }
      ans = true;
      msg = "Command complete";
      XmppNet.sendMessage(jid, msg);
      Main.id++;
    }

    try {
      if (command.startsWith("!timer") && !ans) {
        command = command.replaceAll("!timer ", "");
        java.util.Date today = new java.util.Date();
        long time = (System.currentTimeMillis());
        StringTokenizer st = new StringTokenizer(command, "@");
        String noteU = "";
        while (st.hasMoreTokens()) {
          command = st.nextToken();
          if (!st.hasMoreElements()) {
            NullNoteEx(jid);
          }
          noteU = st.nextToken();
        }
        if (Long.parseLong(command) < 1 || Long.parseLong(command) > 120) {
          throw new NumberFormatException();
        }
        long timeDo = ((time + Long.parseLong(command) * 1000 * 60) / 1000L);
        if (!ans) {
          Sql.add(timeDo, jid, Main.id, noteU);
        }
        ans = true;
        msg = "Timer is set!";
        XmppNet.sendMessage(jid, msg);
        Main.id++;
      }
    } catch (NumberFormatException ex1) {
      ans = true;
      XmppNet.sendMessage(
          jid, "Wrong timer interval \n" + "The permissible range of 1 to 120 minutes.");
    }

    if (command.startsWith("!off") && !ans && jid.startsWith(admin)) {
      XmppNet.disconnect();
      ans = true;
    }

    if (command.startsWith("!roster") && !ans && jid.startsWith(admin)) {
      msg = XmppNet.getXmppRoster();
      XmppNet.sendMessage(jid, msg);
      ans = true;
    }

    if (command.startsWith("!status") && !ans && jid.startsWith(admin)) {
      command = new StringBuffer(command).delete(0, 8).toString();
      String status = command;
      Presence presence = new Presence(Presence.Type.available);
      presence.setStatus(status);
      XmppNet.connection.sendPacket(presence);
      ans = true;
    }

    if (command.equals("!help")) {
      msg =
          "Commands: \n"
              + "!report <message> - send <message> to admin \n \n"
              + "!remind <dd.mm.yyyy HH:mm>@<remind> - set a reminder on this date \n"
              + " For example  !remind 03.10.2012 18:51@Hello \n \n"
              + "!timer <minutes>@<remind> - set timer. \n"
              + "  For example '!timer 2@Hello' send after 2 minutes 'Hello' \n \n"
              + "!list - list of installed timers \n \n"
              + "Notes: \n"
              + "!my - list of notes \n"
              + "!note 'text' - write note \n"
              + "!del #1234567890 - delete note with number #1234567890 \n";
      if (jid.startsWith(admin)) {
        msg +=
            "---------------------\n"
                + "!roster - show bot`s roster \n"
                + "!status <new_status> - change status \n"
                + "!off - offline this bot \n";
      }
      XmppNet.sendMessage(jid, msg);
      ans = true;
    }

    return ans;
  }
Esempio n. 10
0
 public void setStatus(boolean available, String status) {
   Presence.Type type = available ? Type.available : Type.unavailable;
   Presence presence = new Presence(type);
   presence.setStatus(status);
   connection.sendPacket(presence);
 }