aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/protocol/facebook/OperationSetSmsMessagingFacebookImpl.java
blob: a3d535e7527f850320ce2139a285a343ad888fc2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package net.java.sip.communicator.impl.protocol.facebook;

import java.util.*;

import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;

import org.json.*;

public class OperationSetSmsMessagingFacebookImpl
    implements OperationSetSmsMessaging
{

    private static final Logger logger =
        Logger.getLogger(OperationSetBasicInstantMessagingFacebookImpl.class);

    /**
     * Currently registered message listeners.
     */
    private final List<MessageListener> messageListeners
        = new Vector<MessageListener>();

    /**
     * The currently valid persistent presence operation set..
     */
    private OperationSetPersistentPresenceFacebookImpl opSetPersPresence = null;

    /**
     * The protocol provider that created us.
     */
    private ProtocolProviderServiceFacebookImpl parentProvider = null;

    public OperationSetSmsMessagingFacebookImpl(
        ProtocolProviderServiceFacebookImpl provider,
        OperationSetPersistentPresenceFacebookImpl opSetPersPresence)
    {
        this.opSetPersPresence = opSetPersPresence;
        this.parentProvider = provider;
    }
    
    public void addMessageListener(MessageListener listener)
    {
        if (!messageListeners.contains(listener))
            messageListeners.add(listener);
    }

    public Message createMessage(byte[] content, String contentType,
        String contentEncoding)
    {
        return new MessageFacebookImpl(new String(content), contentType,
            contentEncoding, "A message sent over SIP Communicator");
    }

    public Message createMessage(String messageText)
    {
        return new MessageFacebookImpl(messageText, DEFAULT_MIME_TYPE,
            DEFAULT_MIME_ENCODING, "A message sent over SIP Communicator");
    }

    public boolean isContentTypeSupported(String contentType)
    {
        if (contentType.equals(DEFAULT_MIME_TYPE))
            return true;
        else
            return false;
    }

    public void removeMessageListener(MessageListener listener)
    {
        messageListeners.remove(listener);
    }

    /**
     * send as a message
     * 
     */
    public void sendSmsMessage(final Contact to, final Message message)
        throws IllegalStateException,
        IllegalArgumentException
    {
        if (!(to instanceof ContactFacebookImpl))
            throw new IllegalArgumentException(
                "The specified contact is not a Facebook contact." + to);

        Thread sender = new Thread(new Runnable()
        {

            public void run()
            {
                // deliver the facebook chat Message
                MessageDeliveryFailedEvent errorEvent = null;
                try
                {
                    errorEvent =
                        OperationSetSmsMessagingFacebookImpl.this.parentProvider
                            .getAdapter().postMessage(message, to);
                    if (errorEvent == null)
                    {
                        fireMessageDelivered(message, to);
                        return;
                    }
                    // if we got the message: 
                    // Error(1357001): Not Logged In; You must be logged in to do that.
                    // we just unregister.
                    // and the reason we got this message may be "multiple logins"
                    if(errorEvent.getErrorCode() == FacebookErrorCode.kError_Async_NotLoggedIn
                        || errorEvent.getErrorCode() == FacebookErrorCode.kError_Async_LoginChanged)
                    {
                        try 
                        {
                            parentProvider.unregister(RegistrationStateChangeEvent.REASON_MULTIPLE_LOGINS);
                        }
                        catch (OperationFailedException e1)
                        {
                            logger.error(
                                "Unable to unregister the protocol provider: "
                                + this
                                + " due to the following exception: " + e1);
                        }
                        fireMessageDeliveryFailed(message, to, errorEvent);
                        return;
                    }
                }
                catch (JSONException e)
                {
                    logger.warn(e.getMessage());
                }

                // if the above delivery failed, we try again!
                // coding like this is so ugly! God, forgive me!
                try
                {
                    // wait a moment
                    Thread.sleep(1000);
                    errorEvent =
                        OperationSetSmsMessagingFacebookImpl.this.parentProvider
                            .getAdapter().postMessage(message, to);
                    if (errorEvent == null)
                    {
                        fireMessageDelivered(message, to);
                        return;
                    }
                    if(errorEvent.getErrorCode() == FacebookErrorCode.kError_Async_NotLoggedIn
                        || errorEvent.getErrorCode() == FacebookErrorCode.kError_Async_LoginChanged)
                    {
                        try 
                        {
                            parentProvider.unregister(RegistrationStateChangeEvent.REASON_MULTIPLE_LOGINS);
                        }
                        catch (OperationFailedException e1)
                        {
                            logger.error(
                                "Unable to unregister the protocol provider: "
                                + this
                                + " due to the following exception: " + e1);
                        }
                    }
                }
                catch (JSONException e)
                {
                    logger.warn(e.getMessage());
                }
                catch (InterruptedException e)
                {
                    logger.warn(e.getMessage());
                }
                // if we get here, we have failed to deliver this message,
                // twice.
                fireMessageDeliveryFailed(message, to, errorEvent);
                // now do message delivery.----what's this?
                // in case that the "to" we deliver this message to is
                // ourselves?
                // deliverMessageToMyself(message, (ContactFacebookImpl)to);
            }
        });
        sender.start();
    }

    public void sendSmsMessage(String to, Message message)
        throws IllegalStateException,
        IllegalArgumentException
    {
        Map<String, OperationSet> supportedOperationSets =
            parentProvider.getSupportedOperationSets();

        if (supportedOperationSets == null || supportedOperationSets.size() < 1)
            throw new NullPointerException(
                "No OperationSet implementations are supported by "
                    + "this implementation. ");

        // get the operation set presence here.
        OperationSetPersistentPresenceFacebookImpl operationSetPP =
            (OperationSetPersistentPresenceFacebookImpl) supportedOperationSets
                .get(OperationSetPersistentPresence.class.getName());

        Contact toContact = operationSetPP.findContactByID(to);
        sendSmsMessage(toContact, message);
    }
    
    /**
     * Notifies all registered message listeners that a message has been
     * delivered successfully to its addressee..
     * 
     * @param message the <tt>Message</tt> that has been delivered.
     * @param to the <tt>Contact</tt> that <tt>message</tt> was delivered
     *            to.
     */
    private void fireMessageDelivered(Message message, Contact to)
    {
        // we succeeded in sending a message to contact "to",
        // so we know he is online
        // but -- if we support the "invisible" status,
        // this line could be commented
        opSetPersPresence.setPresenceStatusForContact((ContactFacebookImpl) to,
            FacebookStatusEnum.ONLINE);

        MessageDeliveredEvent evt =
            new MessageDeliveredEvent(message, to);

        Iterable<MessageListener> listeners;
        synchronized (messageListeners)
        {
            listeners = new ArrayList<MessageListener>(messageListeners);
        }

        for (MessageListener listener : listeners)
            listener.messageDelivered(evt);
    }

    /**
     * Notifies all registered message listeners that a message has been
     * delivered successfully to its addressee..
     * 
     * @param message the <tt>Message</tt> that has been delivered.
     * @param to the <tt>Contact</tt> that <tt>message</tt> was delivered
     *            to.
     */
    private void fireMessageDeliveryFailed(Message message, Contact to,
        MessageDeliveryFailedEvent event)
    {
        Iterable<MessageListener> listeners;
        synchronized (messageListeners)
        {
            listeners = new ArrayList<MessageListener>(messageListeners);
        }

        for (MessageListener listener : listeners)
            listener.messageDeliveryFailed(event);
    }
}