summary refs log tree commit diff
path: root/webclient/components/matrix/matrix-service.js
blob: 664c5967af40ca29941694bd5954f1878fbf8fdd (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
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/*
Copyright 2014 matrix.org

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

/*
This service wraps up Matrix API calls. 

This serves to isolate the caller from changes to the underlying url paths, as
well as attach common params (e.g. access_token) to requests.
*/
angular.module('matrixService', [])
.factory('matrixService', ['$http', '$q', '$rootScope', function($http, $q, $rootScope) {
        
   /* 
    * Permanent storage of user information
    * The config contains:
    *    - homeserver url
    *    - Identity server url
    *    - user_id
    *    - access_token
    *    - version: the version of this cache
    */    
    var config;
    
    // Current version of permanent storage
    var configVersion = 0;
    var prefixPath = "/matrix/client/api/v1";
    var MAPPING_PREFIX = "alias_for_";

    var doRequest = function(method, path, params, data) {
        if (!config) {
            console.warn("No config exists. Cannot perform request to "+path);
            return;
        }
    
        // Inject the access token
        if (!params) {
            params = {};
        }
        
        params.access_token = config.access_token;
        
        if (path.indexOf(prefixPath) !== 0) {
            path = prefixPath + path;
        }
        
        return doBaseRequest(config.homeserver, method, path, params, data, undefined);
    };

    var doBaseRequest = function(baseUrl, method, path, params, data, headers) {
        return $http({
            method: method,
            url: baseUrl + path,
            params: params,
            data: data,
            headers: headers
        });
    };


    return {
        /****** Home server API ******/
        prefix: prefixPath,

        // Register an user
        register: function(user_name, password) {
            // The REST path spec
            var path = "/register";

            return doRequest("POST", path, undefined, {
                 user_id: user_name,
                 password: password
            });
        },

        // Create a room
        create: function(room_id, visibility) {
            // The REST path spec
            var path = "/rooms";

            return doRequest("POST", path, undefined, {
                visibility: visibility,
                room_alias_name: room_id
            });
        },

        // List all rooms joined or been invited to
        rooms: function(from, to, limit) {
            // The REST path spec
            var path = "/im/sync";

            return doRequest("GET", path);
        },

        // Joins a room
        join: function(room_id) {
            // The REST path spec
            var path = "/rooms/$room_id/members/$user_id/state";

            // Like the cmd client, escape room ids
            room_id = encodeURIComponent(room_id);

            // Customize it
            path = path.replace("$room_id", room_id);
            path = path.replace("$user_id", config.user_id);

            return doRequest("PUT", path, undefined, {
                 membership: "join"
            });
        },

        joinAlias: function(room_alias) {
            var path = "/join/$room_alias";
            room_alias = encodeURIComponent(room_alias);

            path = path.replace("$room_alias", room_alias);

            return doRequest("PUT", path, undefined, {});
        },

        // Invite a user to a room
        invite: function(room_id, user_id) {
            // The REST path spec
            var path = "/rooms/$room_id/members/$user_id/state";

            // Like the cmd client, escape room ids
            room_id = encodeURIComponent(room_id);

            // Customize it
            path = path.replace("$room_id", room_id);
            path = path.replace("$user_id", user_id);

            return doRequest("PUT", path, undefined, {
                 membership: "invite"
            });
        },

        // Leaves a room
        leave: function(room_id) {
            // The REST path spec
            var path = "/rooms/$room_id/members/$user_id/state";

            // Like the cmd client, escape room ids
            room_id = encodeURIComponent(room_id);

            // Customize it
            path = path.replace("$room_id", room_id);
            path = path.replace("$user_id", config.user_id);

            return doRequest("DELETE", path, undefined, undefined);
        },

        // Retrieves the room ID corresponding to a room alias
        resolveRoomAlias:function(room_alias) {
            var path = "/matrix/client/api/v1/ds/room/$room_alias";
            room_alias = encodeURIComponent(room_alias);

            path = path.replace("$room_alias", room_alias);

            return doRequest("GET", path, undefined, {});
        },

        sendMessage: function(room_id, msg_id, content) {
            // The REST path spec
            var path = "/rooms/$room_id/messages/$from/$msg_id";

            if (!msg_id) {
                msg_id = "m" + new Date().getTime();
            }

            // Like the cmd client, escape room ids
            room_id = encodeURIComponent(room_id);            

            // Customize it
            path = path.replace("$room_id", room_id);
            path = path.replace("$from", config.user_id);
            path = path.replace("$msg_id", msg_id);

            return doRequest("PUT", path, undefined, content);
        },

        // Send a text message
        sendTextMessage: function(room_id, body, msg_id) {
            var content = {
                 msgtype: "m.text",
                 body: body
            };

            return this.sendMessage(room_id, msg_id, content);
        },

        // Send an image message
        sendImageMessage: function(room_id, image_url, image_alt, msg_id) {
            var content = {
                 msgtype: "m.image",
                 url: image_url,
                 body: image_alt
            };

            return this.sendMessage(room_id, msg_id, content);
        },

        // Send an emote message
        sendEmoteMessage: function(room_id, body, msg_id) {
            var content = {
                 msgtype: "m.emote",
                 body: body
            };

            return this.sendMessage(room_id, msg_id, content);
        },

        // get a snapshot of the members in a room.
        getMemberList: function(room_id) {
            // Like the cmd client, escape room ids
            room_id = encodeURIComponent(room_id);

            var path = "/rooms/$room_id/members/list";
            path = path.replace("$room_id", room_id);
            return doRequest("GET", path);
        },
        
        paginateBackMessages: function(room_id, from_token, limit) {
            var path = "/rooms/$room_id/messages/list";
            path = path.replace("$room_id", room_id);
            var params = {
                from: from_token,
                limit: limit,
                dir: 'b'
            };
            return doRequest("GET", path, params);
        },

        // get a list of public rooms on your home server
        publicRooms: function() {
            var path = "/public/rooms"
            return doRequest("GET", path);
        },
        
        // get a display name for this user ID
        getDisplayName: function(userId) {
            return this.getProfileInfo(userId, "displayname");
        },

        // get the profile picture url for this user ID
        getProfilePictureUrl: function(userId) {
            return this.getProfileInfo(userId, "avatar_url");
        },

        // update your display name
        setDisplayName: function(newName) {
            var content = {
                displayname: newName
            };
            return this.setProfileInfo(content, "displayname");
        },

        // update your profile picture url
        setProfilePictureUrl: function(newUrl) {
            var content = {
                avatar_url: newUrl
            };
            return this.setProfileInfo(content, "avatar_url");
        },

        setProfileInfo: function(data, info_segment) {
            var path = "/profile/$user/" + info_segment;
            path = path.replace("$user", config.user_id);
            return doRequest("PUT", path, undefined, data);
        },

        getProfileInfo: function(userId, info_segment) {
            var path = "/profile/$user_id/" + info_segment;
            path = path.replace("$user_id", userId);
            return doRequest("GET", path);
        },
        
        login: function(userId, password) {
            // TODO We should be checking to make sure the client can support
            // logging in to this HS, else use the fallback.
            var path = "/login";
            var data = {
                "type": "m.login.password",
                "user": userId,
                "password": password  
            };
            return doRequest("POST", path, undefined, data);
        },

        // hit the Identity Server for a 3PID request.
        linkEmail: function(email) {
            var path = "/matrix/identity/api/v1/validate/email/requestToken"
            var data = "clientSecret=abc123&email=" + encodeURIComponent(email);
            var headers = {};
            headers["Content-Type"] = "application/x-www-form-urlencoded";
            return doBaseRequest(config.identityServer, "POST", path, {}, data, headers); 
        },

        authEmail: function(userId, tokenId, code) {
            var path = "/matrix/identity/api/v1/validate/email/submitToken";
            var data = "token="+code+"&mxId="+encodeURIComponent(userId)+"&tokenId="+tokenId;
            var headers = {};
            headers["Content-Type"] = "application/x-www-form-urlencoded";
            return doBaseRequest(config.identityServer, "POST", path, {}, data, headers); 
        },
        
        uploadContent: function(file) {
            var path = "/matrix/content";
            var headers = {
                "Content-Type": undefined // undefined means angular will figure it out
            };
            var params = {
                access_token: config.access_token
            };
            return doBaseRequest(config.homeserver, "POST", path, params, file, headers);
        },
        
        // start listening on /events
        getEventStream: function(from, timeout) {
            var path = "/events";
            var params = {
                from: from,
                timeout: timeout
            };
            return doRequest("GET", path, params);
        },

        // Indicates if user authentications details are stored in cache
        isUserLoggedIn: function() {
            var config = this.config();

            // User is considered logged in if his cache is not empty and contains
            // an access token
            if (config && config.access_token) {
                return true;
            }
            else {
                return false;
            }
        },

        /****** Permanent storage of user information ******/
        
        // Returns the current config
        config: function() {
            if (!config) {
                config = localStorage.getItem("config");
                if (config) {
                    config = JSON.parse(config);

                    // Reset the cache if the version loaded is not the expected one
                    if (configVersion !== config.version) {
                        config = undefined;
                        this.saveConfig();
                    }
                }
            }
            return config;
        },
        
        // Set a new config (Use saveConfig to actually store it permanently)
        setConfig: function(newConfig) {
            config = newConfig;
        },
        
        // Commits config into permanent storage
        saveConfig: function() {
            config.version = configVersion;
            localStorage.setItem("config", JSON.stringify(config));
        },
        
        createRoomIdToAliasMapping: function(roomId, alias) {
            localStorage.setItem(MAPPING_PREFIX+roomId, alias);
        },
        
        getRoomIdToAliasMapping: function(roomId) {
            return localStorage.getItem(MAPPING_PREFIX+roomId);
        }

    };
}]);