UNPKG

62.8 kBJavaScriptView Raw
1/*
2Copyright 2015, 2016 OpenMarket Ltd
3Copyright 2017 Vector Creations Ltd
4
5Licensed under the Apache License, Version 2.0 (the "License");
6you may not use this file except in compliance with the License.
7You may obtain a copy of the License at
8
9 http://www.apache.org/licenses/LICENSE-2.0
10
11Unless required by applicable law or agreed to in writing, software
12distributed under the License is distributed on an "AS IS" BASIS,
13WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14See the License for the specific language governing permissions and
15limitations under the License.
16*/
17"use strict";
18
19/**
20 * This is an internal module. MatrixBaseApis is currently only meant to be used
21 * by {@link client~MatrixClient}.
22 *
23 * @module base-apis
24 */
25
26var _typeof2 = require("babel-runtime/helpers/typeof");
27
28var _typeof3 = _interopRequireDefault(_typeof2);
29
30var _keys = require("babel-runtime/core-js/object/keys");
31
32var _keys2 = _interopRequireDefault(_keys);
33
34function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
35
36var httpApi = require("./http-api");
37var utils = require("./utils");
38
39/**
40 * Low-level wrappers for the Matrix APIs
41 *
42 * @constructor
43 *
44 * @param {Object} opts Configuration options
45 *
46 * @param {string} opts.baseUrl Required. The base URL to the client-server
47 * HTTP API.
48 *
49 * @param {string} opts.idBaseUrl Optional. The base identity server URL for
50 * identity server requests.
51 *
52 * @param {Function} opts.request Required. The function to invoke for HTTP
53 * requests. The value of this property is typically <code>require("request")
54 * </code> as it returns a function which meets the required interface. See
55 * {@link requestFunction} for more information.
56 *
57 * @param {string} opts.accessToken The access_token for this user.
58 *
59 * @param {Number=} opts.localTimeoutMs Optional. The default maximum amount of
60 * time to wait before timing out HTTP requests. If not specified, there is no
61 * timeout.
62 *
63 * @param {Object} opts.queryParams Optional. Extra query parameters to append
64 * to all requests with this client. Useful for application services which require
65 * <code>?user_id=</code>.
66 *
67 * @param {boolean} [opts.useAuthorizationHeader = false] Set to true to use
68 * Authorization header instead of query param to send the access token to the server.
69 */
70function MatrixBaseApis(opts) {
71 utils.checkObjectHasKeys(opts, ["baseUrl", "request"]);
72
73 this.baseUrl = opts.baseUrl;
74 this.idBaseUrl = opts.idBaseUrl;
75
76 var httpOpts = {
77 baseUrl: opts.baseUrl,
78 idBaseUrl: opts.idBaseUrl,
79 accessToken: opts.accessToken,
80 request: opts.request,
81 prefix: httpApi.PREFIX_R0,
82 onlyData: true,
83 extraParams: opts.queryParams,
84 localTimeoutMs: opts.localTimeoutMs,
85 useAuthorizationHeader: opts.useAuthorizationHeader
86 };
87 this._http = new httpApi.MatrixHttpApi(this, httpOpts);
88
89 this._txnCtr = 0;
90}
91
92/**
93 * Get the Homeserver URL of this client
94 * @return {string} Homeserver URL of this client
95 */
96MatrixBaseApis.prototype.getHomeserverUrl = function () {
97 return this.baseUrl;
98};
99
100/**
101 * Get the Identity Server URL of this client
102 * @param {boolean} stripProto whether or not to strip the protocol from the URL
103 * @return {string} Identity Server URL of this client
104 */
105MatrixBaseApis.prototype.getIdentityServerUrl = function () {
106 var stripProto = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
107
108 if (stripProto && (this.idBaseUrl.startsWith("http://") || this.idBaseUrl.startsWith("https://"))) {
109 return this.idBaseUrl.split("://")[1];
110 }
111 return this.idBaseUrl;
112};
113
114/**
115 * Get the access token associated with this account.
116 * @return {?String} The access_token or null
117 */
118MatrixBaseApis.prototype.getAccessToken = function () {
119 return this._http.opts.accessToken || null;
120};
121
122/**
123 * @return {boolean} true if there is a valid access_token for this client.
124 */
125MatrixBaseApis.prototype.isLoggedIn = function () {
126 return this._http.opts.accessToken !== undefined;
127};
128
129/**
130 * Make up a new transaction id
131 *
132 * @return {string} a new, unique, transaction id
133 */
134MatrixBaseApis.prototype.makeTxnId = function () {
135 return "m" + new Date().getTime() + "." + this._txnCtr++;
136};
137
138// Registration/Login operations
139// =============================
140
141/**
142 * Check whether a username is available prior to registration. An error response
143 * indicates an invalid/unavailable username.
144 * @param {string} username The username to check the availability of.
145 * @return {module:client.Promise} Resolves: to `true`.
146 */
147MatrixBaseApis.prototype.isUsernameAvailable = function (username) {
148 return this._http.authedRequest(undefined, "GET", '/register/available', { username: username }).then(function (response) {
149 return response.available;
150 });
151};
152
153/**
154 * @param {string} username
155 * @param {string} password
156 * @param {string} sessionId
157 * @param {Object} auth
158 * @param {Object} bindThreepids Set key 'email' to true to bind any email
159 * threepid uses during registration in the ID server. Set 'msisdn' to
160 * true to bind msisdn.
161 * @param {string} guestAccessToken
162 * @param {module:client.callback} callback Optional.
163 * @return {module:client.Promise} Resolves: TODO
164 * @return {module:http-api.MatrixError} Rejects: with an error response.
165 */
166MatrixBaseApis.prototype.register = function (username, password, sessionId, auth, bindThreepids, guestAccessToken, callback) {
167 // backwards compat
168 if (bindThreepids === true) {
169 bindThreepids = { email: true };
170 } else if (bindThreepids === null || bindThreepids === undefined) {
171 bindThreepids = {};
172 }
173
174 if (auth === undefined || auth === null) {
175 auth = {};
176 }
177 if (sessionId) {
178 auth.session = sessionId;
179 }
180
181 var params = {
182 auth: auth
183 };
184 if (username !== undefined && username !== null) {
185 params.username = username;
186 }
187 if (password !== undefined && password !== null) {
188 params.password = password;
189 }
190 if (bindThreepids.email) {
191 params.bind_email = true;
192 }
193 if (bindThreepids.msisdn) {
194 params.bind_msisdn = true;
195 }
196 if (guestAccessToken !== undefined && guestAccessToken !== null) {
197 params.guest_access_token = guestAccessToken;
198 }
199 // Temporary parameter added to make the register endpoint advertise
200 // msisdn flows. This exists because there are clients that break
201 // when given stages they don't recognise. This parameter will cease
202 // to be necessary once these old clients are gone.
203 // Only send it if we send any params at all (the password param is
204 // mandatory, so if we send any params, we'll send the password param)
205 if (password !== undefined && password !== null) {
206 params.x_show_msisdn = true;
207 }
208
209 return this.registerRequest(params, undefined, callback);
210};
211
212/**
213 * Register a guest account.
214 * @param {Object=} opts Registration options
215 * @param {Object} opts.body JSON HTTP body to provide.
216 * @param {module:client.callback} callback Optional.
217 * @return {module:client.Promise} Resolves: TODO
218 * @return {module:http-api.MatrixError} Rejects: with an error response.
219 */
220MatrixBaseApis.prototype.registerGuest = function (opts, callback) {
221 opts = opts || {};
222 opts.body = opts.body || {};
223 return this.registerRequest(opts.body, "guest", callback);
224};
225
226/**
227 * @param {Object} data parameters for registration request
228 * @param {string=} kind type of user to register. may be "guest"
229 * @param {module:client.callback=} callback
230 * @return {module:client.Promise} Resolves: to the /register response
231 * @return {module:http-api.MatrixError} Rejects: with an error response.
232 */
233MatrixBaseApis.prototype.registerRequest = function (data, kind, callback) {
234 var params = {};
235 if (kind) {
236 params.kind = kind;
237 }
238
239 return this._http.request(callback, "POST", "/register", params, data);
240};
241
242/**
243 * @param {module:client.callback} callback Optional.
244 * @return {module:client.Promise} Resolves: TODO
245 * @return {module:http-api.MatrixError} Rejects: with an error response.
246 */
247MatrixBaseApis.prototype.loginFlows = function (callback) {
248 return this._http.request(callback, "GET", "/login");
249};
250
251/**
252 * @param {string} loginType
253 * @param {Object} data
254 * @param {module:client.callback} callback Optional.
255 * @return {module:client.Promise} Resolves: TODO
256 * @return {module:http-api.MatrixError} Rejects: with an error response.
257 */
258MatrixBaseApis.prototype.login = function (loginType, data, callback) {
259 var _this = this;
260
261 var login_data = {
262 type: loginType
263 };
264
265 // merge data into login_data
266 utils.extend(login_data, data);
267
268 return this._http.authedRequest(function (error, response) {
269 if (loginType === "m.login.password" && response && response.access_token && response.user_id) {
270 _this._http.opts.accessToken = response.access_token;
271 _this.credentials = {
272 userId: response.user_id
273 };
274 }
275
276 if (callback) {
277 callback(error, response);
278 }
279 }, "POST", "/login", undefined, login_data);
280};
281
282/**
283 * @param {string} user
284 * @param {string} password
285 * @param {module:client.callback} callback Optional.
286 * @return {module:client.Promise} Resolves: TODO
287 * @return {module:http-api.MatrixError} Rejects: with an error response.
288 */
289MatrixBaseApis.prototype.loginWithPassword = function (user, password, callback) {
290 return this.login("m.login.password", {
291 user: user,
292 password: password
293 }, callback);
294};
295
296/**
297 * @param {string} relayState URL Callback after SAML2 Authentication
298 * @param {module:client.callback} callback Optional.
299 * @return {module:client.Promise} Resolves: TODO
300 * @return {module:http-api.MatrixError} Rejects: with an error response.
301 */
302MatrixBaseApis.prototype.loginWithSAML2 = function (relayState, callback) {
303 return this.login("m.login.saml2", {
304 relay_state: relayState
305 }, callback);
306};
307
308/**
309 * @param {string} redirectUrl The URL to redirect to after the HS
310 * authenticates with CAS.
311 * @return {string} The HS URL to hit to begin the CAS login process.
312 */
313MatrixBaseApis.prototype.getCasLoginUrl = function (redirectUrl) {
314 return this.getSsoLoginUrl(redirectUrl, "cas");
315};
316
317/**
318 * @param {string} redirectUrl The URL to redirect to after the HS
319 * authenticates with the SSO.
320 * @param {string} loginType The type of SSO login we are doing (sso or cas).
321 * Defaults to 'sso'.
322 * @return {string} The HS URL to hit to begin the SSO login process.
323 */
324MatrixBaseApis.prototype.getSsoLoginUrl = function (redirectUrl, loginType) {
325 if (loginType === undefined) {
326 loginType = "sso";
327 }
328 return this._http.getUrl("/login/" + loginType + "/redirect", {
329 "redirectUrl": redirectUrl
330 }, httpApi.PREFIX_R0);
331};
332
333/**
334 * @param {string} token Login token previously received from homeserver
335 * @param {module:client.callback} callback Optional.
336 * @return {module:client.Promise} Resolves: TODO
337 * @return {module:http-api.MatrixError} Rejects: with an error response.
338 */
339MatrixBaseApis.prototype.loginWithToken = function (token, callback) {
340 return this.login("m.login.token", {
341 token: token
342 }, callback);
343};
344
345/**
346 * Logs out the current session.
347 * Obviously, further calls that require authorisation should fail after this
348 * method is called. The state of the MatrixClient object is not affected:
349 * it is up to the caller to either reset or destroy the MatrixClient after
350 * this method succeeds.
351 * @param {module:client.callback} callback Optional.
352 * @return {module:client.Promise} Resolves: On success, the empty object
353 */
354MatrixBaseApis.prototype.logout = function (callback) {
355 return this._http.authedRequest(callback, "POST", '/logout');
356};
357
358/**
359 * Deactivates the logged-in account.
360 * Obviously, further calls that require authorisation should fail after this
361 * method is called. The state of the MatrixClient object is not affected:
362 * it is up to the caller to either reset or destroy the MatrixClient after
363 * this method succeeds.
364 * @param {object} auth Optional. Auth data to supply for User-Interactive auth.
365 * @param {boolean} erase Optional. If set, send as `erase` attribute in the
366 * JSON request body, indicating whether the account should be erased. Defaults
367 * to false.
368 * @return {module:client.Promise} Resolves: On success, the empty object
369 */
370MatrixBaseApis.prototype.deactivateAccount = function (auth, erase) {
371 if (typeof erase === 'function') {
372 throw new Error('deactivateAccount no longer accepts a callback parameter');
373 }
374
375 var body = {};
376 if (auth) {
377 body.auth = auth;
378 }
379 if (erase !== undefined) {
380 body.erase = erase;
381 }
382
383 return this._http.authedRequestWithPrefix(undefined, "POST", '/account/deactivate', undefined, body, httpApi.PREFIX_R0);
384};
385
386/**
387 * Get the fallback URL to use for unknown interactive-auth stages.
388 *
389 * @param {string} loginType the type of stage being attempted
390 * @param {string} authSessionId the auth session ID provided by the homeserver
391 *
392 * @return {string} HS URL to hit to for the fallback interface
393 */
394MatrixBaseApis.prototype.getFallbackAuthUrl = function (loginType, authSessionId) {
395 var path = utils.encodeUri("/auth/$loginType/fallback/web", {
396 $loginType: loginType
397 });
398
399 return this._http.getUrl(path, {
400 session: authSessionId
401 }, httpApi.PREFIX_R0);
402};
403
404// Room operations
405// ===============
406
407/**
408 * Create a new room.
409 * @param {Object} options a list of options to pass to the /createRoom API.
410 * @param {string} options.room_alias_name The alias localpart to assign to
411 * this room.
412 * @param {string} options.visibility Either 'public' or 'private'.
413 * @param {string[]} options.invite A list of user IDs to invite to this room.
414 * @param {string} options.name The name to give this room.
415 * @param {string} options.topic The topic to give this room.
416 * @param {module:client.callback} callback Optional.
417 * @return {module:client.Promise} Resolves: <code>{room_id: {string},
418 * room_alias: {string(opt)}}</code>
419 * @return {module:http-api.MatrixError} Rejects: with an error response.
420 */
421MatrixBaseApis.prototype.createRoom = function (options, callback) {
422 // valid options include: room_alias_name, visibility, invite
423 return this._http.authedRequest(callback, "POST", "/createRoom", undefined, options);
424};
425
426/**
427 * @param {string} roomId
428 * @param {module:client.callback} callback Optional.
429 * @return {module:client.Promise} Resolves: TODO
430 * @return {module:http-api.MatrixError} Rejects: with an error response.
431 */
432MatrixBaseApis.prototype.roomState = function (roomId, callback) {
433 var path = utils.encodeUri("/rooms/$roomId/state", { $roomId: roomId });
434 return this._http.authedRequest(callback, "GET", path);
435};
436
437/**
438 * Get an event in a room by its event id.
439 * @param {string} roomId
440 * @param {string} eventId
441 * @param {module:client.callback} callback Optional.
442 *
443 * @return {Promise} Resolves to an object containing the event.
444 * @return {module:http-api.MatrixError} Rejects: with an error response.
445 */
446MatrixBaseApis.prototype.fetchRoomEvent = function (roomId, eventId, callback) {
447 var path = utils.encodeUri("/rooms/$roomId/event/$eventId", {
448 $roomId: roomId,
449 $eventId: eventId
450 });
451 return this._http.authedRequest(callback, "GET", path);
452};
453
454/**
455 * @param {string} roomId
456 * @param {string} includeMembership the membership type to include in the response
457 * @param {string} excludeMembership the membership type to exclude from the response
458 * @param {string} atEventId the id of the event for which moment in the timeline the members should be returned for
459 * @param {module:client.callback} callback Optional.
460 * @return {module:client.Promise} Resolves: dictionary of userid to profile information
461 * @return {module:http-api.MatrixError} Rejects: with an error response.
462 */
463MatrixBaseApis.prototype.members = function (roomId, includeMembership, excludeMembership, atEventId, callback) {
464 var queryParams = {};
465 if (includeMembership) {
466 queryParams.membership = includeMembership;
467 }
468 if (excludeMembership) {
469 queryParams.not_membership = excludeMembership;
470 }
471 if (atEventId) {
472 queryParams.at = atEventId;
473 }
474
475 var queryString = utils.encodeParams(queryParams);
476
477 var path = utils.encodeUri("/rooms/$roomId/members?" + queryString, { $roomId: roomId });
478 return this._http.authedRequest(callback, "GET", path);
479};
480
481/**
482 * Upgrades a room to a new protocol version
483 * @param {string} roomId
484 * @param {string} newVersion The target version to upgrade to
485 * @return {module:client.Promise} Resolves: Object with key 'replacement_room'
486 * @return {module:http-api.MatrixError} Rejects: with an error response.
487 */
488MatrixBaseApis.prototype.upgradeRoom = function (roomId, newVersion) {
489 var path = utils.encodeUri("/rooms/$roomId/upgrade", { $roomId: roomId });
490 return this._http.authedRequest(undefined, "POST", path, undefined, { new_version: newVersion });
491};
492
493/**
494 * @param {string} groupId
495 * @return {module:client.Promise} Resolves: Group summary object
496 * @return {module:http-api.MatrixError} Rejects: with an error response.
497 */
498MatrixBaseApis.prototype.getGroupSummary = function (groupId) {
499 var path = utils.encodeUri("/groups/$groupId/summary", { $groupId: groupId });
500 return this._http.authedRequest(undefined, "GET", path);
501};
502
503/**
504 * @param {string} groupId
505 * @return {module:client.Promise} Resolves: Group profile object
506 * @return {module:http-api.MatrixError} Rejects: with an error response.
507 */
508MatrixBaseApis.prototype.getGroupProfile = function (groupId) {
509 var path = utils.encodeUri("/groups/$groupId/profile", { $groupId: groupId });
510 return this._http.authedRequest(undefined, "GET", path);
511};
512
513/**
514 * @param {string} groupId
515 * @param {Object} profile The group profile object
516 * @param {string=} profile.name Name of the group
517 * @param {string=} profile.avatar_url MXC avatar URL
518 * @param {string=} profile.short_description A short description of the room
519 * @param {string=} profile.long_description A longer HTML description of the room
520 * @return {module:client.Promise} Resolves: Empty object
521 * @return {module:http-api.MatrixError} Rejects: with an error response.
522 */
523MatrixBaseApis.prototype.setGroupProfile = function (groupId, profile) {
524 var path = utils.encodeUri("/groups/$groupId/profile", { $groupId: groupId });
525 return this._http.authedRequest(undefined, "POST", path, undefined, profile);
526};
527
528/**
529 * @param {string} groupId
530 * @param {object} policy The join policy for the group. Must include at
531 * least a 'type' field which is 'open' if anyone can join the group
532 * the group without prior approval, or 'invite' if an invite is
533 * required to join.
534 * @return {module:client.Promise} Resolves: Empty object
535 * @return {module:http-api.MatrixError} Rejects: with an error response.
536 */
537MatrixBaseApis.prototype.setGroupJoinPolicy = function (groupId, policy) {
538 var path = utils.encodeUri("/groups/$groupId/settings/m.join_policy", { $groupId: groupId });
539 return this._http.authedRequest(undefined, "PUT", path, undefined, {
540 'm.join_policy': policy
541 });
542};
543
544/**
545 * @param {string} groupId
546 * @return {module:client.Promise} Resolves: Group users list object
547 * @return {module:http-api.MatrixError} Rejects: with an error response.
548 */
549MatrixBaseApis.prototype.getGroupUsers = function (groupId) {
550 var path = utils.encodeUri("/groups/$groupId/users", { $groupId: groupId });
551 return this._http.authedRequest(undefined, "GET", path);
552};
553
554/**
555 * @param {string} groupId
556 * @return {module:client.Promise} Resolves: Group users list object
557 * @return {module:http-api.MatrixError} Rejects: with an error response.
558 */
559MatrixBaseApis.prototype.getGroupInvitedUsers = function (groupId) {
560 var path = utils.encodeUri("/groups/$groupId/invited_users", { $groupId: groupId });
561 return this._http.authedRequest(undefined, "GET", path);
562};
563
564/**
565 * @param {string} groupId
566 * @return {module:client.Promise} Resolves: Group rooms list object
567 * @return {module:http-api.MatrixError} Rejects: with an error response.
568 */
569MatrixBaseApis.prototype.getGroupRooms = function (groupId) {
570 var path = utils.encodeUri("/groups/$groupId/rooms", { $groupId: groupId });
571 return this._http.authedRequest(undefined, "GET", path);
572};
573
574/**
575 * @param {string} groupId
576 * @param {string} userId
577 * @return {module:client.Promise} Resolves: Empty object
578 * @return {module:http-api.MatrixError} Rejects: with an error response.
579 */
580MatrixBaseApis.prototype.inviteUserToGroup = function (groupId, userId) {
581 var path = utils.encodeUri("/groups/$groupId/admin/users/invite/$userId", { $groupId: groupId, $userId: userId });
582 return this._http.authedRequest(undefined, "PUT", path, undefined, {});
583};
584
585/**
586 * @param {string} groupId
587 * @param {string} userId
588 * @return {module:client.Promise} Resolves: Empty object
589 * @return {module:http-api.MatrixError} Rejects: with an error response.
590 */
591MatrixBaseApis.prototype.removeUserFromGroup = function (groupId, userId) {
592 var path = utils.encodeUri("/groups/$groupId/admin/users/remove/$userId", { $groupId: groupId, $userId: userId });
593 return this._http.authedRequest(undefined, "PUT", path, undefined, {});
594};
595
596/**
597 * @param {string} groupId
598 * @param {string} userId
599 * @param {string} roleId Optional.
600 * @return {module:client.Promise} Resolves: Empty object
601 * @return {module:http-api.MatrixError} Rejects: with an error response.
602 */
603MatrixBaseApis.prototype.addUserToGroupSummary = function (groupId, userId, roleId) {
604 var path = utils.encodeUri(roleId ? "/groups/$groupId/summary/$roleId/users/$userId" : "/groups/$groupId/summary/users/$userId", { $groupId: groupId, $roleId: roleId, $userId: userId });
605 return this._http.authedRequest(undefined, "PUT", path, undefined, {});
606};
607
608/**
609 * @param {string} groupId
610 * @param {string} userId
611 * @return {module:client.Promise} Resolves: Empty object
612 * @return {module:http-api.MatrixError} Rejects: with an error response.
613 */
614MatrixBaseApis.prototype.removeUserFromGroupSummary = function (groupId, userId) {
615 var path = utils.encodeUri("/groups/$groupId/summary/users/$userId", { $groupId: groupId, $userId: userId });
616 return this._http.authedRequest(undefined, "DELETE", path, undefined, {});
617};
618
619/**
620 * @param {string} groupId
621 * @param {string} roomId
622 * @param {string} categoryId Optional.
623 * @return {module:client.Promise} Resolves: Empty object
624 * @return {module:http-api.MatrixError} Rejects: with an error response.
625 */
626MatrixBaseApis.prototype.addRoomToGroupSummary = function (groupId, roomId, categoryId) {
627 var path = utils.encodeUri(categoryId ? "/groups/$groupId/summary/$categoryId/rooms/$roomId" : "/groups/$groupId/summary/rooms/$roomId", { $groupId: groupId, $categoryId: categoryId, $roomId: roomId });
628 return this._http.authedRequest(undefined, "PUT", path, undefined, {});
629};
630
631/**
632 * @param {string} groupId
633 * @param {string} roomId
634 * @return {module:client.Promise} Resolves: Empty object
635 * @return {module:http-api.MatrixError} Rejects: with an error response.
636 */
637MatrixBaseApis.prototype.removeRoomFromGroupSummary = function (groupId, roomId) {
638 var path = utils.encodeUri("/groups/$groupId/summary/rooms/$roomId", { $groupId: groupId, $roomId: roomId });
639 return this._http.authedRequest(undefined, "DELETE", path, undefined, {});
640};
641
642/**
643 * @param {string} groupId
644 * @param {string} roomId
645 * @param {bool} isPublic Whether the room-group association is visible to non-members
646 * @return {module:client.Promise} Resolves: Empty object
647 * @return {module:http-api.MatrixError} Rejects: with an error response.
648 */
649MatrixBaseApis.prototype.addRoomToGroup = function (groupId, roomId, isPublic) {
650 if (isPublic === undefined) {
651 isPublic = true;
652 }
653 var path = utils.encodeUri("/groups/$groupId/admin/rooms/$roomId", { $groupId: groupId, $roomId: roomId });
654 return this._http.authedRequest(undefined, "PUT", path, undefined, { "m.visibility": { type: isPublic ? "public" : "private" } });
655};
656
657/**
658 * Configure the visibility of a room-group association.
659 * @param {string} groupId
660 * @param {string} roomId
661 * @param {bool} isPublic Whether the room-group association is visible to non-members
662 * @return {module:client.Promise} Resolves: Empty object
663 * @return {module:http-api.MatrixError} Rejects: with an error response.
664 */
665MatrixBaseApis.prototype.updateGroupRoomVisibility = function (groupId, roomId, isPublic) {
666 // NB: The /config API is generic but there's not much point in exposing this yet as synapse
667 // is the only server to implement this. In future we should consider an API that allows
668 // arbitrary configuration, i.e. "config/$configKey".
669
670 var path = utils.encodeUri("/groups/$groupId/admin/rooms/$roomId/config/m.visibility", { $groupId: groupId, $roomId: roomId });
671 return this._http.authedRequest(undefined, "PUT", path, undefined, { type: isPublic ? "public" : "private" });
672};
673
674/**
675 * @param {string} groupId
676 * @param {string} roomId
677 * @return {module:client.Promise} Resolves: Empty object
678 * @return {module:http-api.MatrixError} Rejects: with an error response.
679 */
680MatrixBaseApis.prototype.removeRoomFromGroup = function (groupId, roomId) {
681 var path = utils.encodeUri("/groups/$groupId/admin/rooms/$roomId", { $groupId: groupId, $roomId: roomId });
682 return this._http.authedRequest(undefined, "DELETE", path, undefined, {});
683};
684
685/**
686 * @param {string} groupId
687 * @param {Object} opts Additional options to send alongside the acceptance.
688 * @return {module:client.Promise} Resolves: Empty object
689 * @return {module:http-api.MatrixError} Rejects: with an error response.
690 */
691MatrixBaseApis.prototype.acceptGroupInvite = function (groupId) {
692 var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
693
694 var path = utils.encodeUri("/groups/$groupId/self/accept_invite", { $groupId: groupId });
695 return this._http.authedRequest(undefined, "PUT", path, undefined, opts || {});
696};
697
698/**
699 * @param {string} groupId
700 * @return {module:client.Promise} Resolves: Empty object
701 * @return {module:http-api.MatrixError} Rejects: with an error response.
702 */
703MatrixBaseApis.prototype.joinGroup = function (groupId) {
704 var path = utils.encodeUri("/groups/$groupId/self/join", { $groupId: groupId });
705 return this._http.authedRequest(undefined, "PUT", path, undefined, {});
706};
707
708/**
709 * @param {string} groupId
710 * @return {module:client.Promise} Resolves: Empty object
711 * @return {module:http-api.MatrixError} Rejects: with an error response.
712 */
713MatrixBaseApis.prototype.leaveGroup = function (groupId) {
714 var path = utils.encodeUri("/groups/$groupId/self/leave", { $groupId: groupId });
715 return this._http.authedRequest(undefined, "PUT", path, undefined, {});
716};
717
718/**
719 * @return {module:client.Promise} Resolves: The groups to which the user is joined
720 * @return {module:http-api.MatrixError} Rejects: with an error response.
721 */
722MatrixBaseApis.prototype.getJoinedGroups = function () {
723 var path = utils.encodeUri("/joined_groups");
724 return this._http.authedRequest(undefined, "GET", path);
725};
726
727/**
728 * @param {Object} content Request content
729 * @param {string} content.localpart The local part of the desired group ID
730 * @param {Object} content.profile Group profile object
731 * @return {module:client.Promise} Resolves: Object with key group_id: id of the created group
732 * @return {module:http-api.MatrixError} Rejects: with an error response.
733 */
734MatrixBaseApis.prototype.createGroup = function (content) {
735 var path = utils.encodeUri("/create_group");
736 return this._http.authedRequest(undefined, "POST", path, undefined, content);
737};
738
739/**
740 * @param {string[]} userIds List of user IDs
741 * @return {module:client.Promise} Resolves: Object as exmaple below
742 *
743 * {
744 * "users": {
745 * "@bob:example.com": {
746 * "+example:example.com"
747 * }
748 * }
749 * }
750 * @return {module:http-api.MatrixError} Rejects: with an error response.
751 */
752MatrixBaseApis.prototype.getPublicisedGroups = function (userIds) {
753 var path = utils.encodeUri("/publicised_groups");
754 return this._http.authedRequest(undefined, "POST", path, undefined, { user_ids: userIds });
755};
756
757/**
758 * @param {string} groupId
759 * @param {bool} isPublic Whether the user's membership of this group is made public
760 * @return {module:client.Promise} Resolves: Empty object
761 * @return {module:http-api.MatrixError} Rejects: with an error response.
762 */
763MatrixBaseApis.prototype.setGroupPublicity = function (groupId, isPublic) {
764 var path = utils.encodeUri("/groups/$groupId/self/update_publicity", { $groupId: groupId });
765 return this._http.authedRequest(undefined, "PUT", path, undefined, {
766 publicise: isPublic
767 });
768};
769
770/**
771 * Retrieve a state event.
772 * @param {string} roomId
773 * @param {string} eventType
774 * @param {string} stateKey
775 * @param {module:client.callback} callback Optional.
776 * @return {module:client.Promise} Resolves: TODO
777 * @return {module:http-api.MatrixError} Rejects: with an error response.
778 */
779MatrixBaseApis.prototype.getStateEvent = function (roomId, eventType, stateKey, callback) {
780 var pathParams = {
781 $roomId: roomId,
782 $eventType: eventType,
783 $stateKey: stateKey
784 };
785 var path = utils.encodeUri("/rooms/$roomId/state/$eventType", pathParams);
786 if (stateKey !== undefined) {
787 path = utils.encodeUri(path + "/$stateKey", pathParams);
788 }
789 return this._http.authedRequest(callback, "GET", path);
790};
791
792/**
793 * @param {string} roomId
794 * @param {string} eventType
795 * @param {Object} content
796 * @param {string} stateKey
797 * @param {module:client.callback} callback Optional.
798 * @return {module:client.Promise} Resolves: TODO
799 * @return {module:http-api.MatrixError} Rejects: with an error response.
800 */
801MatrixBaseApis.prototype.sendStateEvent = function (roomId, eventType, content, stateKey, callback) {
802 var pathParams = {
803 $roomId: roomId,
804 $eventType: eventType,
805 $stateKey: stateKey
806 };
807 var path = utils.encodeUri("/rooms/$roomId/state/$eventType", pathParams);
808 if (stateKey !== undefined) {
809 path = utils.encodeUri(path + "/$stateKey", pathParams);
810 }
811 return this._http.authedRequest(callback, "PUT", path, undefined, content);
812};
813
814/**
815 * @param {string} roomId
816 * @param {string} eventId
817 * @param {module:client.callback} callback Optional.
818 * @return {module:client.Promise} Resolves: TODO
819 * @return {module:http-api.MatrixError} Rejects: with an error response.
820 */
821MatrixBaseApis.prototype.redactEvent = function (roomId, eventId, callback) {
822 var path = utils.encodeUri("/rooms/$roomId/redact/$eventId", {
823 $roomId: roomId,
824 $eventId: eventId
825 });
826 return this._http.authedRequest(callback, "POST", path, undefined, {});
827};
828
829/**
830 * @param {string} roomId
831 * @param {Number} limit
832 * @param {module:client.callback} callback Optional.
833 * @return {module:client.Promise} Resolves: TODO
834 * @return {module:http-api.MatrixError} Rejects: with an error response.
835 */
836MatrixBaseApis.prototype.roomInitialSync = function (roomId, limit, callback) {
837 if (utils.isFunction(limit)) {
838 callback = limit;limit = undefined;
839 }
840 var path = utils.encodeUri("/rooms/$roomId/initialSync", { $roomId: roomId });
841 if (!limit) {
842 limit = 30;
843 }
844 return this._http.authedRequest(callback, "GET", path, { limit: limit });
845};
846
847/**
848 * Set a marker to indicate the point in a room before which the user has read every
849 * event. This can be retrieved from room account data (the event type is `m.fully_read`)
850 * and displayed as a horizontal line in the timeline that is visually distinct to the
851 * position of the user's own read receipt.
852 * @param {string} roomId ID of the room that has been read
853 * @param {string} rmEventId ID of the event that has been read
854 * @param {string} rrEventId ID of the event tracked by the read receipt. This is here
855 * for convenience because the RR and the RM are commonly updated at the same time as
856 * each other. Optional.
857 * @return {module:client.Promise} Resolves: the empty object, {}.
858 */
859MatrixBaseApis.prototype.setRoomReadMarkersHttpRequest = function (roomId, rmEventId, rrEventId) {
860 var path = utils.encodeUri("/rooms/$roomId/read_markers", {
861 $roomId: roomId
862 });
863
864 var content = {
865 "m.fully_read": rmEventId,
866 "m.read": rrEventId
867 };
868
869 return this._http.authedRequest(undefined, "POST", path, undefined, content);
870};
871
872/**
873 * @return {module:client.Promise} Resolves: A list of the user's current rooms
874 * @return {module:http-api.MatrixError} Rejects: with an error response.
875 */
876MatrixBaseApis.prototype.getJoinedRooms = function () {
877 var path = utils.encodeUri("/joined_rooms");
878 return this._http.authedRequest(undefined, "GET", path);
879};
880
881/**
882 * Retrieve membership info. for a room.
883 * @param {string} roomId ID of the room to get membership for
884 * @return {module:client.Promise} Resolves: A list of currently joined users
885 * and their profile data.
886 * @return {module:http-api.MatrixError} Rejects: with an error response.
887 */
888MatrixBaseApis.prototype.getJoinedRoomMembers = function (roomId) {
889 var path = utils.encodeUri("/rooms/$roomId/joined_members", {
890 $roomId: roomId
891 });
892 return this._http.authedRequest(undefined, "GET", path);
893};
894
895// Room Directory operations
896// =========================
897
898/**
899 * @param {Object} options Options for this request
900 * @param {string} options.server The remote server to query for the room list.
901 * Optional. If unspecified, get the local home
902 * server's public room list.
903 * @param {number} options.limit Maximum number of entries to return
904 * @param {string} options.since Token to paginate from
905 * @param {object} options.filter Filter parameters
906 * @param {string} options.filter.generic_search_term String to search for
907 * @param {module:client.callback} callback Optional.
908 * @return {module:client.Promise} Resolves: TODO
909 * @return {module:http-api.MatrixError} Rejects: with an error response.
910 */
911MatrixBaseApis.prototype.publicRooms = function (options, callback) {
912 if (typeof options == 'function') {
913 callback = options;
914 options = {};
915 }
916 if (options === undefined) {
917 options = {};
918 }
919
920 var query_params = {};
921 if (options.server) {
922 query_params.server = options.server;
923 delete options.server;
924 }
925
926 if ((0, _keys2.default)(options).length === 0 && (0, _keys2.default)(query_params).length === 0) {
927 return this._http.authedRequest(callback, "GET", "/publicRooms");
928 } else {
929 return this._http.authedRequest(callback, "POST", "/publicRooms", query_params, options);
930 }
931};
932
933/**
934 * Create an alias to room ID mapping.
935 * @param {string} alias The room alias to create.
936 * @param {string} roomId The room ID to link the alias to.
937 * @param {module:client.callback} callback Optional.
938 * @return {module:client.Promise} Resolves: TODO.
939 * @return {module:http-api.MatrixError} Rejects: with an error response.
940 */
941MatrixBaseApis.prototype.createAlias = function (alias, roomId, callback) {
942 var path = utils.encodeUri("/directory/room/$alias", {
943 $alias: alias
944 });
945 var data = {
946 room_id: roomId
947 };
948 return this._http.authedRequest(callback, "PUT", path, undefined, data);
949};
950
951/**
952 * Delete an alias to room ID mapping. This alias must be on your local server
953 * and you must have sufficient access to do this operation.
954 * @param {string} alias The room alias to delete.
955 * @param {module:client.callback} callback Optional.
956 * @return {module:client.Promise} Resolves: TODO.
957 * @return {module:http-api.MatrixError} Rejects: with an error response.
958 */
959MatrixBaseApis.prototype.deleteAlias = function (alias, callback) {
960 var path = utils.encodeUri("/directory/room/$alias", {
961 $alias: alias
962 });
963 return this._http.authedRequest(callback, "DELETE", path, undefined, undefined);
964};
965
966/**
967 * Get room info for the given alias.
968 * @param {string} alias The room alias to resolve.
969 * @param {module:client.callback} callback Optional.
970 * @return {module:client.Promise} Resolves: Object with room_id and servers.
971 * @return {module:http-api.MatrixError} Rejects: with an error response.
972 */
973MatrixBaseApis.prototype.getRoomIdForAlias = function (alias, callback) {
974 // TODO: deprecate this or resolveRoomAlias
975 var path = utils.encodeUri("/directory/room/$alias", {
976 $alias: alias
977 });
978 return this._http.authedRequest(callback, "GET", path);
979};
980
981/**
982 * @param {string} roomAlias
983 * @param {module:client.callback} callback Optional.
984 * @return {module:client.Promise} Resolves: TODO
985 * @return {module:http-api.MatrixError} Rejects: with an error response.
986 */
987MatrixBaseApis.prototype.resolveRoomAlias = function (roomAlias, callback) {
988 // TODO: deprecate this or getRoomIdForAlias
989 var path = utils.encodeUri("/directory/room/$alias", { $alias: roomAlias });
990 return this._http.request(callback, "GET", path);
991};
992
993/**
994 * Get the visibility of a room in the current HS's room directory
995 * @param {string} roomId
996 * @param {module:client.callback} callback Optional.
997 * @return {module:client.Promise} Resolves: TODO
998 * @return {module:http-api.MatrixError} Rejects: with an error response.
999 */
1000MatrixBaseApis.prototype.getRoomDirectoryVisibility = function (roomId, callback) {
1001 var path = utils.encodeUri("/directory/list/room/$roomId", {
1002 $roomId: roomId
1003 });
1004 return this._http.authedRequest(callback, "GET", path);
1005};
1006
1007/**
1008 * Set the visbility of a room in the current HS's room directory
1009 * @param {string} roomId
1010 * @param {string} visibility "public" to make the room visible
1011 * in the public directory, or "private" to make
1012 * it invisible.
1013 * @param {module:client.callback} callback Optional.
1014 * @return {module:client.Promise} Resolves: result object
1015 * @return {module:http-api.MatrixError} Rejects: with an error response.
1016 */
1017MatrixBaseApis.prototype.setRoomDirectoryVisibility = function (roomId, visibility, callback) {
1018 var path = utils.encodeUri("/directory/list/room/$roomId", {
1019 $roomId: roomId
1020 });
1021 return this._http.authedRequest(callback, "PUT", path, undefined, { "visibility": visibility });
1022};
1023
1024/**
1025 * Set the visbility of a room bridged to a 3rd party network in
1026 * the current HS's room directory.
1027 * @param {string} networkId the network ID of the 3rd party
1028 * instance under which this room is published under.
1029 * @param {string} roomId
1030 * @param {string} visibility "public" to make the room visible
1031 * in the public directory, or "private" to make
1032 * it invisible.
1033 * @param {module:client.callback} callback Optional.
1034 * @return {module:client.Promise} Resolves: result object
1035 * @return {module:http-api.MatrixError} Rejects: with an error response.
1036 */
1037MatrixBaseApis.prototype.setRoomDirectoryVisibilityAppService = function (networkId, roomId, visibility, callback) {
1038 var path = utils.encodeUri("/directory/list/appservice/$networkId/$roomId", {
1039 $networkId: networkId,
1040 $roomId: roomId
1041 });
1042 return this._http.authedRequest(callback, "PUT", path, undefined, { "visibility": visibility });
1043};
1044
1045// User Directory Operations
1046// =========================
1047
1048/**
1049 * Query the user directory with a term matching user IDs, display names and domains.
1050 * @param {object} opts options
1051 * @param {string} opts.term the term with which to search.
1052 * @param {number} opts.limit the maximum number of results to return. The server will
1053 * apply a limit if unspecified.
1054 * @return {module:client.Promise} Resolves: an array of results.
1055 */
1056MatrixBaseApis.prototype.searchUserDirectory = function (opts) {
1057 var body = {
1058 search_term: opts.term
1059 };
1060
1061 if (opts.limit !== undefined) {
1062 body.limit = opts.limit;
1063 }
1064
1065 return this._http.authedRequest(undefined, "POST", "/user_directory/search", undefined, body);
1066};
1067
1068// Media operations
1069// ================
1070
1071/**
1072 * Upload a file to the media repository on the home server.
1073 *
1074 * @param {object} file The object to upload. On a browser, something that
1075 * can be sent to XMLHttpRequest.send (typically a File). Under node.js,
1076 * a a Buffer, String or ReadStream.
1077 *
1078 * @param {object} opts options object
1079 *
1080 * @param {string=} opts.name Name to give the file on the server. Defaults
1081 * to <tt>file.name</tt>.
1082 *
1083 * @param {boolean=} opts.includeFilename if false will not send the filename,
1084 * e.g for encrypted file uploads where filename leaks are undesirable.
1085 * Defaults to true.
1086 *
1087 * @param {string=} opts.type Content-type for the upload. Defaults to
1088 * <tt>file.type</tt>, or <tt>applicaton/octet-stream</tt>.
1089 *
1090 * @param {boolean=} opts.rawResponse Return the raw body, rather than
1091 * parsing the JSON. Defaults to false (except on node.js, where it
1092 * defaults to true for backwards compatibility).
1093 *
1094 * @param {boolean=} opts.onlyContentUri Just return the content URI,
1095 * rather than the whole body. Defaults to false (except on browsers,
1096 * where it defaults to true for backwards compatibility). Ignored if
1097 * opts.rawResponse is true.
1098 *
1099 * @param {Function=} opts.callback Deprecated. Optional. The callback to
1100 * invoke on success/failure. See the promise return values for more
1101 * information.
1102 *
1103 * @param {Function=} opts.progressHandler Optional. Called when a chunk of
1104 * data has been uploaded, with an object containing the fields `loaded`
1105 * (number of bytes transferred) and `total` (total size, if known).
1106 *
1107 * @return {module:client.Promise} Resolves to response object, as
1108 * determined by this.opts.onlyData, opts.rawResponse, and
1109 * opts.onlyContentUri. Rejects with an error (usually a MatrixError).
1110 */
1111MatrixBaseApis.prototype.uploadContent = function (file, opts) {
1112 return this._http.uploadContent(file, opts);
1113};
1114
1115/**
1116 * Cancel a file upload in progress
1117 * @param {module:client.Promise} promise The promise returned from uploadContent
1118 * @return {boolean} true if canceled, otherwise false
1119 */
1120MatrixBaseApis.prototype.cancelUpload = function (promise) {
1121 return this._http.cancelUpload(promise);
1122};
1123
1124/**
1125 * Get a list of all file uploads in progress
1126 * @return {array} Array of objects representing current uploads.
1127 * Currently in progress is element 0. Keys:
1128 * - promise: The promise associated with the upload
1129 * - loaded: Number of bytes uploaded
1130 * - total: Total number of bytes to upload
1131 */
1132MatrixBaseApis.prototype.getCurrentUploads = function () {
1133 return this._http.getCurrentUploads();
1134};
1135
1136// Profile operations
1137// ==================
1138
1139/**
1140 * @param {string} userId
1141 * @param {string} info The kind of info to retrieve (e.g. 'displayname',
1142 * 'avatar_url').
1143 * @param {module:client.callback} callback Optional.
1144 * @return {module:client.Promise} Resolves: TODO
1145 * @return {module:http-api.MatrixError} Rejects: with an error response.
1146 */
1147MatrixBaseApis.prototype.getProfileInfo = function (userId, info, callback) {
1148 if (utils.isFunction(info)) {
1149 callback = info;info = undefined;
1150 }
1151
1152 var path = info ? utils.encodeUri("/profile/$userId/$info", { $userId: userId, $info: info }) : utils.encodeUri("/profile/$userId", { $userId: userId });
1153 return this._http.authedRequest(callback, "GET", path);
1154};
1155
1156// Account operations
1157// ==================
1158
1159/**
1160 * @param {module:client.callback} callback Optional.
1161 * @return {module:client.Promise} Resolves: TODO
1162 * @return {module:http-api.MatrixError} Rejects: with an error response.
1163 */
1164MatrixBaseApis.prototype.getThreePids = function (callback) {
1165 var path = "/account/3pid";
1166 return this._http.authedRequest(callback, "GET", path, undefined, undefined);
1167};
1168
1169/**
1170 * @param {Object} creds
1171 * @param {boolean} bind
1172 * @param {module:client.callback} callback Optional.
1173 * @return {module:client.Promise} Resolves: TODO
1174 * @return {module:http-api.MatrixError} Rejects: with an error response.
1175 */
1176MatrixBaseApis.prototype.addThreePid = function (creds, bind, callback) {
1177 var path = "/account/3pid";
1178 var data = {
1179 'threePidCreds': creds,
1180 'bind': bind
1181 };
1182 return this._http.authedRequest(callback, "POST", path, null, data);
1183};
1184
1185/**
1186 * @param {string} medium The threepid medium (eg. 'email')
1187 * @param {string} address The threepid address (eg. 'bob@example.com')
1188 * this must be as returned by getThreePids.
1189 * @return {module:client.Promise} Resolves: The server response on success
1190 * (generally the empty JSON object)
1191 * @return {module:http-api.MatrixError} Rejects: with an error response.
1192 */
1193MatrixBaseApis.prototype.deleteThreePid = function (medium, address) {
1194 var path = "/account/3pid/delete";
1195 var data = {
1196 'medium': medium,
1197 'address': address
1198 };
1199 return this._http.authedRequestWithPrefix(undefined, "POST", path, null, data, httpApi.PREFIX_UNSTABLE);
1200};
1201
1202/**
1203 * Make a request to change your password.
1204 * @param {Object} authDict
1205 * @param {string} newPassword The new desired password.
1206 * @param {module:client.callback} callback Optional.
1207 * @return {module:client.Promise} Resolves: TODO
1208 * @return {module:http-api.MatrixError} Rejects: with an error response.
1209 */
1210MatrixBaseApis.prototype.setPassword = function (authDict, newPassword, callback) {
1211 var path = "/account/password";
1212 var data = {
1213 'auth': authDict,
1214 'new_password': newPassword
1215 };
1216
1217 return this._http.authedRequest(callback, "POST", path, null, data);
1218};
1219
1220// Device operations
1221// =================
1222
1223/**
1224 * Gets all devices recorded for the logged-in user
1225 * @return {module:client.Promise} Resolves: result object
1226 * @return {module:http-api.MatrixError} Rejects: with an error response.
1227 */
1228MatrixBaseApis.prototype.getDevices = function () {
1229 var path = "/devices";
1230 return this._http.authedRequestWithPrefix(undefined, "GET", path, undefined, undefined, httpApi.PREFIX_UNSTABLE);
1231};
1232
1233/**
1234 * Update the given device
1235 *
1236 * @param {string} device_id device to update
1237 * @param {Object} body body of request
1238 * @return {module:client.Promise} Resolves: result object
1239 * @return {module:http-api.MatrixError} Rejects: with an error response.
1240 */
1241MatrixBaseApis.prototype.setDeviceDetails = function (device_id, body) {
1242 var path = utils.encodeUri("/devices/$device_id", {
1243 $device_id: device_id
1244 });
1245
1246 return this._http.authedRequestWithPrefix(undefined, "PUT", path, undefined, body, httpApi.PREFIX_UNSTABLE);
1247};
1248
1249/**
1250 * Delete the given device
1251 *
1252 * @param {string} device_id device to delete
1253 * @param {object} auth Optional. Auth data to supply for User-Interactive auth.
1254 * @return {module:client.Promise} Resolves: result object
1255 * @return {module:http-api.MatrixError} Rejects: with an error response.
1256 */
1257MatrixBaseApis.prototype.deleteDevice = function (device_id, auth) {
1258 var path = utils.encodeUri("/devices/$device_id", {
1259 $device_id: device_id
1260 });
1261
1262 var body = {};
1263
1264 if (auth) {
1265 body.auth = auth;
1266 }
1267
1268 return this._http.authedRequestWithPrefix(undefined, "DELETE", path, undefined, body, httpApi.PREFIX_UNSTABLE);
1269};
1270
1271/**
1272 * Delete multiple device
1273 *
1274 * @param {string[]} devices IDs of the devices to delete
1275 * @param {object} auth Optional. Auth data to supply for User-Interactive auth.
1276 * @return {module:client.Promise} Resolves: result object
1277 * @return {module:http-api.MatrixError} Rejects: with an error response.
1278 */
1279MatrixBaseApis.prototype.deleteMultipleDevices = function (devices, auth) {
1280 var body = { devices: devices };
1281
1282 if (auth) {
1283 body.auth = auth;
1284 }
1285
1286 return this._http.authedRequestWithPrefix(undefined, "POST", "/delete_devices", undefined, body, httpApi.PREFIX_UNSTABLE);
1287};
1288
1289// Push operations
1290// ===============
1291
1292/**
1293 * Gets all pushers registered for the logged-in user
1294 *
1295 * @param {module:client.callback} callback Optional.
1296 * @return {module:client.Promise} Resolves: Array of objects representing pushers
1297 * @return {module:http-api.MatrixError} Rejects: with an error response.
1298 */
1299MatrixBaseApis.prototype.getPushers = function (callback) {
1300 var path = "/pushers";
1301 return this._http.authedRequest(callback, "GET", path, undefined, undefined);
1302};
1303
1304/**
1305 * Adds a new pusher or updates an existing pusher
1306 *
1307 * @param {Object} pusher Object representing a pusher
1308 * @param {module:client.callback} callback Optional.
1309 * @return {module:client.Promise} Resolves: Empty json object on success
1310 * @return {module:http-api.MatrixError} Rejects: with an error response.
1311 */
1312MatrixBaseApis.prototype.setPusher = function (pusher, callback) {
1313 var path = "/pushers/set";
1314 return this._http.authedRequest(callback, "POST", path, null, pusher);
1315};
1316
1317/**
1318 * @param {module:client.callback} callback Optional.
1319 * @return {module:client.Promise} Resolves: TODO
1320 * @return {module:http-api.MatrixError} Rejects: with an error response.
1321 */
1322MatrixBaseApis.prototype.getPushRules = function (callback) {
1323 return this._http.authedRequest(callback, "GET", "/pushrules/");
1324};
1325
1326/**
1327 * @param {string} scope
1328 * @param {string} kind
1329 * @param {string} ruleId
1330 * @param {Object} body
1331 * @param {module:client.callback} callback Optional.
1332 * @return {module:client.Promise} Resolves: TODO
1333 * @return {module:http-api.MatrixError} Rejects: with an error response.
1334 */
1335MatrixBaseApis.prototype.addPushRule = function (scope, kind, ruleId, body, callback) {
1336 // NB. Scope not uri encoded because devices need the '/'
1337 var path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", {
1338 $kind: kind,
1339 $ruleId: ruleId
1340 });
1341 return this._http.authedRequest(callback, "PUT", path, undefined, body);
1342};
1343
1344/**
1345 * @param {string} scope
1346 * @param {string} kind
1347 * @param {string} ruleId
1348 * @param {module:client.callback} callback Optional.
1349 * @return {module:client.Promise} Resolves: TODO
1350 * @return {module:http-api.MatrixError} Rejects: with an error response.
1351 */
1352MatrixBaseApis.prototype.deletePushRule = function (scope, kind, ruleId, callback) {
1353 // NB. Scope not uri encoded because devices need the '/'
1354 var path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", {
1355 $kind: kind,
1356 $ruleId: ruleId
1357 });
1358 return this._http.authedRequest(callback, "DELETE", path);
1359};
1360
1361/**
1362 * Enable or disable a push notification rule.
1363 * @param {string} scope
1364 * @param {string} kind
1365 * @param {string} ruleId
1366 * @param {boolean} enabled
1367 * @param {module:client.callback} callback Optional.
1368 * @return {module:client.Promise} Resolves: result object
1369 * @return {module:http-api.MatrixError} Rejects: with an error response.
1370 */
1371MatrixBaseApis.prototype.setPushRuleEnabled = function (scope, kind, ruleId, enabled, callback) {
1372 var path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/enabled", {
1373 $kind: kind,
1374 $ruleId: ruleId
1375 });
1376 return this._http.authedRequest(callback, "PUT", path, undefined, { "enabled": enabled });
1377};
1378
1379/**
1380 * Set the actions for a push notification rule.
1381 * @param {string} scope
1382 * @param {string} kind
1383 * @param {string} ruleId
1384 * @param {array} actions
1385 * @param {module:client.callback} callback Optional.
1386 * @return {module:client.Promise} Resolves: result object
1387 * @return {module:http-api.MatrixError} Rejects: with an error response.
1388 */
1389MatrixBaseApis.prototype.setPushRuleActions = function (scope, kind, ruleId, actions, callback) {
1390 var path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/actions", {
1391 $kind: kind,
1392 $ruleId: ruleId
1393 });
1394 return this._http.authedRequest(callback, "PUT", path, undefined, { "actions": actions });
1395};
1396
1397// Search
1398// ======
1399
1400/**
1401 * Perform a server-side search.
1402 * @param {Object} opts
1403 * @param {string} opts.next_batch the batch token to pass in the query string
1404 * @param {Object} opts.body the JSON object to pass to the request body.
1405 * @param {module:client.callback} callback Optional.
1406 * @return {module:client.Promise} Resolves: TODO
1407 * @return {module:http-api.MatrixError} Rejects: with an error response.
1408 */
1409MatrixBaseApis.prototype.search = function (opts, callback) {
1410 var queryparams = {};
1411 if (opts.next_batch) {
1412 queryparams.next_batch = opts.next_batch;
1413 }
1414 return this._http.authedRequest(callback, "POST", "/search", queryparams, opts.body);
1415};
1416
1417// Crypto
1418// ======
1419
1420/**
1421 * Upload keys
1422 *
1423 * @param {Object} content body of upload request
1424 *
1425 * @param {Object=} opts
1426 *
1427 * @param {string=} opts.device_id explicit device_id to use for upload
1428 * (default is to use the same as that used during auth).
1429 *
1430 * @param {module:client.callback=} callback
1431 *
1432 * @return {module:client.Promise} Resolves: result object. Rejects: with
1433 * an error response ({@link module:http-api.MatrixError}).
1434 */
1435MatrixBaseApis.prototype.uploadKeysRequest = function (content, opts, callback) {
1436 opts = opts || {};
1437 var deviceId = opts.device_id;
1438 var path = void 0;
1439 if (deviceId) {
1440 path = utils.encodeUri("/keys/upload/$deviceId", {
1441 $deviceId: deviceId
1442 });
1443 } else {
1444 path = "/keys/upload";
1445 }
1446 return this._http.authedRequestWithPrefix(callback, "POST", path, undefined, content, httpApi.PREFIX_UNSTABLE);
1447};
1448
1449/**
1450 * Download device keys
1451 *
1452 * @param {string[]} userIds list of users to get keys for
1453 *
1454 * @param {Object=} opts
1455 *
1456 * @param {string=} opts.token sync token to pass in the query request, to help
1457 * the HS give the most recent results
1458 *
1459 * @return {module:client.Promise} Resolves: result object. Rejects: with
1460 * an error response ({@link module:http-api.MatrixError}).
1461 */
1462MatrixBaseApis.prototype.downloadKeysForUsers = function (userIds, opts) {
1463 if (utils.isFunction(opts)) {
1464 // opts used to be 'callback'.
1465 throw new Error('downloadKeysForUsers no longer accepts a callback parameter');
1466 }
1467 opts = opts || {};
1468
1469 var content = {
1470 device_keys: {}
1471 };
1472 if ('token' in opts) {
1473 content.token = opts.token;
1474 }
1475 userIds.forEach(function (u) {
1476 content.device_keys[u] = {};
1477 });
1478
1479 return this._http.authedRequestWithPrefix(undefined, "POST", "/keys/query", undefined, content, httpApi.PREFIX_UNSTABLE);
1480};
1481
1482/**
1483 * Claim one-time keys
1484 *
1485 * @param {string[]} devices a list of [userId, deviceId] pairs
1486 *
1487 * @param {string} [key_algorithm = signed_curve25519] desired key type
1488 *
1489 * @return {module:client.Promise} Resolves: result object. Rejects: with
1490 * an error response ({@link module:http-api.MatrixError}).
1491 */
1492MatrixBaseApis.prototype.claimOneTimeKeys = function (devices, key_algorithm) {
1493 var queries = {};
1494
1495 if (key_algorithm === undefined) {
1496 key_algorithm = "signed_curve25519";
1497 }
1498
1499 for (var i = 0; i < devices.length; ++i) {
1500 var userId = devices[i][0];
1501 var deviceId = devices[i][1];
1502 var query = queries[userId] || {};
1503 queries[userId] = query;
1504 query[deviceId] = key_algorithm;
1505 }
1506 var content = { one_time_keys: queries };
1507 return this._http.authedRequestWithPrefix(undefined, "POST", "/keys/claim", undefined, content, httpApi.PREFIX_UNSTABLE);
1508};
1509
1510/**
1511 * Ask the server for a list of users who have changed their device lists
1512 * between a pair of sync tokens
1513 *
1514 * @param {string} oldToken
1515 * @param {string} newToken
1516 *
1517 * @return {module:client.Promise} Resolves: result object. Rejects: with
1518 * an error response ({@link module:http-api.MatrixError}).
1519 */
1520MatrixBaseApis.prototype.getKeyChanges = function (oldToken, newToken) {
1521 var qps = {
1522 from: oldToken,
1523 to: newToken
1524 };
1525
1526 return this._http.authedRequestWithPrefix(undefined, "GET", "/keys/changes", qps, undefined, httpApi.PREFIX_UNSTABLE);
1527};
1528
1529// Identity Server Operations
1530// ==========================
1531
1532/**
1533 * Requests an email verification token directly from an Identity Server.
1534 *
1535 * Note that the Home Server offers APIs to proxy this API for specific
1536 * situations, allowing for better feedback to the user.
1537 *
1538 * @param {string} email The email address to request a token for
1539 * @param {string} clientSecret A secret binary string generated by the client.
1540 * It is recommended this be around 16 ASCII characters.
1541 * @param {number} sendAttempt If an identity server sees a duplicate request
1542 * with the same sendAttempt, it will not send another email.
1543 * To request another email to be sent, use a larger value for
1544 * the sendAttempt param as was used in the previous request.
1545 * @param {string} nextLink Optional If specified, the client will be redirected
1546 * to this link after validation.
1547 * @param {module:client.callback} callback Optional.
1548 * @return {module:client.Promise} Resolves: TODO
1549 * @return {module:http-api.MatrixError} Rejects: with an error response.
1550 * @throws Error if No ID server is set
1551 */
1552MatrixBaseApis.prototype.requestEmailToken = function (email, clientSecret, sendAttempt, nextLink, callback) {
1553 var params = {
1554 client_secret: clientSecret,
1555 email: email,
1556 send_attempt: sendAttempt,
1557 next_link: nextLink
1558 };
1559 return this._http.idServerRequest(callback, "POST", "/validate/email/requestToken", params, httpApi.PREFIX_IDENTITY_V1);
1560};
1561
1562/**
1563 * Submits an MSISDN token to the identity server
1564 *
1565 * This is used when submitting the code sent by SMS to a phone number.
1566 * The ID server has an equivalent API for email but the js-sdk does
1567 * not expose this, since email is normally validated by the user clicking
1568 * a link rather than entering a code.
1569 *
1570 * @param {string} sid The sid given in the response to requestToken
1571 * @param {string} clientSecret A secret binary string generated by the client.
1572 * This must be the same value submitted in the requestToken call.
1573 * @param {string} token The token, as enetered by the user.
1574 *
1575 * @return {module:client.Promise} Resolves: Object, currently with no parameters.
1576 * @return {module:http-api.MatrixError} Rejects: with an error response.
1577 * @throws Error if No ID server is set
1578 */
1579MatrixBaseApis.prototype.submitMsisdnToken = function (sid, clientSecret, token) {
1580 var params = {
1581 sid: sid,
1582 client_secret: clientSecret,
1583 token: token
1584 };
1585 return this._http.idServerRequest(undefined, "POST", "/validate/msisdn/submitToken", params, httpApi.PREFIX_IDENTITY_V1);
1586};
1587
1588/**
1589 * Looks up the public Matrix ID mapping for a given 3rd party
1590 * identifier from the Identity Server
1591 * @param {string} medium The medium of the threepid, eg. 'email'
1592 * @param {string} address The textual address of the threepid
1593 * @param {module:client.callback} callback Optional.
1594 * @return {module:client.Promise} Resolves: A threepid mapping
1595 * object or the empty object if no mapping
1596 * exists
1597 * @return {module:http-api.MatrixError} Rejects: with an error response.
1598 */
1599MatrixBaseApis.prototype.lookupThreePid = function (medium, address, callback) {
1600 var params = {
1601 medium: medium,
1602 address: address
1603 };
1604 return this._http.idServerRequest(callback, "GET", "/lookup", params, httpApi.PREFIX_IDENTITY_V1);
1605};
1606
1607// Direct-to-device messaging
1608// ==========================
1609
1610/**
1611 * Send an event to a specific list of devices
1612 *
1613 * @param {string} eventType type of event to send
1614 * @param {Object.<string, Object<string, Object>>} contentMap
1615 * content to send. Map from user_id to device_id to content object.
1616 * @param {string=} txnId transaction id. One will be made up if not
1617 * supplied.
1618 * @return {module:client.Promise} Resolves to the result object
1619 */
1620MatrixBaseApis.prototype.sendToDevice = function (eventType, contentMap, txnId) {
1621 var path = utils.encodeUri("/sendToDevice/$eventType/$txnId", {
1622 $eventType: eventType,
1623 $txnId: txnId ? txnId : this.makeTxnId()
1624 });
1625
1626 var body = {
1627 messages: contentMap
1628 };
1629
1630 return this._http.authedRequestWithPrefix(undefined, "PUT", path, undefined, body, httpApi.PREFIX_UNSTABLE);
1631};
1632
1633// Third party Lookup API
1634// ======================
1635
1636/**
1637 * Get the third party protocols that can be reached using
1638 * this HS
1639 * @return {module:client.Promise} Resolves to the result object
1640 */
1641MatrixBaseApis.prototype.getThirdpartyProtocols = function () {
1642 return this._http.authedRequestWithPrefix(undefined, "GET", "/thirdparty/protocols", undefined, undefined, httpApi.PREFIX_UNSTABLE).then(function (response) {
1643 // sanity check
1644 if (!response || (typeof response === "undefined" ? "undefined" : (0, _typeof3.default)(response)) !== 'object') {
1645 throw new Error("/thirdparty/protocols did not return an object: " + response);
1646 }
1647 return response;
1648 });
1649};
1650
1651/**
1652 * Get information on how a specific place on a third party protocol
1653 * may be reached.
1654 * @param {string} protocol The protocol given in getThirdpartyProtocols()
1655 * @param {object} params Protocol-specific parameters, as given in the
1656 * response to getThirdpartyProtocols()
1657 * @return {module:client.Promise} Resolves to the result object
1658 */
1659MatrixBaseApis.prototype.getThirdpartyLocation = function (protocol, params) {
1660 var path = utils.encodeUri("/thirdparty/location/$protocol", {
1661 $protocol: protocol
1662 });
1663
1664 return this._http.authedRequestWithPrefix(undefined, "GET", path, params, undefined, httpApi.PREFIX_UNSTABLE);
1665};
1666
1667/**
1668 * Get information on how a specific user on a third party protocol
1669 * may be reached.
1670 * @param {string} protocol The protocol given in getThirdpartyProtocols()
1671 * @param {object} params Protocol-specific parameters, as given in the
1672 * response to getThirdpartyProtocols()
1673 * @return {module:client.Promise} Resolves to the result object
1674 */
1675MatrixBaseApis.prototype.getThirdpartyUser = function (protocol, params) {
1676 var path = utils.encodeUri("/thirdparty/user/$protocol", {
1677 $protocol: protocol
1678 });
1679
1680 return this._http.authedRequestWithPrefix(undefined, "GET", path, params, undefined, httpApi.PREFIX_UNSTABLE);
1681};
1682
1683/**
1684 * MatrixBaseApis object
1685 */
1686module.exports = MatrixBaseApis;
1687//# sourceMappingURL=base-apis.js.map
\No newline at end of file