aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/pixart/messenger/utils/RichPreview.java
blob: 1f9c58b80bb7bb0b06599d4ad9113f9354d94cad (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
package de.pixart.messenger.utils;

import android.content.Context;
import android.os.AsyncTask;
import android.view.View;

import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.regex.Pattern;

import de.pixart.messenger.Config;

/**
 * Created by ponna on 16-01-2018.
 */

public class RichPreview {

    public static final String RICH_LINK_METADATA = "richlink_meta_data";
    private MetaData metaData;
    private ResponseListener responseListener;
    private String url;
    private String filename;
    private Context context;

    public RichPreview(ResponseListener responseListener) {
        this.responseListener = responseListener;
        metaData = new MetaData();
    }

    public void getPreview(final String url, final String filename, final Context context) {
        this.url = url;
        this.filename = filename;
        this.context = context;
        new getData().execute();
    }

    private class getData extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            FileInputStream fis = null;
            ObjectInputStream is = null;
            final File file = new File(context.getCacheDir(), RICH_LINK_METADATA + "/" + filename);
            try {
                fis = new FileInputStream(file);
                InputStreamReader isr = new InputStreamReader(fis);
                BufferedReader bufferedReader = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line);
                }
                String string = sb.substring(sb.indexOf("{"), sb.lastIndexOf("}") + 1);
                JSONObject json = new JSONObject(string);
                if (json.has("url")) {
                    metaData.setUrl(json.getString("url"));
                }
                if (json.has("imageurl")) {
                    metaData.setImageurl(json.getString("imageurl"));
                }
                if (json.has("title")) {
                    metaData.setTitle(json.getString("title"));
                }
                if (json.has("description")) {
                    metaData.setDescription(json.getString("description"));
                }
                if (json.has("sitename")) {
                    metaData.setSitename(json.getString("sitename"));
                }
                if (json.has("mediatype")) {
                    metaData.setMediatype(json.getString("mediatype"));
                }
                if (json.has("favicon")) {
                    metaData.setFavicon(json.getString("favicon"));
                }
            } catch (Exception e) {
                retrieveMeta(url, context);
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            responseListener.onData(metaData);
        }
    }

    private String resolveURL(String url, String part) {
        if (Patterns.AUTOLINK_WEB_URL.matcher(part).matches() && !part.contains(" ")) {
            return part;
        } else {
            URI base_uri = null;
            try {
                base_uri = new URI(url);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            try {
                base_uri = base_uri != null ? base_uri.resolve(URLEncoder.encode(part, "UTF-8")) : null;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return base_uri != null ? base_uri.toString() : null;
        }
    }

    private void saveMeta(MetaData metaData, Context context) {
        final File file = new File(context.getCacheDir(), RICH_LINK_METADATA + "/" + filename);
        file.getParentFile().mkdirs();
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        boolean keep = true;
        try {
            fos = new FileOutputStream(file);
            oos = new ObjectOutputStream(fos);
            JSONObject json = new JSONObject();
            json.put("url", metaData.getUrl());
            json.put("imageurl", metaData.getImageurl());
            json.put("title", metaData.getTitle());
            json.put("description", metaData.getDescription());
            json.put("sitename", metaData.getSitename());
            json.put("mediatype", metaData.getMediatype());
            json.put("favicon", metaData.getFavicon());
            oos.writeObject(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
            keep = false;
        } finally {
            try {
                if (oos != null) oos.close();
                if (fos != null) fos.close();
                if (!keep) file.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void retrieveMeta(String url, Context context) {
        Document doc = null;
        try {
            doc = Jsoup.connect(url)
                    .timeout(Config.CONNECT_TIMEOUT * 1000)
                    .get();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Elements elements = null;
        if (doc != null) {
            elements = doc.getElementsByTag("meta");

            // getTitle doc.select("meta[property=og:title]")
            String title = doc.select("meta[property=og:title]").attr("content");

            if (title == null || title.isEmpty()) {
                title = doc.title();
            }
            metaData.setTitle(title);

            //getDescription
            String description = doc.select("meta[name=description]").attr("content");
            if (description == null || description.isEmpty()) {
                description = doc.select("meta[name=Description]").attr("content");
            }
            if (description == null || description.isEmpty()) {
                description = doc.select("meta[property=og:description]").attr("content");
            }
            if (description == null || description.isEmpty()) {
                description = "";
            }
            metaData.setDescription(description);


            // getMediaType
            Elements mediaTypes = doc.select("meta[name=medium]");
            String type = "";
            if (mediaTypes.size() > 0) {
                String media = mediaTypes.attr("content");

                type = media.equals("image") ? "photo" : media;
            } else {
                type = doc.select("meta[property=og:type]").attr("content");
            }
            metaData.setMediatype(type);


            //getImages
            Elements imageElements = doc.select("meta[property=og:image]");
            if (imageElements.size() > 0) {
                String image = imageElements.attr("content");
                if (!image.isEmpty()) {
                    metaData.setImageurl(resolveURL(url, image));
                }
            }
            if (metaData.getImageurl() != null && metaData.getImageurl().isEmpty()) {
                String src = doc.select("link[rel=image_src]").attr("href");
                if (!src.isEmpty()) {
                    metaData.setImageurl(resolveURL(url, src));
                } else {
                    src = doc.select("link[rel=apple-touch-icon]").attr("href");
                    if (!src.isEmpty()) {
                        metaData.setImageurl(resolveURL(url, src));
                        metaData.setFavicon(resolveURL(url, src));
                    } else {
                        src = doc.select("link[rel=icon]").attr("href");
                        if (!src.isEmpty()) {
                            metaData.setImageurl(resolveURL(url, src));
                            metaData.setFavicon(resolveURL(url, src));
                        }
                    }
                }
            }

            //Favicon
            String src = doc.select("link[rel=apple-touch-icon]").attr("href");
            if (!src.isEmpty()) {
                metaData.setFavicon(resolveURL(url, src));
            } else {
                src = doc.select("link[rel=icon]").attr("href");
                if (!src.isEmpty()) {
                    metaData.setFavicon(resolveURL(url, src));
                }
            }
        }

        if (elements != null) {
            for (Element element : elements) {
                if (element.hasAttr("property")) {
                    String str_property = element.attr("property").trim();
                    if (str_property.equals("og:url")) {
                        metaData.setUrl(element.attr("content"));
                    }
                    if (str_property.equals("og:site_name")) {
                        metaData.setSitename(element.attr("content"));
                    }
                }
            }
        }

        if (metaData.getUrl().equals("") || metaData.getUrl().isEmpty()) {
            URI uri = null;
            try {
                uri = new URI(url);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            if (url == null) {
                metaData.setUrl(url);
            } else {
                metaData.setUrl(uri != null ? uri.getHost() : null);
            }
        }
        saveMeta(metaData, context);
    }

    public interface ResponseListener {

        void onData(MetaData metaData);

        void onError(Exception e);
    }

    public interface RichLinkListener {

        void onClicked(View view, MetaData meta);
    }

    public interface ViewListener {

        void onSuccess(boolean status);

        void onError(Exception e);
    }

    // Pattern for recognizing a URL, based off RFC 3986
    public static final Pattern urlPattern = Pattern.compile(
            "(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"
                    + "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"
                    + "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~@!:/{};']*)",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
}