-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMatrixAPI.cs
493 lines (423 loc) · 17.2 KB
/
MatrixAPI.cs
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
using libMatrix.Backends;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace libMatrix
{
public partial class MatrixAPI
{
public const string VERSION = "r0.0.1";
IMatrixAPIBackend _backend = null;
private Events _events = null;
private MatrixAppInfo _appInfo = null;
public string UserID { get; private set; }
public string DeviceID { get; private set; }
public string DeviceName { get; private set; } = "libMatrix";
//public string HomeServer { get; private set; }
public string SyncToken { get; private set; } = "";
public int SyncTimeout = 10000;
public bool RunningInitialSync { get; private set; }
public bool IsConnected { get; private set; }
public Events Events { get => _events; set => _events = value; }
public MatrixAppInfo AppInfo { get => _appInfo; }
public MatrixAPI(string Url, string accessToken = "", string syncToken = "")
{
if (!Uri.IsWellFormedUriString(Url, UriKind.Absolute))
throw new MatrixException("URL is not valid.");
_backend = new HttpBackend(Url);
_events = new Events();
_appInfo = new MatrixAppInfo();
if (!string.IsNullOrEmpty(accessToken))
_backend.SetAccessToken(accessToken);
SyncToken = syncToken;
if (string.IsNullOrEmpty(SyncToken))
RunningInitialSync = true;
}
private void FlushMessageQueue()
{
//throw new NotImplementedException();
}
public void SetUserID(string _userId)
{
UserID = _userId;
}
public void SetDeviceID(string _deviceId)
{
DeviceID = _deviceId;
}
public void SetDeviceName(string _deviceName)
{
DeviceName = _deviceName;
}
public async Task ClientSync(bool connectionFailureTimeout = false, bool fullState = false)
{
string url = "/_matrix/client/r0/sync?timeout=" + SyncTimeout;
if (!string.IsNullOrEmpty(SyncToken))
url += "&since=" + SyncToken;
if (fullState)
url += "&full_state=true";
var tuple = await _backend.Get(url, true);
MatrixRequestError err = tuple.Item1;
string response = tuple.Item2;
if (err.IsOk)
{
await ParseClientSync(response);
}
else if (connectionFailureTimeout)
{
}
if (RunningInitialSync)
{
// Fire an event to say sync has been done
RunningInitialSync = false;
}
}
[MatrixSpec("r0.0.1/client_server.html#get-matrix-client-versions")]
public async Task<string[]> ClientVersions()
{
var tuple = await _backend.Get("/_matrix/client/versions", false);
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
// Parse the version request
return ParseClientVersions(result);
}
else
{
throw new MatrixException("Failed to validate version.");
}
}
[MatrixSpec("r0.0.1/client_server.html#post-matrix-client-r0-register")]
public async void ClientRegister(Requests.Session.MatrixRegister registration)
{
var tuple = await _backend.Post("/_matrix/client/r0/register", false, Helpers.JsonHelper.Serialize(registration));
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
// Parse registration response
}
else
throw new MatrixException(err.ToString());
}
[MatrixSpec("r0.0.1/client_server.html#post-matrix-client-r0-login")]
public async void ClientLogin(Requests.Session.MatrixLogin login)
{
var tuple = await _backend.Post("/_matrix/client/r0/login", false, Helpers.JsonHelper.Serialize(login));
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
// We logged in!
ParseLoginResponse(result);
}
else
{
//throw new MatrixException(err.ToString());
Events.FireLoginFailEvent(err.ToString());
}
}
public async void ClientProfile(string userId)
{
var tuple = await _backend.Get("/_matrix/client/r0/profile/" + userId, true);
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
Responses.UserData.UserProfileResponse profileResponse = ParseUserProfile(result);
Events.FireUserProfileReceivedEvent(userId, profileResponse.AvatarUrl, profileResponse.DisplayName);
}
else
{
// Fire an error
}
}
public async Task<bool> ClientSetDisplayName(string displayName)
{
Requests.UserData.UserProfileSetDisplayName req = new Requests.UserData.UserProfileSetDisplayName() { DisplayName = displayName };
var tuple = await _backend.Put(string.Format("/_matrix/client/r0/profile/{0}/displayname", Uri.EscapeDataString(UserID)), true, Helpers.JsonHelper.Serialize(req));
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
return true;
}
return false;
}
public async Task<bool> ClientSetAvatar(string avatarUrl)
{
Requests.UserData.UserProfileSetAvatar req = new Requests.UserData.UserProfileSetAvatar() { AvatarUrl = avatarUrl };
var tuple = await _backend.Put(string.Format("/_matrix/client/r0/profile/{0}/displayname", Uri.EscapeDataString(UserID)), true, Helpers.JsonHelper.Serialize(req));
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
return true;
}
return false;
}
public async Task<bool> ClientSetPresence(string presence, string statusMessage = null)
{
Requests.Presence.MatrixSetPresence req = new Requests.Presence.MatrixSetPresence()
{
Presence = presence
};
if (statusMessage != null)
{
req.StatusMessage = statusMessage;
}
var tuple = await _backend.Put(string.Format("/_matrix/client/r0/presence/{0}/status", Uri.EscapeDataString(UserID)), true, Helpers.JsonHelper.Serialize(req));
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
return true;
}
return false;
}
public async Task<string> MediaUpload(string contentType, byte[] data)
{
var tuple = await _backend.Post("/_matrix/media/r0/upload", true, data, new Dictionary<string, string>() { { "Content-Type", contentType } });
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
// Parse response
return ParseMediaUpload(result);
}
return "";
}
public string GetMediaDownloadUri(string contentUrl)
{
if (!contentUrl.StartsWith("mxc://"))
return string.Empty;
var newUrl = contentUrl.Remove(0, 6);
var contentUrlSplit = newUrl.Split('/');
if (contentUrlSplit.Count() < 2)
return string.Empty;
string uriPath = _backend.GetPath(string.Format("/_matrix/media/r0/download/{0}/{1}", contentUrlSplit[0], contentUrlSplit[1]), false);
return uriPath;
}
public async void JoinedRooms()
{
var tuple = await _backend.Get("/_matrix/client/r0/joined_rooms", true);
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
// Parse joined rooms
ParseJoinedRooms(result);
}
}
public async Task<bool> InviteToRoom(string roomId, string userId)
{
Requests.Rooms.MatrixRoomInvite invite = new Requests.Rooms.MatrixRoomInvite() { UserID = userId };
var tuple = await _backend.Post(string.Format("/_matrix/client/r0/rooms/{0}/invite", System.Uri.EscapeDataString(roomId)), true, Helpers.JsonHelper.Serialize(invite));
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
return true;
}
throw new MatrixException(err.ToString());
}
public async Task<bool> JoinRoom(string roomId)
{
Requests.Rooms.MatrixRoomJoin roomJoin = new Requests.Rooms.MatrixRoomJoin();
var tuple = await _backend.Post(string.Format("/_matrix/client/r0/rooms/{0}/join", Uri.EscapeDataString(roomId)), true, Helpers.JsonHelper.Serialize(roomJoin));
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
return true;
}
return false;
}
public async Task<bool> CreateRoom(string roomName, string roomTopic, bool isDirect = false)
{
if (string.IsNullOrEmpty(roomName))
return false;
Requests.Rooms.MatrixRoomCreate roomCreate = new Requests.Rooms.MatrixRoomCreate
{
Name = roomName,
IsDirect = isDirect
};
if (string.IsNullOrEmpty(roomTopic))
roomCreate.Topic = roomTopic;
var tuple = await _backend.Post("/_matrix/client/r0/createRoom", true, Helpers.JsonHelper.Serialize(roomCreate));
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
try
{
ParseCreatedRoom(result);
return true;
}
catch (MatrixException)
{
// Failed to create the room
return false;
}
}
return false;
}
public async Task<bool> AddRoomAlias(string roomId, string alias)
{
Requests.Rooms.MatrixRoomAddAlias roomAddAlias = new Requests.Rooms.MatrixRoomAddAlias
{
RoomID = roomId
};
var tuple = await _backend.Put(string.Format("/_matrix/client/r0/directory/room/{0}", Uri.EscapeDataString(alias)), true, Helpers.JsonHelper.Serialize(roomAddAlias));
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
return true;
}
return false;
}
public async Task<bool> DeleteRoomAlias(string roomAlias)
{
var tuple = await _backend.Delete(string.Format("/_matrix/client/r0/directory/room/{0}", Uri.EscapeDataString(roomAlias)), true);
MatrixRequestError err = tuple.Item1;
if (err.IsOk)
{
return true;
}
return false;
}
public async Task<bool> LeaveRoom(string roomId)
{
var tuple = await _backend.Post(string.Format("/_matrix/client/r0/rooms/{0}/leave", Uri.EscapeDataString(roomId)), true, "");
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
return true;
}
return false;
}
public async void RoomTypingSend(string roomId, bool typing, int timeout = 0)
{
Requests.Rooms.MatrixRoomSendTyping req = new Requests.Rooms.MatrixRoomSendTyping() { Typing = typing };
if (timeout > 0)
req.Timeout = timeout;
var tuple = await _backend.Put(string.Format("/_matrix/client/r0/rooms/{0}/typing/{1}", Uri.EscapeDataString(roomId), Uri.EscapeDataString(UserID)), true, Helpers.JsonHelper.Serialize(req));
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (!err.IsOk)
throw new MatrixException(err.ToString());
}
public async Task<bool> GetRoomState(string roomId, string eventType = null, string stateKey = null)
{
string url = string.Format("/_matrix/client/r0/rooms/{0}/state", roomId);
if (!string.IsNullOrEmpty(eventType))
url += "/" + eventType;
if (!string.IsNullOrEmpty(stateKey))
url += "/" + stateKey;
var tuple = await _backend.Get(url, true);
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
// Parse stuff
// Parsing will differ if there is no eventType specified
if (!string.IsNullOrEmpty(eventType))
{
}
else
{
}
return true;
}
return false;
}
private async Task<bool> SendEventToRoom(string roomId, string eventType, string content)
{
var tuple = await _backend.Put(string.Format("/_matrix/client/r0/rooms/{0}/send/{1}/{2}", Uri.EscapeDataString(roomId), eventType, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()), true, content);
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
return true;
return false;
}
public async Task<bool> SendTextMessageToRoom(string roomId, string message)
{
Requests.Rooms.Message.MatrixRoomMessageText req = new Requests.Rooms.Message.MatrixRoomMessageText()
{
Body = message
};
return await SendEventToRoom(roomId, "m.room.message", Helpers.JsonHelper.Serialize(req));
}
public async Task<bool> SendLocationToRoom(string roomId, string description, double lat, double lon)
{
StringBuilder sb = new StringBuilder("geo:");
sb.Append(lat);
sb.Append(",");
sb.Append(lon);
Requests.Rooms.Message.MatrixRoomMessageLocation req = new Requests.Rooms.Message.MatrixRoomMessageLocation()
{
Description = description,
GeoUri = sb.ToString()
};
return await SendEventToRoom(roomId, "m.room.message", Helpers.JsonHelper.Serialize(req));
}
public async Task<bool> SetPusher(string pushUrl, string pushKey)
{
Requests.Pushers.MatrixSetPusher req = new Requests.Pushers.MatrixSetPusher()
{
PushKey = pushKey,
Kind = "http",
AppID = AppInfo.ApplicationID,
AppDisplayName = AppInfo.ApplicationName,
DeviceDisplayName = DeviceName,
Language = "en",
Append = false
};
req.Data = new Requests.Pushers.MatrixPusherData()
{
Url = pushUrl,
Format = "event_id_only"
};
var jsonData = Helpers.JsonHelper.Serialize(req);
var tuple = await _backend.Post("/_matrix/client/r0/pushers/set", true, jsonData);
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
return true;
}
return false;
}
public async Task<bool> GetNotifications(string from = "", int limit = -1, string only = "")
{
StringBuilder url = new StringBuilder("/_matrix/client/r0/notifications");
Dictionary<string, string> urlParams = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(from))
urlParams.Add("from", from);
if (limit != -1)
urlParams.Add("limit", limit.ToString());
if (!string.IsNullOrEmpty(only))
urlParams.Add("only", only);
if (urlParams.Count > 0)
{
var enc = new System.Net.Http.FormUrlEncodedContent(urlParams);
url.Append("?" + enc.ReadAsStringAsync().Result);
}
var tuple = await _backend.Get(url.ToString(), true);
MatrixRequestError err = tuple.Item1;
string result = tuple.Item2;
if (err.IsOk)
{
// Parse the response
ParseNotifications(result);
return true;
}
return false;
}
}
}