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); } }
@Override public void presenceChanged(Presence presence) { log.info("Presence Updated: " + presence.getFrom()); updated = true; presenceChanged.add(presence.getFrom()); }
private boolean hasOnlineStateChanged(Presence presence) { Presence last = lastPresenceMap.get(presence.getFrom()); lastPresenceMap.put(presence.getFrom(), presence); if (last == null) return false; return last.isAvailable() ^ presence.isAvailable(); }
@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); }
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) { } } } } }
private void handleIncomingSubscribe(Presence request) { final ContentValues values = new ContentValues(); values.put(RosterConstants.JID, request.getFrom()); values.put(RosterConstants.ALIAS, request.getFrom()); values.put(RosterConstants.GROUP, ""); values.put(RosterConstants.STATUS_MODE, getStatusInt(request)); values.put(RosterConstants.STATUS_MESSAGE, request.getStatus()); Uri uri = contentResolver.insert(RosterProvider.CONTENT_URI, values); Log.d(TAG, "handleIncomingSubscribe: faked " + uri); }
/** * 根据RosterEntry创建一个User * * @param entry * @return */ public User transEntryToUser(RosterEntry entry, Roster roster) { User user = new User(); user.setJID(entry.getUser()); Presence presence = roster.getPresence(entry.getUser()); user.setFrom(presence.getFrom()); user.setStatus(presence.getStatus()); user.setAvailable(presence.isAvailable()); user.setType(entry.getType()); // user.setvCard(userManager.getUserVCard(entry.getUser())); if (entry.getName() == null) { // if(user.getvCard()==null) // user.setName(StringUtil.getUserNameByJid(entry.getUser())); // else { // user.setName(user.getvCard().getNickName()); // } user.setName(StringUtil.getUserNameByJid(entry.getUser())); } else { user.setName(entry.getName()); } String avatar = UserManager.saveAvatar(entry.getUser(), context); user.setAvatar_path(avatar); return user; }
private XMPPFriendImpl getFriend(org.jivesoftware.smack.packet.Presence presence) { XMPPFriendImpl friend; synchronized (friends) { friend = friends.get(PresenceUtils.parseBareAddress(presence.getFrom())); } return friend; }
private void clearCache(Presence presence) { String rjid = presence.getFrom(); if (rjid == null) { LOG.error("presence.getFrom() is null"); return; } DiscoverInfoWrapper infoWrapper = cache.remove(rjid); if (infoWrapper != null) { if (infoWrapper.isAvailable()) { LOG.debug( "clearing cache entry of contact " + rjid + ": " + infoWrapper.item.getChildElementXML()); } else { LOG.debug( "clearing cache entry of contact " + rjid + " but cache entry is empty (a discovery is " + "still running or the last one failed)"); } } }
private void acceptSubscription(final Presence presence, boolean subscribe) { if (!isOnline()) return; myFacade.changeSubscription(presence.getFrom(), subscribe); if (subscribe) { String from = getSimpleId(presence.getFrom()); LOG.info("Add " + from + " to the roster"); try { getRoster().createEntry(from, from, new String[] {UserModel.DEFAULT_GROUP}); } catch (XMPPException e) { LOG.warn(e); } } }
/** * Updates user's changed presence * * @param presence */ public void presenceChanged(Presence presence) { String from = presence.getFrom(); // Log.i(tag, presence.getMode().toString()); new BuddiesController(context) .notifyPresenceChanged(from, presence.getMode(), presence.getStatus()); return; }
private String getCurrentJabberID(User user, RosterEntry rosterEntry) { Presence presence = _getPresence(user); String jabberId = null; if (presence != null) { jabberId = presence.getFrom(); } if (jabberId == null) jabberId = rosterEntry.getUser(); if (jabberId == null) jabberId = rosterEntry.getName(); return jabberId; }
@Override public void processPacket(Packet packet) { final Presence presence = ((Presence) packet); if (presence.getType() != Presence.Type.subscribe) return; LOG.info("Subscribe request from " + presence.getFrom()); if (myIgnoreList.isIgnored(presence.getFrom())) { LOG.info(presence.getFrom() + " in ignore list"); return; } if (isUserInMyContactListAndActive(presence.getFrom()) || Pico.isUnitTest()) { acceptSubscription(presence, true); return; } UIUtil.invokeLater( () -> acceptSubscription(presence, myUI.shouldAcceptSubscriptionRequest(presence))); }
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()); }
/** * There are two ways we initially learn about new peers. The first is a Lantern peer directly on * our roster, which will produce this event. The second is a kaleidoscope advertisement. Those * Kaleidoscope advertisements can be from peers on our roster, but they can also be from peers * we're not directly connected to. This method captures the first case where peers on our roster * are running Lantern. * * @param event The update presence event. */ @Subscribe public void onUpdatePresenceEvent(final UpdatePresenceEvent event) { log.debug("Processing presence event"); final Presence presence = event.getPresence(); final String from = presence.getFrom(); if (StringUtils.isBlank(from)) { log.warn("Presence with blank from?"); } else { addPeer(LanternUtils.newURI(from), Type.pc); } }
// 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); } }
@Override public void presenceChanged(final org.jivesoftware.smack.packet.Presence presence) { String localJID; try { localJID = getLocalJid(); } catch (FriendException e) { localJID = null; } if (!presence.getFrom().equals(localJID)) { XMPPFriendImpl friend = getFriend(presence); if (friend != null) { LOG.debugf("presence from {0} changed to {1}", presence.getFrom(), presence.getType()); // synchronize to avoid updates or presences from being lost // better to replace that with a lock object private to this // connection class synchronized (friend) { if (presence.getType().equals(org.jivesoftware.smack.packet.Presence.Type.available)) { if (!friend.getPresences().containsKey(presence.getFrom())) { addNewPresence(friend, presence); } else { updatePresence(friend, presence); } } else if (presence .getType() .equals(org.jivesoftware.smack.packet.Presence.Type.unavailable)) { PresenceImpl p = (PresenceImpl) friend.getPresence(presence.getFrom()); if (p != null) { p.update(presence); friend.removePresense(p); } } } } else { LOG.debugf("no friend for presence {0}", presence.getFrom()); } } }
/** * Returns the RQ-JIDs of all presences of the given (plain) JID which are available. * * <p>An empty list is returned if no presence for the given JID is online. */ public List<JID> getAvailablePresences(JID from) { List<JID> result = new ArrayList<JID>(); for (Presence presence : getPresences(from)) { if (!presence.isAvailable()) continue; String rjid = presence.getFrom(); if (rjid == null) { LOG.error("presence.getFrom() is null"); continue; } result.add(new JID(rjid)); } return result; }
/** * Returns the RQ-JID of given plain JID supporting the feature of the given name-space if * available, otherwise null. * * <p>If not in the cache then a blocking cache update is performed. * * @param jid The JID of the user to find a supporting presence for. The JID can be resource * qualified in which case the resource is stripped, before performing the look-up. * @blocking This method blocks until the ServiceDiscovery returns. * @reentrant This method can be called concurrently. * @caching If results are available in the cache, they are used instead of querying the server. */ public JID getSupportingPresence(final JID jid, final String namespace) { checkJID(jid); for (Presence presence : rosterTracker.getPresences(jid.getBareJID())) { if (!presence.isAvailable()) continue; String rjid = presence.getFrom(); if (rjid == null) { LOG.error("presence.getFrom() is null"); continue; } JID jidToCheck = new JID(rjid); Boolean supported = queryFeatureSupport(jidToCheck, namespace); if (supported != null && supported) return jidToCheck; } return null; }
public void sendFile(String filename) throws XMPPException { Presence pre = connection.getRoster().getPresence("*****@*****.**"); System.out.println(pre); if (pre.getType() != Presence.Type.unavailable) { if (fileTransferManager == null) { initFileTransport(); } FileTransferManager manager = new FileTransferManager(connection); // 创建输出的文件传输 OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(pre.getFrom()); // 发送文件 transfer.sendFile(new File(filename), "图片"); // while (!transfer.isDone()) { // if (transfer.getStatus() == FileTransfer.Status.in_progress) { // // 可以调用transfer.getProgress();获得传输的进度 // System.out.println(transfer.getStatus()); // System.out.println(transfer.getProgress()); // System.out.println(transfer.isDone()); // } // } } }
@Override public void processPacket(Packet packet) { if (!(packet instanceof Presence)) return; Presence p = (Presence) packet; if (p.getType() != Presence.Type.subscribe) return; String from = p.getFrom(); Notification notification = new Notification( android.R.drawable.stat_notify_more, mService.getString(R.string.AcceptContactRequest, from), System.currentTimeMillis()); notification.flags = Notification.FLAG_AUTO_CANCEL; Intent intent = new Intent(mService, Subscription.class); intent.setData(Contact.makeXmppUri(from)); notification.setLatestEventInfo( mService, from, mService.getString(R.string.AcceptContactRequestFrom, from), PendingIntent.getActivity(mService, 0, intent, PendingIntent.FLAG_ONE_SHOT)); int id = p.hashCode(); mService.sendNotification(id, notification); }
private void updatePresence( XMPPFriendImpl friend, org.jivesoftware.smack.packet.Presence presence) { PresenceImpl currentPresence = (PresenceImpl) friend.getPresences().get(presence.getFrom()); currentPresence.update(presence); friend.updatePresence(currentPresence); }
/** * Handles presence stanzas * * @param presence */ private void handlePresence(Presence presence) { // unavailable is sent when user leaves the room if (!presence.isAvailable()) { return; } String from = presence.getFrom(); JitsiMeetConference conference = getConferenceForMucJid(from); if (conference == null) { if (logger.isDebugEnabled()) { logger.debug("Room not found for JID: " + from); } return; } ChatRoomMemberRole role = conference.getRoleForMucJid(from); if (role != null && role.compareTo(ChatRoomMemberRole.MODERATOR) < 0) { StartMutedPacketExtension ext = (StartMutedPacketExtension) presence.getExtension( StartMutedPacketExtension.ELEMENT_NAME, StartMutedPacketExtension.NAMESPACE); if (ext != null) { boolean[] startMuted = {ext.getAudioMuted(), ext.getVideoMuted()}; conference.setStartMuted(startMuted); } } Participant participant = conference.findParticipantForRoomJid(from); ColibriConference colibriConference = conference.getColibriConference(); if (participant != null && colibriConference != null) { // Check if this conference is valid String conferenceId = colibriConference.getConferenceId(); if (StringUtils.isNullOrEmpty(conferenceId)) { logger.error("Unable to send DisplayNameChanged event" + " - no conference id"); return; } // Check for changes to the display name String oldDisplayName = participant.getDisplayName(); String newDisplayName = null; for (PacketExtension pe : presence.getExtensions()) { if (pe instanceof Nick) { newDisplayName = ((Nick) pe).getName(); break; } } if (!Objects.equals(oldDisplayName, newDisplayName)) { participant.setDisplayName(newDisplayName); EventAdmin eventAdmin = FocusBundleActivator.getEventAdmin(); if (eventAdmin != null) { // Prevent NPE when adding to event hashtable if (newDisplayName == null) { newDisplayName = ""; } eventAdmin.sendEvent( EventFactory.endpointDisplayNameChanged( conferenceId, participant.getEndpointId(), newDisplayName)); } } } }
/* * 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); } }
/** * Sends a file transfer request to the given <tt>toContact</tt>. * * @return the transfer object * @param toContact the contact that should receive the file * @param file file to send * @param gw special gateway to be used for receiver if its jid misses the domain part */ FileTransfer sendFile(Contact toContact, File file, String gw) throws IllegalStateException, IllegalArgumentException, OperationNotSupportedException { OutgoingFileTransferJabberImpl outgoingTransfer = null; try { assertConnected(); if (file.length() > getMaximumFileLength()) throw new IllegalArgumentException("File length exceeds the allowed one for this protocol"); String fullJid = null; // Find the jid of the contact which support file transfer // and is with highest priority if more than one found // if we have equals priorities // choose the one that is more available OperationSetMultiUserChat mucOpSet = jabberProvider.getOperationSet(OperationSetMultiUserChat.class); if (mucOpSet != null && mucOpSet.isPrivateMessagingContact(toContact.getAddress())) { fullJid = toContact.getAddress(); } else { Iterator<Presence> iter = jabberProvider.getConnection().getRoster().getPresences(toContact.getAddress()); int bestPriority = -1; PresenceStatus jabberStatus = null; while (iter.hasNext()) { Presence presence = iter.next(); if (jabberProvider.isFeatureListSupported( presence.getFrom(), new String[] { "http://jabber.org/protocol/si", "http://jabber.org/protocol/si/profile/file-transfer" })) { int priority = (presence.getPriority() == Integer.MIN_VALUE) ? 0 : presence.getPriority(); if (priority > bestPriority) { bestPriority = priority; fullJid = presence.getFrom(); jabberStatus = OperationSetPersistentPresenceJabberImpl.jabberStatusToPresenceStatus( presence, jabberProvider); } else if (priority == bestPriority && jabberStatus != null) { PresenceStatus tempStatus = OperationSetPersistentPresenceJabberImpl.jabberStatusToPresenceStatus( presence, jabberProvider); if (tempStatus.compareTo(jabberStatus) > 0) { fullJid = presence.getFrom(); jabberStatus = tempStatus; } } } } } // First we check if file transfer is at all supported for this // contact. if (fullJid == null) { throw new OperationNotSupportedException( "Contact client or server does not support file transfers."); } if (gw != null && !fullJid.contains("@") && !fullJid.endsWith(gw)) { fullJid = fullJid + "@" + gw; } OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(fullJid); outgoingTransfer = new OutgoingFileTransferJabberImpl(toContact, file, transfer, jabberProvider); // Notify all interested listeners that a file transfer has been // created. FileTransferCreatedEvent event = new FileTransferCreatedEvent(outgoingTransfer, new Date()); fireFileTransferCreated(event); // Send the file through the Jabber file transfer. transfer.sendFile(file, "Sending file"); // Start the status and progress thread. new FileTransferProgressThread(transfer, outgoingTransfer).start(); } catch (XMPPException e) { logger.error("Failed to send file.", e); } return outgoingTransfer; }
/** * Returns the users full jid (ex. [email protected]/spark). * * @return the users Full JID. */ public String getJID() { presence = PresenceManager.getPresence(getParticipantJID()); return presence.getFrom(); }