/** * Sends a typing notification state. * * @param typingState the typing notification state to send * @return the result of this operation. One of the TYPING_NOTIFICATION_XXX constants defined in * this class */ public int sendTypingNotification(int typingState) { // If this chat transport does not support sms messaging we do // nothing here. if (!allowsTypingNotifications()) return -1; ProtocolProviderService protocolProvider = contact.getProtocolProvider(); OperationSetTypingNotifications tnOperationSet = protocolProvider.getOperationSet(OperationSetTypingNotifications.class); // if protocol is not registered or contact is offline don't // try to send typing notifications if (protocolProvider.isRegistered() && contact.getPresenceStatus().getStatus() >= PresenceStatus.ONLINE_THRESHOLD) { try { tnOperationSet.sendTypingNotification(contact, typingState); return ChatPanel.TYPING_NOTIFICATION_SUCCESSFULLY_SENT; } catch (Exception ex) { logger.error("Failed to send typing notifications.", ex); return ChatPanel.TYPING_NOTIFICATION_SEND_FAILED; } } return ChatPanel.TYPING_NOTIFICATION_SEND_FAILED; }
/** * Permanently removes locally stored message history for the metacontact, remove any recent * contacts if any. */ public void eraseLocallyStoredHistory(MetaContact contact) throws IOException { List<ComparableEvtObj> toRemove = null; synchronized (recentMessages) { toRemove = new ArrayList<ComparableEvtObj>(); Iterator<Contact> iter = contact.getContacts(); while (iter.hasNext()) { Contact item = iter.next(); String id = item.getAddress(); ProtocolProviderService provider = item.getProtocolProvider(); for (ComparableEvtObj msc : recentMessages) { if (msc.getProtocolProviderService().equals(provider) && msc.getContactAddress().equals(id)) { toRemove.add(msc); } } } recentMessages.removeAll(toRemove); } if (recentQuery != null) { for (ComparableEvtObj msc : toRemove) { recentQuery.fireContactRemoved(msc); } } }
/** * Sends the given file through this chat transport file transfer operation set. * * @param file the file to send * @return the <tt>FileTransfer</tt> object charged to transfer the file * @throws Exception if anything goes wrong */ public FileTransfer sendFile(File file) throws Exception { // If this chat transport does not support instant messaging we do // nothing here. if (!allowsFileTransfer()) return null; OperationSetFileTransfer ftOpSet = contact.getProtocolProvider().getOperationSet(OperationSetFileTransfer.class); if (FileUtils.isImage(file.getName())) { // Create a thumbnailed file if possible. OperationSetThumbnailedFileFactory tfOpSet = contact.getProtocolProvider().getOperationSet(OperationSetThumbnailedFileFactory.class); if (tfOpSet != null) { byte[] thumbnail = getFileThumbnail(file); if (thumbnail != null && thumbnail.length > 0) { file = tfOpSet.createFileWithThumbnail( file, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, "image/png", thumbnail); } } } return ftOpSet.sendFile(contact, file); }
public void run() { if (telephony == null) return; Call createdCall = null; if (contacts != null) { Contact contact = (Contact) contacts.get(0); // NOTE: The multi user call is not yet implemented! // We just get the first contact and create a call for him. try { createdCall = telephony.createCall(contact); } catch (OperationFailedException e) { logger.error("The call could not be created: " + e); callPanel.getParticipantPanel(contact.getDisplayName()).setState(e.getMessage()); removeCallPanelWait(callPanel); } // If the call is successfully created we set the created // Call instance to the already existing CallPanel and we // add this call to the active calls. if (createdCall != null) { callPanel.setCall(createdCall, GuiCallParticipantRecord.OUTGOING_CALL); activeCalls.put(createdCall, callPanel); } } else { try { createdCall = telephony.createCall(stringContact); } catch (ParseException e) { logger.error("The call could not be created: " + e); callPanel.getParticipantPanel(stringContact).setState(e.getMessage()); removeCallPanelWait(callPanel); } catch (OperationFailedException e) { logger.error("The call could not be created: " + e); callPanel.getParticipantPanel(stringContact).setState(e.getMessage()); removeCallPanelWait(callPanel); } // If the call is successfully created we set the created // Call instance to the already existing CallPanel and we // add this call to the active calls. if (createdCall != null) { callPanel.setCall(createdCall, GuiCallParticipantRecord.OUTGOING_CALL); activeCalls.put(createdCall, callPanel); } } }
/** * Shows a warning message to the user when message delivery has failed. * * @param evt the event containing details on the message delivery failure */ public void messageDeliveryFailed(MessageDeliveryFailedEvent evt) { logger.error(evt.getReason()); String errorMsg = null; Message sourceMessage = (Message) evt.getSource(); Contact sourceContact = evt.getDestinationContact(); MetaContact metaContact = GuiActivator.getContactListService().findMetaContactByContact(sourceContact); if (evt.getErrorCode() == MessageDeliveryFailedEvent.OFFLINE_MESSAGES_NOT_SUPPORTED) { errorMsg = GuiActivator.getResources() .getI18NString( "service.gui.MSG_DELIVERY_NOT_SUPPORTED", new String[] {sourceContact.getDisplayName()}); } else if (evt.getErrorCode() == MessageDeliveryFailedEvent.NETWORK_FAILURE) { errorMsg = GuiActivator.getResources().getI18NString("service.gui.MSG_NOT_DELIVERED"); } else if (evt.getErrorCode() == MessageDeliveryFailedEvent.PROVIDER_NOT_REGISTERED) { errorMsg = GuiActivator.getResources().getI18NString("service.gui.MSG_SEND_CONNECTION_PROBLEM"); } else if (evt.getErrorCode() == MessageDeliveryFailedEvent.INTERNAL_ERROR) { errorMsg = GuiActivator.getResources().getI18NString("service.gui.MSG_DELIVERY_INTERNAL_ERROR"); } else { errorMsg = GuiActivator.getResources().getI18NString("service.gui.MSG_DELIVERY_ERROR"); } String reason = evt.getReason(); if (reason != null) errorMsg += " " + GuiActivator.getResources() .getI18NString("service.gui.ERROR_WAS", new String[] {reason}); ChatPanel chatPanel = chatWindowManager.getContactChat(metaContact, sourceContact); chatPanel.addMessage( sourceContact.getAddress(), metaContact.getDisplayName(), new Date(), Chat.OUTGOING_MESSAGE, sourceMessage.getContent(), sourceMessage.getContentType(), sourceMessage.getMessageUID(), evt.getCorrectedMessageUID()); chatPanel.addErrorMessage(metaContact.getDisplayName(), errorMsg); chatWindowManager.openChat(chatPanel, false); }
@Override public void supportedOperationSetsChanged(ContactCapabilitiesEvent event) { Contact contact = event.getSourceContact(); if (contact == null) return; for (ComparableEvtObj msc : recentMessages) { if (contact.equals(msc.getContact())) { if (recentQuery != null) recentQuery.updateCapabilities(msc, contact); return; } } }
/** * Determines whether the protocol supports the supplied content type for the given contact. * * @param contentType the type we want to check * @param contact contact which is checked for supported contentType * @return <tt>true</tt> if the contact supports it and <tt>false</tt> otherwise. */ @Override public boolean isContentTypeSupported(String contentType, Contact contact) { // by default we support default mime type, for other mimetypes // method must be overriden if (contentType.equals(DEFAULT_MIME_TYPE)) return true; else if (contentType.equals(HTML_MIME_TYPE)) { String toJID = recentJIDForAddress.get(contact.getAddress()); if (toJID == null) toJID = contact.getAddress(); return jabberProvider.isFeatureListSupported(toJID, HTML_NAMESPACE); } return false; }
/** * Returns <code>true</code> if this chat transport supports typing notifications, otherwise * returns <code>false</code>. * * @return <code>true</code> if this chat transport supports typing notifications, otherwise * returns <code>false</code>. */ public boolean allowsTypingNotifications() { Object tnOpSet = contact.getProtocolProvider().getOperationSet(OperationSetTypingNotifications.class); if (tnOpSet != null) return true; else return false; }
/** * Sends the given sms message trough this chat transport. * * @param phoneNumber phone number of the destination * @param messageText The message to send. * @throws Exception if the send operation is interrupted */ public void sendSmsMessage(String phoneNumber, String messageText) throws Exception { // If this chat transport does not support sms messaging we do // nothing here. if (!allowsSmsMessage()) return; SMSManager.sendSMS(contact.getProtocolProvider(), phoneNumber, messageText); }
/** * Determines whether this chat transport supports the supplied content type * * @param contentType the type we want to check * @return <tt>true</tt> if the chat transport supports it and <tt>false</tt> otherwise. */ public boolean isContentTypeSupported(String contentType) { OperationSetBasicInstantMessaging imOpSet = contact.getProtocolProvider().getOperationSet(OperationSetBasicInstantMessaging.class); if (imOpSet != null) return imOpSet.isContentTypeSupported(contentType); else return false; }
/** * If a contact is renamed update the locally stored message if any. * * @param evt the <tt>ContactPropertyChangeEvent</tt> containing the source */ @Override public void contactModified(ContactPropertyChangeEvent evt) { if (!evt.getPropertyName().equals(ContactPropertyChangeEvent.PROPERTY_DISPLAY_NAME)) return; Contact contact = evt.getSourceContact(); if (contact == null) return; for (ComparableEvtObj msc : recentMessages) { if (contact.equals(msc.getContact())) { if (recentQuery != null) recentQuery.updateContactDisplayName(msc, contact.getDisplayName()); return; } } }
/** * Removes the instant message listener from this chat transport. * * @param l The message listener to remove. */ public void removeInstantMessageListener(MessageListener l) { // If this chat transport does not support instant messaging we do // nothing here. if (!allowsInstantMessage()) return; OperationSetBasicInstantMessaging imOpSet = contact.getProtocolProvider().getOperationSet(OperationSetBasicInstantMessaging.class); imOpSet.removeMessageListener(l); }
/** * Whether a dialog need to be opened so the user can enter the destination number. * * @return <tt>true</tt> if dialog needs to be open. */ public boolean askForSMSNumber() { // If this chat transport does not support sms messaging we do // nothing here. if (!allowsSmsMessage()) return false; OperationSetSmsMessaging smsOpSet = contact.getProtocolProvider().getOperationSet(OperationSetSmsMessaging.class); return smsOpSet.askForNumber(contact); }
/** * If sending im is supported check it for supporting html messages if a font is set. As it can be * slow make sure its not on our way */ private void checkImCaps() { if (ConfigurationUtils.getChatDefaultFontFamily() != null && ConfigurationUtils.getChatDefaultFontSize() > 0) { OperationSetBasicInstantMessaging imOpSet = contact.getProtocolProvider().getOperationSet(OperationSetBasicInstantMessaging.class); if (imOpSet != null) imOpSet.isContentTypeSupported(OperationSetBasicInstantMessaging.HTML_MIME_TYPE, contact); } }
/** * Removes the given sms message listener from this chat transport. * * @param l The message listener to remove. */ public void removeSmsMessageListener(MessageListener l) { // If this chat transport does not support sms messaging we do // nothing here. if (!allowsSmsMessage()) return; OperationSetSmsMessaging smsOpSet = contact.getProtocolProvider().getOperationSet(OperationSetSmsMessaging.class); smsOpSet.removeMessageListener(l); }
/** * Returns <code>true</code> if this chat transport supports message corrections and false * otherwise. * * @return <code>true</code> if this chat transport supports message corrections and false * otherwise. */ public boolean allowsMessageCorrections() { OperationSetContactCapabilities capOpSet = getProtocolProvider().getOperationSet(OperationSetContactCapabilities.class); if (capOpSet != null) { return capOpSet.getOperationSet(contact, OperationSetMessageCorrection.class) != null; } else { return contact.getProtocolProvider().getOperationSet(OperationSetMessageCorrection.class) != null; } }
/** * When a sent message is delivered shows it in the chat conversation panel. * * @param evt the event containing details on the message delivery */ public void messageDelivered(MessageDeliveredEvent evt) { Contact contact = evt.getDestinationContact(); MetaContact metaContact = GuiActivator.getContactListService().findMetaContactByContact(contact); if (logger.isTraceEnabled()) logger.trace("MESSAGE DELIVERED to contact: " + contact.getAddress()); ChatPanel chatPanel = chatWindowManager.getContactChat(metaContact, false); if (chatPanel != null) { Message msg = evt.getSourceMessage(); ProtocolProviderService protocolProvider = contact.getProtocolProvider(); if (logger.isTraceEnabled()) logger.trace( "MESSAGE DELIVERED: process message to chat for contact: " + contact.getAddress() + " MESSAGE: " + msg.getContent()); chatPanel.addMessage( this.mainFrame.getAccountAddress(protocolProvider), this.mainFrame.getAccountDisplayName(protocolProvider), evt.getTimestamp(), Chat.OUTGOING_MESSAGE, msg.getContent(), msg.getContentType(), msg.getMessageUID(), evt.getCorrectedMessageUID()); if (evt.isSmsMessage() && !ConfigurationUtils.isSmsNotifyTextDisabled()) { chatPanel.addMessage( contact.getDisplayName(), new Date(), Chat.ACTION_MESSAGE, GuiActivator.getResources().getI18NString("service.gui.SMS_SUCCESSFULLY_SENT"), "text"); } } }
/** * Tries to match the event object to already existing ComparableEvtObj in the supplied list. * * @param obj the object that we will try to match. * @param list the list we will search in. * @return the found ComparableEvtObj */ private static ComparableEvtObj findRecentMessage(EventObject obj, List<ComparableEvtObj> list) { Contact contact = null; ChatRoom chatRoom = null; if (obj instanceof MessageDeliveredEvent) { contact = ((MessageDeliveredEvent) obj).getDestinationContact(); } else if (obj instanceof MessageReceivedEvent) { contact = ((MessageReceivedEvent) obj).getSourceContact(); } else if (obj instanceof ChatRoomMessageDeliveredEvent) { chatRoom = ((ChatRoomMessageDeliveredEvent) obj).getSourceChatRoom(); } else if (obj instanceof ChatRoomMessageReceivedEvent) { chatRoom = ((ChatRoomMessageReceivedEvent) obj).getSourceChatRoom(); } for (ComparableEvtObj evt : list) { if ((contact != null && contact.equals(evt.getContact())) || (chatRoom != null && chatRoom.equals(evt.getRoom()))) return evt; } return null; }
/** * Implements ListSelectionListener.valueChanged. Enables or disables call and hangup buttons * depending on the selection in the contactlist. */ public void valueChanged(ListSelectionEvent e) { Object o = mainFrame.getContactListPanel().getContactList().getSelectedValue(); if ((e.getFirstIndex() != -1 || e.getLastIndex() != -1) && (o instanceof MetaContact)) { setCallMetaContact(true); // Switch automatically to the appropriate pps in account selector // box and enable callButton if telephony is supported. Contact contact = ((MetaContact) o).getDefaultContact(OperationSetBasicTelephony.class); if (contact != null) { callButton.setEnabled(true); if (contact.getProtocolProvider().isRegistered()) getAccountSelectorBox().setSelected(contact.getProtocolProvider()); } else { callButton.setEnabled(false); } } else if (phoneNumberCombo.isComboFieldEmpty()) { callButton.setEnabled(false); } }
/** * Extract values from <tt>EventObject</tt>. * * @param source */ public void update(EventObject source) { this.eventObject = source; if (source instanceof MessageDeliveredEvent) { MessageDeliveredEvent e = (MessageDeliveredEvent) source; this.contact = e.getDestinationContact(); this.address = contact.getAddress(); this.ppService = contact.getProtocolProvider(); this.timestamp = e.getTimestamp(); } else if (source instanceof MessageReceivedEvent) { MessageReceivedEvent e = (MessageReceivedEvent) source; this.contact = e.getSourceContact(); this.address = contact.getAddress(); this.ppService = contact.getProtocolProvider(); this.timestamp = e.getTimestamp(); } else if (source instanceof ChatRoomMessageDeliveredEvent) { ChatRoomMessageDeliveredEvent e = (ChatRoomMessageDeliveredEvent) source; this.room = e.getSourceChatRoom(); this.address = room.getIdentifier(); this.ppService = room.getParentProvider(); this.timestamp = e.getTimestamp(); } else if (source instanceof ChatRoomMessageReceivedEvent) { ChatRoomMessageReceivedEvent e = (ChatRoomMessageReceivedEvent) source; this.room = e.getSourceChatRoom(); this.address = room.getIdentifier(); this.ppService = room.getParentProvider(); this.timestamp = e.getTimestamp(); } }
/** * Returns <code>true</code> if this chat transport supports sms messaging, otherwise returns * <code>false</code>. * * @return <code>true</code> if this chat transport supports sms messaging, otherwise returns * <code>false</code>. */ public boolean allowsSmsMessage() { // First try to ask the capabilities operation set if such is // available. OperationSetContactCapabilities capOpSet = getProtocolProvider().getOperationSet(OperationSetContactCapabilities.class); if (capOpSet != null) { if (capOpSet.getOperationSet(contact, OperationSetSmsMessaging.class) != null) { return true; } } else if (contact.getProtocolProvider().getOperationSet(OperationSetSmsMessaging.class) != null) return true; return false; }
/** * Sends the <tt>message</tt> to the destination indicated by the <tt>to</tt> contact. * * @param to the <tt>Contact</tt> to send <tt>message</tt> to * @param message the <tt>Message</tt> to send. * @throws java.lang.IllegalStateException if the underlying stack is not registered and * initialized. * @throws java.lang.IllegalArgumentException if <tt>to</tt> is not an instance of ContactImpl. */ public void sendInstantMessage(Contact to, Message message) throws IllegalStateException, IllegalArgumentException { if (!(to instanceof ContactSipImpl)) throw new IllegalArgumentException("The specified contact is not a Sip contact." + to); assertConnected(); // offline message if (to.getPresenceStatus().equals(sipStatusEnum.getStatus(SipStatusEnum.OFFLINE)) && !offlineMessageSupported) { if (logger.isDebugEnabled()) logger.debug("trying to send a message to an offline contact"); fireMessageDeliveryFailed( message, to, MessageDeliveryFailedEvent.OFFLINE_MESSAGES_NOT_SUPPORTED); return; } // create the message Request mes; try { mes = createMessageRequest(to, message); } catch (OperationFailedException ex) { logger.error("Failed to create the message.", ex); fireMessageDeliveryFailed(message, to, MessageDeliveryFailedEvent.INTERNAL_ERROR); return; } try { sendMessageRequest(mes, to, message); } catch (TransactionUnavailableException ex) { logger.error( "Failed to create messageTransaction.\n" + "This is most probably a network connection error.", ex); fireMessageDeliveryFailed(message, to, MessageDeliveryFailedEvent.NETWORK_FAILURE); return; } catch (SipException ex) { logger.error("Failed to send the message.", ex); fireMessageDeliveryFailed(message, to, MessageDeliveryFailedEvent.INTERNAL_ERROR); return; } }
/** * Sends a file transfer request to the given <tt>toContact</tt> by specifying the local and * remote file path and the <tt>fromContact</tt>, sending the file. * * @param toContact the contact that should receive the file * @param file the file to send * @return the transfer object * @throws IllegalStateException if the protocol provider is not registered or connected * @throws IllegalArgumentException if some of the arguments doesn't fit the protocol requirements */ public FileTransfer sendFile(Contact toContact, File file) throws IllegalStateException, IllegalArgumentException { assertConnected(); if (file.length() > getMaximumFileLength()) throw new IllegalArgumentException("File length exceeds the allowed one for this protocol"); // Get the aim connection AimConnection aimConnection = icqProvider.getAimConnection(); // Create an outgoing file transfer instance OutgoingFileTransfer outgoingFileTransfer = aimConnection .getIcbmService() .getRvConnectionManager() .createOutgoingFileTransfer(new Screenname(toContact.getAddress())); String id = String.valueOf(outgoingFileTransfer.getRvSessionInfo().getRvSession().getRvSessionId()); FileTransferImpl outFileTransfer = new FileTransferImpl(outgoingFileTransfer, id, toContact, file, FileTransfer.OUT); // Adding the file to the outgoing file transfer try { outgoingFileTransfer.setSingleFile(new File(file.getPath())); } catch (IOException e) { if (logger.isDebugEnabled()) logger.debug("Error sending file", e); return null; } // Notify all interested listeners that a file transfer has been // created. FileTransferCreatedEvent event = new FileTransferCreatedEvent(outFileTransfer, new Date()); fireFileTransferCreated(event); // Sending the file outgoingFileTransfer.sendRequest(new InvitationMessage("")); outFileTransfer.fireStatusChangeEvent(FileTransferStatusChangeEvent.PREPARING); return outFileTransfer; }
/** * Sends <tt>message</tt> as a message correction through this transport, specifying the mime type * (html or plain text) and the id of the message to replace. * * @param message The message to send. * @param mimeType The mime type of the message to send: text/html or text/plain. * @param correctedMessageUID The ID of the message being corrected by this message. */ public void correctInstantMessage(String message, String mimeType, String correctedMessageUID) { if (!allowsMessageCorrections()) { return; } OperationSetMessageCorrection mcOpSet = contact.getProtocolProvider().getOperationSet(OperationSetMessageCorrection.class); Message msg; if (mimeType.equals(OperationSetBasicInstantMessaging.HTML_MIME_TYPE) && mcOpSet.isContentTypeSupported(OperationSetBasicInstantMessaging.HTML_MIME_TYPE)) { msg = mcOpSet.createMessage( message, OperationSetBasicInstantMessaging.HTML_MIME_TYPE, "utf-8", ""); } else { msg = mcOpSet.createMessage(message); } mcOpSet.correctMessage(contact, contactResource, msg, correctedMessageUID); }
/** * Sends the given instant message through this chat transport, by specifying the mime type (html * or plain text). * * @param message The message to send. * @param mimeType The mime type of the message to send: text/html or text/plain. * @throws Exception if the send operation is interrupted */ public void sendInstantMessage(String message, String mimeType) throws Exception { // If this chat transport does not support instant messaging we do // nothing here. if (!allowsInstantMessage()) return; OperationSetBasicInstantMessaging imOpSet = contact.getProtocolProvider().getOperationSet(OperationSetBasicInstantMessaging.class); Message msg; if (mimeType.equals(OperationSetBasicInstantMessaging.HTML_MIME_TYPE) && imOpSet.isContentTypeSupported(OperationSetBasicInstantMessaging.HTML_MIME_TYPE)) { msg = imOpSet.createMessage( message, OperationSetBasicInstantMessaging.HTML_MIME_TYPE, "utf-8", ""); } else { msg = imOpSet.createMessage(message); } if (contactResource != null) imOpSet.sendInstantMessage(contact, contactResource, msg); else imOpSet.sendInstantMessage(contact, ContactResource.BASE_RESOURCE, msg); }
/** * Initialize (a new) Whiteboard with contact * * @param contact Contact used to init whiteboard */ public void initWhiteboard(final Contact contact) { opSetWb = (OperationSetWhiteboarding) contact.getProtocolProvider().getOperationSet(OperationSetWhiteboarding.class); if (opSetWb == null) { logger.info("Contact does not support whiteboarding"); return; } WhiteboardFrame wbf = getWhiteboardFrame(contact); if (wbf != null) { wbf.setVisible(true); return; } new Thread() { public void run() { try { WhiteboardSession wbSession = opSetWb.createWhiteboardSession(contact.getDisplayName(), null); WhiteboardFrame wbFrame = new WhiteboardFrame(WhiteboardSessionManager.this, wbSession); wbFrames.add(wbFrame); wbFrame.setContact(contact); wbFrame.setVisible(true); wbSession.join(); wbSession.invite(contact.getAddress()); } catch (OperationFailedException e) { logger.error("Creating a whiteboard session failed.", e); } catch (OperationNotSupportedException e) { logger.error("Do not support create of whiteboard session", e); } } }.start(); }
/** * Creates an instance of <tt>MetaContactChatTransport</tt> by specifying the parent * <tt>chatSession</tt> and the <tt>contact</tt> associated with the transport. * * @param chatSession the parent <tt>ChatSession</tt> * @param contact the <tt>Contact</tt> associated with this transport * @param contactResource the <tt>ContactResource</tt> associated with the contact * @param isDisplayResourceOnly indicates if only the resource name should be displayed */ public MetaContactChatTransport( MetaContactChatSession chatSession, Contact contact, ContactResource contactResource, boolean isDisplayResourceOnly) { this.parentChatSession = chatSession; this.contact = contact; this.contactResource = contactResource; this.isDisplayResourceOnly = isDisplayResourceOnly; presenceOpSet = contact.getProtocolProvider().getOperationSet(OperationSetPresence.class); if (presenceOpSet != null) presenceOpSet.addContactPresenceStatusListener(this); // checking this can be slow so make // sure its out of our way new Thread( new Runnable() { public void run() { checkImCaps(); } }) .start(); }
/** * 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; }
/** * Helper function used to send a message to a contact, with the given extensions attached. * * @param to The contact to send the message to. * @param toResource The resource to send the message to or null if no resource has been specified * @param message The message to send. * @param extensions The XMPP extensions that should be attached to the message before sending. * @return The MessageDeliveryEvent that resulted after attempting to send this message, so the * calling function can modify it if needed. */ private MessageDeliveredEvent sendMessage( Contact to, ContactResource toResource, Message message, PacketExtension[] extensions) { if (!(to instanceof ContactJabberImpl)) throw new IllegalArgumentException("The specified contact is not a Jabber contact." + to); assertConnected(); org.jivesoftware.smack.packet.Message msg = new org.jivesoftware.smack.packet.Message(); String toJID = null; if (toResource != null) { if (toResource.equals(ContactResource.BASE_RESOURCE)) { toJID = to.getAddress(); } else toJID = ((ContactResourceJabberImpl) toResource).getFullJid(); } if (toJID == null) { toJID = to.getAddress(); } msg.setPacketID(message.getMessageUID()); msg.setTo(toJID); for (PacketExtension ext : extensions) { msg.addExtension(ext); } if (logger.isTraceEnabled()) logger.trace("Will send a message to:" + toJID + " chat.jid=" + toJID); MessageDeliveredEvent msgDeliveryPendingEvt = new MessageDeliveredEvent(message, to, toResource); MessageDeliveredEvent[] transformedEvents = messageDeliveryPendingTransform(msgDeliveryPendingEvt); if (transformedEvents == null || transformedEvents.length == 0) return null; for (MessageDeliveredEvent event : transformedEvents) { String content = event.getSourceMessage().getContent(); if (message.getContentType().equals(HTML_MIME_TYPE)) { msg.setBody(Html2Text.extractText(content)); // Check if the other user supports XHTML messages // make sure we use our discovery manager as it caches calls if (jabberProvider.isFeatureListSupported(toJID, HTML_NAMESPACE)) { // Add the XHTML text to the message XHTMLManager.addBody(msg, OPEN_BODY_TAG + content + CLOSE_BODY_TAG); } } else { // this is plain text so keep it as it is. msg.setBody(content); } // msg.addExtension(new Version()); if (event.isMessageEncrypted() && isCarbonEnabled) { msg.addExtension(new CarbonPacketExtension.PrivateExtension()); } MessageEventManager.addNotificationsRequests(msg, true, false, false, true); String threadID = getThreadIDForAddress(toJID); if (threadID == null) threadID = nextThreadID(); msg.setThread(threadID); msg.setType(org.jivesoftware.smack.packet.Message.Type.chat); msg.setFrom(jabberProvider.getConnection().getUser()); jabberProvider.getConnection().sendPacket(msg); putJidForAddress(toJID, threadID); } return new MessageDeliveredEvent(message, to, toResource); }
/** * Construct a <tt>Request</tt> represent a new message. * * @param to the <tt>Contact</tt> to send <tt>message</tt> to * @param message the <tt>Message</tt> to send. * @return a Message Request destined to the contact * @throws OperationFailedException if an error occurred during the creation of the request */ Request createMessageRequest(Contact to, Message message) throws OperationFailedException { Address toAddress = null; try { toAddress = sipProvider.parseAddressString(to.getAddress()); } catch (ParseException exc) { // Shouldn't happen logger.error("An unexpected error occurred while" + "constructing the address", exc); throw new OperationFailedException( "An unexpected error occurred while" + "constructing the address", OperationFailedException.INTERNAL_ERROR, exc); } // Call ID CallIdHeader callIdHeader = this.sipProvider.getDefaultJainSipProvider().getNewCallId(); // CSeq CSeqHeader cSeqHeader = null; try { // protect seqN synchronized (this) { cSeqHeader = this.sipProvider.getHeaderFactory().createCSeqHeader(seqN++, Request.MESSAGE); } } catch (InvalidArgumentException ex) { // Shouldn't happen logger.error("An unexpected error occurred while" + "constructing the CSeqHeadder", ex); throw new OperationFailedException( "An unexpected error occurred while" + "constructing the CSeqHeadder", OperationFailedException.INTERNAL_ERROR, ex); } catch (ParseException exc) { // shouldn't happen logger.error("An unexpected error occurred while" + "constructing the CSeqHeadder", exc); throw new OperationFailedException( "An unexpected error occurred while" + "constructing the CSeqHeadder", OperationFailedException.INTERNAL_ERROR, exc); } // FromHeader and ToHeader String localTag = SipMessageFactory.generateLocalTag(); FromHeader fromHeader = null; ToHeader toHeader = null; try { // FromHeader fromHeader = this.sipProvider .getHeaderFactory() .createFromHeader(sipProvider.getOurSipAddress(toAddress), localTag); // ToHeader toHeader = this.sipProvider.getHeaderFactory().createToHeader(toAddress, null); } catch (ParseException ex) { // these two should never happen. logger.error( "An unexpected error occurred while" + "constructing the FromHeader or ToHeader", ex); throw new OperationFailedException( "An unexpected error occurred while" + "constructing the FromHeader or ToHeader", OperationFailedException.INTERNAL_ERROR, ex); } // ViaHeaders ArrayList<ViaHeader> viaHeaders = this.sipProvider.getLocalViaHeaders(toAddress); // MaxForwards MaxForwardsHeader maxForwards = this.sipProvider.getMaxForwardsHeader(); // Content params ContentTypeHeader contTypeHeader; ContentLengthHeader contLengthHeader; try { contTypeHeader = this.sipProvider .getHeaderFactory() .createContentTypeHeader(getType(message), getSubType(message)); if (!DEFAULT_MIME_ENCODING.equalsIgnoreCase(message.getEncoding())) contTypeHeader.setParameter("charset", message.getEncoding()); contLengthHeader = this.sipProvider.getHeaderFactory().createContentLengthHeader(message.getSize()); } catch (ParseException ex) { // these two should never happen. logger.error("An unexpected error occurred while" + "constructing the content headers", ex); throw new OperationFailedException( "An unexpected error occurred while" + "constructing the content headers", OperationFailedException.INTERNAL_ERROR, ex); } catch (InvalidArgumentException exc) { // these two should never happen. logger.error( "An unexpected error occurred while" + "constructing the content length header", exc); throw new OperationFailedException( "An unexpected error occurred while" + "constructing the content length header", OperationFailedException.INTERNAL_ERROR, exc); } Request req; try { req = this.sipProvider .getMessageFactory() .createRequest( toHeader.getAddress().getURI(), Request.MESSAGE, callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwards, contTypeHeader, message.getRawData()); } catch (ParseException ex) { // shouldn't happen logger.error("Failed to create message Request!", ex); throw new OperationFailedException( "Failed to create message Request!", OperationFailedException.INTERNAL_ERROR, ex); } req.addHeader(contLengthHeader); return req; }