summaryrefslogtreecommitdiffstats
path: root/remoting/webapp/host_list.js
blob: ec9348f0bb5c2029dfa5a925e8fff1d0518c5c67 (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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview
 * Class representing the host-list portion of the home screen UI.
 */

'use strict';

/** @suppress {duplicate} */
var remoting = remoting || {};

/**
 * Create a host list consisting of the specified HTML elements, which should
 * have a common parent that contains only host-list UI as it will be hidden
 * if the host-list is empty.
 *
 * @constructor
 * @param {Element} table The HTML <table> to contain host-list.
 * @param {Element} errorDiv The HTML <div> to display error messages.
 */
remoting.HostList = function(table, errorDiv) {
  /**
   * @type {Element}
   * @private
   */
  this.table_ = table;
  /**
   * @type {Element}
   * @private
   */
  this.errorDiv_ = errorDiv;
  /**
   * @type {Array.<remoting.HostTableEntry>}
   * @private
   */
  this.hostTableEntries_ = [];
  /**
   * @type {Array.<remoting.Host>}
   * @private
   */
  this.hosts_ = [];
  /**
   * @type {string}
   * @private
   */
  this.lastError_ = '';

  // Load the cache of the last host-list, if present.
  var cached = /** @type {string} */
      (window.localStorage.getItem(remoting.HostList.HOSTS_KEY));
  if (cached) {
    try {
      this.hosts_ = /** @type {Array} */ JSON.parse(cached);
    } catch (err) {
      console.error('Invalid host list cache:', /** @type {*} */(err));
    }
  }
};

/**
 * Search the host list for a host with the specified id.
 *
 * @param {string} hostId The unique id of the host.
 * @return {remoting.Host?} The host, if any.
 */
remoting.HostList.prototype.getHostForId = function(hostId) {
  for (var i = 0; i < this.hosts_.length; ++i) {
    if (this.hosts_[i].hostId == hostId) {
      return this.hosts_[i];
    }
  }
  return null;
};

/**
 * Query the Remoting Directory for the user's list of hosts.
 *
 * @param {function(boolean):void} onDone Callback invoked with true on success
 *     or false on failure.
 * @return {void} Nothing.
 */
remoting.HostList.prototype.refresh = function(onDone) {
  /** @type {remoting.HostList} */
  var that = this;
  /** @param {XMLHttpRequest} xhr The response from the server. */
  var parseHostListResponse = function(xhr) {
    that.parseHostListResponse_(xhr, onDone);
  }
  /** @param {string} token The OAuth2 token. */
  var getHosts = function(token) {
    // TODO(simonmorris): Pass the access token in a header, not a URL
    // parameter, when crbug.com/116574 has a better fix.
    var params = { 'access_token': token };
    remoting.xhr.get(
        'https://www.googleapis.com/chromoting/v1/@me/hosts',
        parseHostListResponse, params);
  };
  remoting.oauth2.callWithToken(getHosts);
};

/**
 * Handle the results of the host list request.  A success response will
 * include a JSON-encoded list of host descriptions, which we display if we're
 * able to successfully parse it.
 *
 * @param {XMLHttpRequest} xhr The XHR object for the host list request.
 * @param {function(boolean):void} onDone The callback passed to |refresh|.
 * @return {void} Nothing.
 * @private
 */
remoting.HostList.prototype.parseHostListResponse_ = function(xhr, onDone) {
  this.hosts_ = [];
  this.lastError_ = '';
  try {
    if (xhr.status == 200) {
      var parsed_response =
          /** @type {{data: {items: Array}}} */ JSON.parse(xhr.responseText);
      if (parsed_response.data && parsed_response.data.items) {
        this.hosts_ = parsed_response.data.items;
        /**
         * @param {remoting.Host} a
         * @param {remoting.Host} b
         */
        var cmp = function(a, b) {
          if (a.status < b.status) {
            return 1;
          } else if (b.status < a.status) {
            return -1;
          }
          return 0;
        };
        this.hosts_ = /** @type {Array} */ this.hosts_.sort(cmp);
      }
    } else {
      // Some other error.
      console.error('Bad status on host list query: ', xhr);
      if (xhr.status == 403) {
        // The user's account is not enabled for Me2Me, so fail silently.
      } else if (xhr.status >= 400 && xhr.status < 500) {
        // For other errors, tell the user to re-authorize us.
        this.lastError_ = remoting.Error.GENERIC;
      } else if (xhr.status == 503) {
        this.lastError_ = remoting.Error.SERVICE_UNAVAILABLE;
      } else {
        this.lastError_ = remoting.Error.UNEXPECTED;
      }
    }
  } catch (er) {
    var typed_er = /** @type {Object} */ (er);
    console.error('Error processing response: ', xhr, typed_er);
    this.lastError_ = remoting.Error.UNEXPECTED;
  }
  window.localStorage.setItem(remoting.HostList.HOSTS_KEY,
                              JSON.stringify(this.hosts_));
  onDone(this.lastError_ == '');
};

/**
 * Display the list of hosts or error condition.
 *
 * @return {void} Nothing.
 */
remoting.HostList.prototype.display = function() {
  this.table_.innerHTML = '';
  this.errorDiv_.innerText = '';
  this.hostTableEntries_ = [];

  /**
   * @type {remoting.HostList}
   */
  var that = this;
  /**
   * @param {remoting.HostTableEntry} hostTableEntry The entry being renamed.
   */
  var onRename = function(hostTableEntry) { that.renameHost_(hostTableEntry); }
  /**
   * @param {remoting.HostTableEntry} hostTableEntry The entry beign deleted.
   */
  var onDelete = function(hostTableEntry) { that.deleteHost_(hostTableEntry); }

  this.table_.hidden = (this.hosts_.length == 0);

  for (var i = 0; i < this.hosts_.length; ++i) {
    /** @type {remoting.Host} */
    var host = this.hosts_[i];
    // Validate the entry to make sure it has all the fields we expect.
    // If the host has never sent a heartbeat, then there will be no jabberId.
    if (host.hostName && host.hostId && host.status && host.publicKey) {
      var hostTableEntry = new remoting.HostTableEntry();
      hostTableEntry.create(host, onRename, onDelete);
      this.hostTableEntries_[i] = hostTableEntry;
      this.table_.appendChild(hostTableEntry.tableRow);
    }
  }

  if (this.lastError_ != '') {
    l10n.localizeElementFromTag(this.errorDiv_, this.lastError_);
  }
  this.errorDiv_.hidden = (this.lastError_ == '');
};

/**
 * Remove a host from the list, and deregister it.
 * @param {remoting.HostTableEntry} hostTableEntry The host to be removed.
 * @return {void} Nothing.
 * @private
 */
remoting.HostList.prototype.deleteHost_ = function(hostTableEntry) {
  this.table_.removeChild(hostTableEntry.tableRow);
  var index = this.hostTableEntries_.indexOf(hostTableEntry);
  if (index != -1) {
    this.hostTableEntries_.splice(index, 1);
  }

  /** @param {string} token The OAuth2 token. */
  var deleteHost = function(token) {
    var headers = { 'Authorization': 'OAuth ' + token };
    remoting.xhr.remove(
        'https://www.googleapis.com/chromoting/v1/@me/hosts/' +
        hostTableEntry.host.hostId,
        function() {}, '', headers);
  }
  remoting.oauth2.callWithToken(deleteHost);
};

/**
 * Prepare a host for renaming by replacing its name with an edit box.
 * @param {remoting.HostTableEntry} hostTableEntry The host to be renamed.
 * @return {void} Nothing.
 * @private
 */
remoting.HostList.prototype.renameHost_ = function(hostTableEntry) {
  for (var i = 0; i < this.hosts_.length; ++i) {
    if (this.hosts_[i].hostId == hostTableEntry.host.hostId) {
      this.hosts_[i].hostName = hostTableEntry.host.hostName;
      break;
    }
  }
  window.localStorage.setItem(remoting.HostList.HOSTS_KEY,
                              JSON.stringify(this.hosts_));

  /** @param {string} token */
  var renameHost = function(token) {
    var headers = {
      'Authorization': 'OAuth ' + token,
      'Content-type' : 'application/json; charset=UTF-8'
    };
    var newHostDetails = { data: {
      hostId: hostTableEntry.host.hostId,
      hostName: hostTableEntry.host.hostName,
      publicKey: hostTableEntry.host.publicKey
    } };
    remoting.xhr.put(
        'https://www.googleapis.com/chromoting/v1/@me/hosts/' +
        hostTableEntry.host.hostId,
        function(xhr) {},
        JSON.stringify(newHostDetails),
        headers);
  }
  remoting.oauth2.callWithToken(renameHost);
};

/**
 * Key name under which Me2Me hosts are cached.
 */
remoting.HostList.HOSTS_KEY = 'me2me-cached-hosts';

/** @type {remoting.HostList} */
remoting.hostList = null;