summaryrefslogtreecommitdiff
path: root/plugins/LinkPreview/linkpreview.js
blob: 407934c5ae46b56c8fd69e063c484348ea7a1cbf (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
/**
 * (c) 2010 StatusNet, Inc.
 */

(function() {
    /**
     * Quickie wrapper around ooembed JSON lookup
     */
    var oEmbed = {
        api: 'http://oohembed.com/oohembed',
        width: 100,
        height: 75,
        cache: {},
        callbacks: {},

        /**
         * Do a cached oEmbed lookup for the given URL.
         *
         * @param {String} url
         * @param {function} callback
         */
        lookup: function(url, callback)
        {
            if (typeof oEmbed.cache[url] == "object") {
                // We already have a successful lookup.
                callback(oEmbed.cache[url]);
            } else if (typeof oEmbed.callbacks[url] == "undefined") {
                // No lookup yet... Start it!
                oEmbed.callbacks[url] = [callback];

                oEmbed.rawLookup(url, function(data) {
                    oEmbed.cache[url] = data;
                    var callbacks = oEmbed.callbacks[url];
                    oEmbed.callbacks[url] = undefined;
                    for (var i = 0; i < callbacks.length; i++) {
                        callbacks[i](data);
                    }
                });
            } else {
                // A lookup is in progress.
                oEmbed.callbacks[url].push(callback);
            }
        },

        /**
         * Do an oEmbed lookup for the given URL.
         *
         * @fixme proxy through ourselves if possible?
         * @fixme use the global thumbnail size settings
         *
         * @param {String} url
         * @param {function} callback
         */
        rawLookup: function(url, callback)
        {
            var params = {
                url: url,
                format: 'json',
                maxwidth: oEmbed.width,
                maxheight: oEmbed.height,
                token: $('#token').val()
            };
            $.ajax({
                url: oEmbed.api,
                data: params,
                dataType: 'json',
                success: function(data, xhr) {
                    callback(data);
                },
                error: function(xhr, textStatus, errorThrown) {
                    callback(null);
                }
            });
        }
    };

    var LinkPreview = {
        links: [],
        state: [],
        refresh: [],

        /**
         * Find URL links from the source text that may be interesting.
         *
         * @param {String} text
         * @return {Array} list of URLs
         */
        findLinks: function (text)
        {
            // @fixme match this to core code
            var re = /(?:^| )(https?:\/\/.+?\/.+?)(?= |$)/mg;
            var links = [];
            var matches;
            while ((matches = re.exec(text)) !== null) {
                links.push(matches[1]);
            }
            return links;
        },

        /**
         * Start looking up info for a link preview...
         * May start async data loads.
         *
         * @param {number} col: column number to insert preview into
         */
        prepLinkPreview: function(col)
        {
            var id = 'link-preview-' + col;
            var url = LinkPreview.links[col];
            LinkPreview.refresh[col] = false;
            LinkPreview.markLoading(col);

            oEmbed.lookup(url, function(data) {
                var thumb = null;
                var width = 100;
                if (data && typeof data.thumbnail_url == "string") {
                    thumb = data.thumbnail_url;
                    if (typeof data.thumbnail_width !== "undefined") {
                        if (data.thumbnail_width < width) {
                            width = data.thumbnail_width;
                        }
                    }
                } else if (data && data.type == 'photo' && typeof data.url == "string") {
                    thumb = data.url;
                    if (typeof data.width !== "undefined") {
                        if (data.width < width) {
                            width = data.width;
                        }
                    }
                }

                if (thumb) {
                    var link = $('<span class="inline-attachment"><a><img/></a></span>');
                    link.find('a')
                            .attr('href', url)
                            .attr('target', '_blank')
                            .last()
                        .find('img')
                            .attr('src', thumb)
                            .attr('width', width)
                            .attr('title', data.title || data.url || url);
                    $('#' + id).empty();
                    $('#' + id).append(link);
                } else {
                    // No thumbnail available or error retriving it.
                    LinkPreview.clearLink(col);
                }

                if (LinkPreview.refresh[col]) {
                    // Darn user has typed more characters.
                    // Go fetch another link!
                    LinkPreview.prepLinkPreview(col);
                } else {
                    LinkPreview.markDone(col);
                }
            });
        },

        /**
         * Update the live preview section with links found in the given text.
         * May start async data loads.
         *
         * @param {String} text: free-form input text
         */
        previewLinks: function(text)
        {
            var i;
            var old = LinkPreview.links;
            var links = LinkPreview.findLinks(text);
            LinkPreview.links = links;

            // Check for existing common elements...
            for (i = 0; i < old.length && i < links.length; i++) {
                if (links[i] != old[i]) {
                    if (LinkPreview.state[i] == "loading") {
                        // Slate this column for a refresh when this one's done.
                        LinkPreview.refresh[i] = true;
                    } else {
                        // Change an existing entry!
                        LinkPreview.prepLinkPreview(i);
                    }
                }
            }
            if (links.length > old.length) {
                // Adding new entries, whee!
                for (i = old.length; i < links.length; i++) {
                    LinkPreview.addPreviewArea(i);
                    LinkPreview.prepLinkPreview(i);
                }
            } else if (old.length > links.length) {
                // Remove preview entries for links that have been removed.
                for (i = links.length; i < old.length; i++) {
                    LinkPreview.clearLink(i);
                }
            }
        },

        addPreviewArea: function(col) {
            var id = 'link-preview-' + col;
            $('#link-preview').append('<span id="' + id + '"></span>');
        },

        clearLink: function(col) {
            var id = 'link-preview-' + col;
            $('#' + id).html('');
        },

        markLoading: function(col) {
            LinkPreview.state[col] = "loading";
            var id = 'link-preview-' + col;
            $('#' + id).attr('style', 'opacity: 0.5');
        },

        markDone: function(col) {
            LinkPreview.state[col] = "done";
            var id = 'link-preview-' + col;
            $('#' + id).removeAttr('style');
        },

        /**
         * Clear out any link preview data.
         */
        clear: function() {
            LinkPreview.links = [];
            $('#link-preview').empty();
        }
    };

    SN.Init.LinkPreview = function(params) {
        if (params.api) oEmbed.api = params.api;
        if (params.width) oEmbed.width = params.width;
        if (params.height) oEmbed.height = params.height;

        $('#form_notice')
            .append('<div id="link-preview" class="thumbnails"></div>')
            .bind('reset', function() {
                LinkPreview.clear();
            });

        // Piggyback on the counter update...
        var origCounter = SN.U.Counter;
        SN.U.Counter = function(form) {
            LinkPreview.previewLinks($('#notice_data-text').val());
            return origCounter(form);
        }
    }
})();