aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/protocol/facebook/OperationSetServerStoredContactInfoFacebookImpl.java
blob: 9788bc81e97e84b5e6ef91d31934333119d67ddd (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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/*
 * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.impl.protocol.facebook;

import java.awt.image.*;
import java.io.*;
import java.net.*;
import java.util.*;

import javax.imageio.*;

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

/**
 * Operation Set Server Stored Contact Info Facebook Implementation
 * 
 * @author Dai Zhiwei
 */
public class OperationSetServerStoredContactInfoFacebookImpl
    implements OperationSetServerStoredContactInfo
{
    private static final Logger logger =
        Logger.getLogger(OperationSetServerStoredContactInfoFacebookImpl.class);
    
    /**
     * A callback to the Facebook provider that created us.
     */
    private final ProtocolProviderServiceFacebookImpl parentProvider;
    
    /**
     * All the details retreived so far is kept here
     */
    private final Map<String, List> retreivedDetails
        = new Hashtable<String, List>();
    
    /**
     * Details retreived addresses
     */
    private final Set<String> detailsRetreivedAddresses = new HashSet<String>();

    /**
     * Host address for retreiving images
     */
    private static String fileHostUrl = "http://static.ak.fbcdn.net";
    
    protected OperationSetServerStoredContactInfoFacebookImpl(
        ProtocolProviderServiceFacebookImpl provider)
    {
        this.parentProvider = provider;
    }
    /**
     * Returns the user details from the specified class or its descendants
     * the class is one from the
     * net.java.sip.communicator.service.protocol.ServerStoredDetails
     * or implemented one in the operation set for the user info
     *
     * @param contact Contact
     * @param detailClass Class
     * @return Iterator
     */
    public Iterator getDetailsAndDescendants(Contact contact, Class detailClass)
    {
        List details = getContactDetails(contact.getAddress());
        List result = new LinkedList();
        
        if(details == null)
            return result.iterator();

        Iterator iter = details.iterator();
        while (iter.hasNext())
        {
            Object item = iter.next();
            //the class AND its descendants
            if(detailClass.isInstance(item))
                result.add(item);
        }

        return result.iterator();
    }

    /**
     * Returns the user details from the specified class
     * exactly that class not its descendants
     *
     * @param contact Contact
     * @param detailClass Class
     * @return Iterator
     */
    public Iterator getDetails(Contact contact, Class detailClass)
    {
        List details = getContactDetails(contact.getAddress());
        List result = new LinkedList();
        
        if(details == null)
            return result.iterator();
        
        Iterator iter = details.iterator();
        while (iter.hasNext())
        {
            Object item = iter.next();
            //exactly that class not its descendants
            if(detailClass.equals(item.getClass()))
                result.add(item);
        }

        return result.iterator();
    }

    /**
     * Request the full info for the given uin
     * waits and return this details
     *
     * @param contact Contact
     * @return Iterator
     */
    public Iterator getAllDetailsForContact(Contact contact)
    {
        List details = getContactDetails(contact.getAddress());
        
        if(details == null)
            return new LinkedList().iterator();
        else
            return new LinkedList(details).iterator();
    }
    
    /**
     * Request the full info for the given contactAddress
     * waits and return this details
     *
     * @param contactAddress String
     * @return Vector the details
     */
    private List getContactDetails(String contactAddress)
    {
        List result = retreivedDetails.get(contactAddress);

        if(result == null || (!detailsRetreivedAddresses.contains(contactAddress)))
        {
            result = new LinkedList();
            try
            {
                /**
                 * Summary:
                 * First Name;
                 * Middle Name;
                 * Last Name;
                 * Gender;
                 * Birth Date;
                 * Age;
                 * E-mail;
                 * Phone..
                 * 
                 * Extended:
                 * ...
                 */
                FacebookAdapter adapter = parentProvider.getAdapter();
                OperationSetPersistentPresenceFacebookImpl presenceOS = getParentPresenceOperationSet();

                if(adapter == null || presenceOS == null)
                    return null;
                
                String tmpValueStr = "Who Am I";
                ContactFacebookImpl contact = (ContactFacebookImpl)presenceOS.findContactByID(contactAddress);
                
                //avatar, name, first name
                if(contact != null){
                    /**
                     * TODO fixme "Avatar" should be loaded from resources.properties
                     */
                    byte[] imageBytes = contact.getBigImage();
                    if(imageBytes != null && imageBytes.length > 0)
                        result.add(new ServerStoredDetails.ImageDetail(
                            "Avatar", imageBytes));
                    
                    FacebookUser metaInfo = contact.getContactInfo();
                    if(metaInfo == null)
                        return null;
                    
                    tmpValueStr = metaInfo.name;
                    if(tmpValueStr != null)
                        result.add(new ServerStoredDetails.DisplayNameDetail(tmpValueStr));
                    
                    tmpValueStr = metaInfo.firstName;
                    if(tmpValueStr != null)
                        result.add(new ServerStoredDetails.FirstNameDetail(tmpValueStr));
                }
                
                String profilePage = adapter.getProfilePage(contactAddress);
                
                if(profilePage == null)
                    throw new Exception("Failed to load profile page");
                
                logger.trace("====== Profile Page: ======\n" + profilePage);
                
                /**
                 * @fixme should we fill the summary pannel?
                 */
                
                //add this contact into the set,
                //so that we needn't to fetch his/her info again
                detailsRetreivedAddresses.add(contactAddress);
                
                //class="profile_info"><dl class="info">
                //<div class="profile_info_container">
                String tmpPrefix = "<div class=\"profile_info_container\">";
                int beginPos = profilePage.indexOf(tmpPrefix);
                
                if(beginPos >= 0){
                    //do something
                    beginPos += tmpPrefix.length();
                    if(beginPos >= profilePage.length())
                        throw new Exception("Failed to load profile page");
                    
                    String tmpLabelStr;
                    int tmpLeft = profilePage.indexOf("<dt>", beginPos);
                    int tmpRight = 0;
                    while(tmpLeft >= 0 && tmpLeft < profilePage.length()){
                        tmpRight = profilePage.indexOf("</dt>", tmpLeft);
                        if(tmpRight >= 0){
                            tmpLabelStr = profilePage.substring(tmpLeft + 4, tmpRight);
                            tmpLabelStr = getText(tmpLabelStr);
                            if(tmpLabelStr.endsWith(":"))
                                tmpLabelStr = tmpLabelStr.substring(0, tmpLabelStr.length()-1);
                            //label done!
                            
                            tmpLeft = profilePage.indexOf("<dd>", tmpRight);
                            if(tmpLeft >= 0){
                                tmpRight = profilePage.indexOf("</dd>", tmpLeft);
                                if(tmpRight >= 0){
                                    tmpValueStr = profilePage.substring(tmpLeft + 4, tmpRight);
                                    if(tmpValueStr.startsWith("<img src=\"/") && tmpValueStr.endsWith("\" border=0>")){
                                        //<img src="/string_image.php?ct=AAAAAQAQVVaveiWcR6O91PkY7zr1NgAAABesyLV-PSZ6liviNVJWiOP6XeTgkFFyaMM%2C&fp=8.7&state=0&highlight=1386786477" border=0>
                                        tmpValueStr = tmpValueStr.substring(10, tmpValueStr.length() - 11);
                                        //"http://static.ak.fbcdn.net"
                                        byte[] imageBytes = getImage(fileHostUrl + tmpValueStr);
                                        if(imageBytes != null && imageBytes.length > 0)
                                            result.add(new ServerStoredDetails.ImageDetail(
                                                tmpLabelStr, imageBytes));
                                    } else {
                                        tmpValueStr = getText(tmpValueStr);
                                        //value done!
                                        result.add(new ServerStoredDetails.StringDetail(tmpLabelStr, tmpValueStr));
                                    }
                                } else
                                    break;                                
                            } else
                                break;
                        } else
                            break;
                        tmpLeft = profilePage.indexOf("<dt>", tmpRight + 5);
                    }
                }
                /*//Gender
                String tmpPrefix = "<td class=\"data\"><div id=\'Gender-data\'class=\"datawrap\">";
                String tmpPostfix = "</div>";
                int beginPos = profilePage.indexOf(tmpPrefix);
                int endPos;
                if(beginPos >= 0){
                    endPos = profilePage.indexOf(tmpPostfix, beginPos);
                    if(endPos >= 0){
                        tmp = null;
                        tmp = profilePage.substring(beginPos + tmpPrefix.length(), endPos);
                        if(tmp != null)
                            result.add(new ServerStoredDetails.GenderDetail(getText(tmp)));
                    }
                }
                
                //birthday
                tmpPrefix = "<td class=\"data\"><div id=\'Birthday-data\'class=\"datawrap\">";
                tmpPostfix = "</a></div>";
                beginPos = profilePage.indexOf(tmpPrefix);
                if(beginPos >= 0){
                    endPos = profilePage.indexOf(tmpPostfix, beginPos);
                    if(endPos >= 0){
                        tmp = null;
                        tmp = profilePage.substring(beginPos + tmpPrefix.length(), endPos);
                        if(tmp != null)
                            //@fixme birthday label
                            result.add(new ServerStoredDetails.StringDetail("Birthday", getText(tmp)));
                    }
                }
                
                //Hometown
                tmpPrefix = "<td class=\"data\"><div id=\'Hometown-data\'class=\"datawrap\">";
                tmpPostfix = "</a></div>";
                beginPos = profilePage.indexOf(tmpPrefix);
                if(beginPos >= 0){
                    endPos = profilePage.indexOf(tmpPostfix, beginPos);
                    if(endPos >= 0){
                        tmp = null;
                        tmp = profilePage.substring(beginPos + tmpPrefix.length(), endPos);
                        if(tmp != null)
                            result.add(new ServerStoredDetails.StringDetail("Hometown", getText(tmp)));
                    }
                }*/
            }
            catch (Exception exc)
            {
                logger.error("Cannot load details for contact "
                    + contactAddress + " : " + exc.getMessage()
                    , exc);
            }
        }

        retreivedDetails.put(contactAddress, result);
        
        return new LinkedList(result);
    }
    
    /**
     * Returns the persistent presence operation set that this contact belongs
     * to.
     * 
     * @return the <tt>OperationSetPersistentPresenceFacebookImpl</tt> that
     *         this contact belongs to.
     */
    public OperationSetPersistentPresenceFacebookImpl getParentPresenceOperationSet()
    {
        return (OperationSetPersistentPresenceFacebookImpl) parentProvider
            .getOperationSet(OperationSetPersistentPresence.class);
    }
    /**
     * Get text from html formatted string
     * 
     * @param srcStr the html formatted string
     * @return the plain text
     */
    public static String getText(String srcStr){
        String text = "";
        
        int left = 0;
        int cur = srcStr.indexOf("<", left);
        while(cur >= 0){
            text += srcStr.substring(left, cur);
            left = srcStr.indexOf(">", cur);
            if(left < 0)
                break;
            
            left++;
            if(left < srcStr.length()){
                cur = srcStr.indexOf("<", left);
                continue;
            } else
                break;
        }
        if(left >= 0)
            text += srcStr.substring(left);
        
        /**
         * support for some special symbols, e.g.:
         * & = &amp;
         * (space) = &nbsp;
         * > = &gt;
         * < = &lt;
         * " = &quot;
         * ' = &#039;
         * © = &copy;
         * ® = &reg;
         */
        text = text.replaceAll("&amp;", "&");
        text = text.replaceAll("&nbsp;", " ");
        text = text.replaceAll("&gt;", ">");
        text = text.replaceAll("&lt;", "<");
        text = text.replaceAll("&quot;", "\"");
        text = text.replaceAll("&#039;", "'");
        text = text.replaceAll("&copy;", "©");
        text = text.replaceAll("&reg;", "®");
        
        return text;
    }
    public static byte[] getImage(String urlStr){
        ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
        try
        {
            URL url = new URL(urlStr);
            BufferedImage newAvatar = ImageIO.read(url);

            javax.imageio.ImageIO.write(newAvatar, "PNG", byteArrayOS);
        }
        catch (IOException e)
        {
            logger.warn("IOException occured when loading image", e);
            // OK, we use the defaultAvatar temporarily
            return null;
        }
        finally
        {
            try
            {
                byteArrayOS.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return byteArrayOS.toByteArray();
    }
}