diff --git a/lib/client.js b/lib/client.js index c984b5295..e924e5d2f 100644 --- a/lib/client.js +++ b/lib/client.js @@ -185,6 +185,7 @@ function MatrixClient(opts) { this._ongoingScrollbacks = {}; this._txnCtr = 0; this.timelineSupport = Boolean(opts.timelineSupport); + this.urlPreviewCache = {}; } utils.inherits(MatrixClient, EventEmitter); @@ -1448,6 +1449,41 @@ MatrixClient.prototype.getCurrentUploads = function() { return this._http.getCurrentUploads(); }; +/** + * Get a preview of the given URL as of (roughly) the given point in time, + * described as an object with OpenGraph keys and associated values. + * Attributes may be synthesized where actual OG metadata is lacking. + * Caches results to prevent hammering the server. + * @param {string} url The URL to get preview data for + * @param {Number} ts The preferred point in time that the preview should + * describe (ms since epoch). The preview returned will either be the most + * recent one preceding this timestamp if available, or failing that the next + * most recent available preview. + * @param {module:client.callback} callback Optional. + * @return {module:client.Promise} Resolves: Object of OG metadata. + * @return {module:http-api.MatrixError} Rejects: with an error response. + * May return synthesized attributes if the URL lacked OG meta. + */ +MatrixClient.prototype.getUrlPreview = function(url, ts, callback) { + var key = ts + "_" + url; + var og = this.urlPreviewCache[key]; + if (og) { + return q(og); + } + + var self = this; + return this._http.authedRequestWithPrefix( + callback, "GET", "/preview_url", { + url: url, + ts: ts, + }, undefined, httpApi.PREFIX_MEDIA_R0 + ).then(function(response) { + // TODO: expire cache occasionally + self.urlPreviewCache[key] = response; + return response; + }); +}; + /** * @param {string} roomId * @param {boolean} isTyping diff --git a/lib/http-api.js b/lib/http-api.js index 9d7edbc70..92fdd085a 100644 --- a/lib/http-api.js +++ b/lib/http-api.js @@ -47,6 +47,11 @@ module.exports.PREFIX_UNSTABLE = "/_matrix/client/unstable"; */ module.exports.PREFIX_IDENTITY_V1 = "/_matrix/identity/api/v1"; +/** + * URI path for the media repo API + */ +module.exports.PREFIX_MEDIA_R0 = "/_matrix/media/r0"; + /** * Construct a MatrixHttpApi. * @constructor