aboutsummaryrefslogtreecommitdiffstats
path: root/lib/caldav/xhr.js
blob: 6c8351fbccd4959f86ac35e0e597e26a57782999 (plain) (blame)
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
/**
@namespace
*/
(function(module, ns) {
  var Native;

  if (typeof(window) === 'undefined') {
    Native = require('xmlhttprequest').XMLHttpRequest;
  } else {
    Native = window.XMLHttpRequest;
  }

  /**
   * Creates a XHR wrapper.
   * Depending on the platform this is loaded
   * from the correct wrapper type will be used.
   *
   * Options are derived from properties on the prototype.
   * See each property for its default value.
   *
   * @class
   * @name Caldav.Xhr
   * @param {Object} options options for xhr.
   * @param {String} [options.method="GET"] any HTTP verb like 'GET' or 'POST'.
   * @param {Boolean} [options.async] false will indicate
   *                   a synchronous request.
   * @param {Object} [options.headers] full of http headers.
   * @param {Object} [options.data] post data.
   */
  function Xhr(options) {
    var key;
    if (typeof(options) === 'undefined') {
      options = {};
    }

    for (key in options) {
      if (Object.hasOwnProperty.call(options, key)) {
        this[key] = options[key];
      }
    }
  }

  Xhr.prototype = {
    globalXhrOptions: null,
    xhrClass: Native,
    xhr: null,
    method: 'GET',
    async: true,
    waiting: false,
    user: null,
    password: null,
    url: null,
    streaming: true,

    headers: {},
    data: null,

    _serialize: function _serialize() {
      return this.data;
    },

    /**
     * @param {String} user basic auth user.
     * @param {String} password basic auth pass.
     * @return {String} basic auth token.
     */
    _credentials: function(user, pass) {
      // this code should never run in nodejs.
      return 'Basic ' + window.btoa(
        user + ':' + pass
      );
    },

    /**
     * Aborts the request if it has already been sent.
     * @param {Function=} cb An optional callback function.
     */
    abort: function(cb) {
      if (this.waiting) {
        this.xhr.abort();
        this.waiting = false;
      }

      if (cb !== undefined) {
        cb();
      }
    },

   _buildXHR: function(callback) {
      var header;

      if (typeof(callback) === 'undefined') {
        callback = this.callback;
      }

      this.xhr = new this.xhrClass(
          this.globalXhrOptions ? this.globalXhrOptions : undefined);

      // This hack is in place due to some platform
      // bug in gecko when using mozSystem xhr
      // the credentials only seem to work as expected
      // when constructing them manually.
      if (!this.globalXhrOptions || !this.globalXhrOptions.mozSystem) {
        this.xhr.open(
            this.method, this.url, this.async, this.user, this.password);
      } else {
        this.xhr.open(this.method, this.url, this.async);
        this.xhr.setRequestHeader('Authorization', this._credentials(
          this.user,
          this.password
        ));
      }

      var useMozChunkedText = false;
      if (
        this.streaming &&
        this.globalXhrOptions &&
        this.globalXhrOptions.useMozChunkedText
      ) {
        useMozChunkedText = true;
        this.xhr.responseType = 'moz-chunked-text';
      }

      for (header in this.headers) {
        if (Object.hasOwnProperty.call(this.headers, header)) {
          this.xhr.setRequestHeader(header, this.headers[header]);
        }
      }


      var hasProgressEvents = false;

      // check for progress event support.
      if (this.streaming) {
        if ('onprogress' in this.xhr) {
          hasProgressEvents = true;
          var last = 0;

          if (useMozChunkedText) {
            this.xhr.onprogress = (function onChunkedProgress(event) {
              if (this.ondata) {
                this.ondata(this.xhr.responseText);
              }
            }.bind(this));
          } else {
            this.xhr.onprogress = (function onProgress(event) {
              var chunk = this.xhr.responseText.substr(last, event.loaded);
              last = event.loaded;
              if (this.ondata) {
                this.ondata(chunk);
              }
            }.bind(this));
          }
        }
      }

      this.xhr.onreadystatechange = (function onReadyStateChange() {
        var data;
        if (this.xhr.readyState === 4) {
          data = this.xhr.responseText;

          // emulate progress events for node...
          // this really lame we should probably just
          // use a real http request for node but this
          // will let us do some testing via node for now.
          if (!hasProgressEvents && this.ondata) {
            this.ondata(data);
          }

          this.waiting = false;
          callback(null, this.xhr);
        }
      }.bind(this));

      this.waiting = true;
      return this.xhr;
    },

    /**
     * Sends request to server.
     *
     * @param {Function} callback success/failure handler.
     */
    send: function send(callback) {
      var xhr = this._buildXHR(callback);
      xhr.send(this._serialize());
      return xhr;
    }
  };

  module.exports = Xhr;

}.apply(
  this,
  (this.Caldav) ?
    [Caldav('xhr'), Caldav] :
    [module, require('./caldav')]
));