summaryrefslogtreecommitdiffstats
path: root/js/dav/lib/accounts.js
blob: dbeb67459a3a4181e60c49eebbfacd1e25611b8f (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
import co from 'co';
import url from 'url';

import { listCalendars, listCalendarObjects } from './calendars';
import { listAddressBooks, listVCards } from './contacts';
import fuzzyUrlEquals from './fuzzy_url_equals';
import { Account } from './model';
import * as ns from './namespace';
import * as request from './request';

let debug = require('./debug')('dav:accounts');

let defaults = {
  accountType: 'caldav',
  loadCollections: true,
  loadObjects: false
};

/**
 * rfc 6764.
 *
 * @param {dav.Account} account to find root url for.
 */
let serviceDiscovery = co.wrap(function *(account, options) {
  debug('Attempt service discovery.');

  let endpoint = url.parse(account.server);
  endpoint.protocol = endpoint.protocol || 'http';  // TODO(gareth) https?

  let uri = url.format({
    protocol: endpoint.protocol,
    host: endpoint.host,
    pathname: `/.well-known/${options.accountType}`
  });

  let req = request.basic({ method: 'GET' });
  try {
    let xhr = yield options.xhr.send(req, uri, { sandbox: options.sandbox });
    if (xhr.status >= 300 && xhr.status < 400) {
      // http redirect.
      let location = xhr.getResponseHeader('Location');
      if (typeof location === 'string' && location.length) {
        debug(`Discovery redirected to ${location}`);
        return url.format({
          protocol: endpoint.protocol,
          host: endpoint.host,
          pathname: location
        });
      }
    }
  } catch (error) {
    debug('Discovery failed... failover to the provided url');
  }

  return endpoint.href;
});

/**
 * rfc 5397.
 *
 * @param {dav.Account} account to get principal url for.
 */
let principalUrl = co.wrap(function *(account, options) {
  debug(`Fetch principal url from context path ${account.rootUrl}.`);
  let req = request.propfind({
    props: [ { name: 'current-user-principal', namespace: ns.DAV } ],
    depth: 0,
    mergeResponses: true
  });

  let res = yield options.xhr.send(req, account.rootUrl, {
    sandbox: options.sandbox
  });

  let container = res.props;
  debug(`Received principal: ${container.currentUserPrincipal}`);
  return url.resolve(account.rootUrl, container.currentUserPrincipal);
});

/**
 * @param {dav.Account} account to get home url for.
 */
let homeUrl = co.wrap(function *(account, options) {
  debug(`Fetch home url from principal url ${account.principalUrl}.`);
  let prop;
  if (options.accountType === 'caldav') {
    prop = { name: 'calendar-home-set', namespace: ns.CALDAV };
  } else if (options.accountType === 'carddav') {
    prop = { name: 'addressbook-home-set', namespace: ns.CARDDAV };
  }

  var req = request.propfind({ props: [ prop ] });

  let responses = yield options.xhr.send(req, account.principalUrl, {
    sandbox: options.sandbox
  });

  let response = responses.find(response => {
    return fuzzyUrlEquals(account.principalUrl, response.href);
  });

  let container = response.props;
  let href;
  if (options.accountType === 'caldav') {
    debug(`Received home: ${container.calendarHomeSet}`);
    href = container.calendarHomeSet;
  } else if (options.accountType === 'carddav') {
    debug(`Received home: ${container.addressbookHomeSet}`);
    href = container.addressbookHomeSet;
  }

  return url.resolve(account.rootUrl, href);
});

/**
 * Options:
 *
 *   (String) accountType - one of 'caldav' or 'carddav'. Defaults to 'caldav'.
 *   (Array.<Object>) filters - list of caldav filters to send with request.
 *   (Boolean) loadCollections - whether or not to load dav collections.
 *   (Boolean) loadObjects - whether or not to load dav objects.
 *   (dav.Sandbox) sandbox - optional request sandbox.
 *   (String) server - some url for server (needn't be base url).
 *   (String) timezone - VTIMEZONE calendar object.
 *   (dav.Transport) xhr - request sender.
 *
 * @return {Promise} a promise that will resolve with a dav.Account object.
 */
exports.createAccount = co.wrap(function *(options) {
  options = Object.assign({}, defaults, options);
  if (typeof options.loadObjects !== 'boolean') {
    options.loadObjects = options.loadCollections;
  }

  let account = new Account({
    server: options.server,
    credentials: options.xhr.credentials
  });

  account.rootUrl = yield serviceDiscovery(account, options);
  account.principalUrl = yield principalUrl(account, options);
  account.homeUrl = yield homeUrl(account, options);

  if (!options.loadCollections) {
    return account;
  }

  let key, loadCollections, loadObjects;
  if (options.accountType === 'caldav') {
    key = 'calendars';
    loadCollections = listCalendars;
    loadObjects = listCalendarObjects;
  } else if (options.accountType === 'carddav') {
    key = 'addressBooks';
    loadCollections = listAddressBooks;
    loadObjects = listVCards;
  }

  var collections = yield loadCollections(account, options);
  account[key] = collections;
  if (!options.loadObjects) {
    return account;
  }

  yield collections.map(co.wrap(function *(collection) {
    try {
      collection.objects = yield loadObjects(collection, options);
    } catch (error) {
      collection.error = error;
    }
  }));

  account[key] = account[key].filter(function(collection) {
    return !collection.error;
  });

  return account;
});