3 // feature detection flags
4 var haveXMLHttpRequest, haveLocalStorage;
5 // used to store settings in localStorage
6 var SETTINGS_KEY = 'remotestorage:discover';
7 // cache loaded from localStorage
11 * Class: RemoteStorage.Discover
13 * This class deals with the webfinger lookup
16 * userAddress - user@host
17 * callback - gets called with href of the storage, the type and the authURL
24 RemoteStorage.Discover = function(userAddress, callback) {
25 if (userAddress in cachedInfo) {
26 var info = cachedInfo[userAddress];
27 callback(info.href, info.type, info.authURL);
30 var hostname = userAddress.split('@')[1];
31 var params = '?resource=' + encodeURIComponent('acct:' + userAddress);
33 'https://' + hostname + '/.well-known/webfinger' + params,
34 'https://' + hostname + '/.well-known/host-meta.json' + params,
35 'http://' + hostname + '/.well-known/webfinger' + params,
36 'http://' + hostname + '/.well-known/host-meta.json' + params
40 var xhr = new XMLHttpRequest();
41 var url = urls.shift();
42 if (!url) { return callback(); }
43 RemoteStorage.log('try url', url);
44 xhr.open('GET', url, true);
45 xhr.onabort = xhr.onerror = function() {
46 console.error("webfinger error", arguments, '(', url, ')');
49 xhr.onload = function() {
50 if (xhr.status !== 200) { return tryOne(); }
54 profile = JSON.parse(xhr.responseText);
56 RemoteStorage.log("Failed to parse profile ", xhr.responseText, e);
62 RemoteStorage.log("profile has no links section ", JSON.stringify(profile));
68 profile.links.forEach(function(l) {
69 if (l.rel === 'remotestorage') {
71 } else if (l.rel === 'remoteStorage' && !link) {
75 RemoteStorage.log('got profile', profile, 'and link', link);
77 var authURL = link.properties['auth-endpoint'] ||
78 link.properties['http://tools.ietf.org/html/rfc6749#section-4.2'];
79 cachedInfo[userAddress] = { href: link.href, type: link.type, authURL: authURL };
80 if (haveLocalStorage) {
81 localStorage[SETTINGS_KEY] = JSON.stringify({ cache: cachedInfo });
83 callback(link.href, link.type, authURL);
93 RemoteStorage.Discover._rs_init = function(remoteStorage) {
94 if (haveLocalStorage) {
96 try { settings = JSON.parse(localStorage[SETTINGS_KEY]); } catch(e) {}
98 cachedInfo = settings.cache;
103 RemoteStorage.Discover._rs_supported = function() {
104 haveLocalStorage = !! global.localStorage;
105 haveXMLHttpRequest = !! global.XMLHttpRequest;
106 return haveXMLHttpRequest;
109 RemoteStorage.Discover._rs_cleanup = function() {
110 if (haveLocalStorage) {
111 delete localStorage[SETTINGS_KEY];
115 })(typeof(window) !== 'undefined' ? window : global);