[SDK] Refactoring with new linter rules
This commit is contained in:
parent
8129ac00a2
commit
a3c5add79e
|
@ -35,8 +35,7 @@ class AccountData {
|
|||
|
||||
/// Get a State event from a table row or from the event stream.
|
||||
factory AccountData.fromJson(Map<String, dynamic> jsonPayload) {
|
||||
final Map<String, dynamic> content =
|
||||
Event.getMapFromPayload(jsonPayload['content']);
|
||||
final content = Event.getMapFromPayload(jsonPayload['content']);
|
||||
return AccountData(content: content, typeKey: jsonPayload['type']);
|
||||
}
|
||||
}
|
||||
|
|
1066
lib/src/client.dart
1066
lib/src/client.dart
File diff suppressed because it is too large
Load diff
|
@ -47,7 +47,7 @@ class Event {
|
|||
/// The user who has sent this event if it is not a global account data event.
|
||||
final String senderId;
|
||||
|
||||
User get sender => room.getUserByMXIDSync(senderId ?? "@unknown");
|
||||
User get sender => room.getUserByMXIDSync(senderId ?? '@unknown');
|
||||
|
||||
/// The time this event has received at the server. May be null for events like
|
||||
/// account data.
|
||||
|
@ -78,17 +78,17 @@ class Event {
|
|||
|
||||
static const int defaultStatus = 2;
|
||||
static const Map<String, int> STATUS_TYPE = {
|
||||
"ERROR": -1,
|
||||
"SENDING": 0,
|
||||
"SENT": 1,
|
||||
"TIMELINE": 2,
|
||||
"ROOM_STATE": 3,
|
||||
'ERROR': -1,
|
||||
'SENDING': 0,
|
||||
'SENT': 1,
|
||||
'TIMELINE': 2,
|
||||
'ROOM_STATE': 3,
|
||||
};
|
||||
|
||||
/// Optional. The event that redacted this event, if any. Otherwise null.
|
||||
Event get redactedBecause =>
|
||||
unsigned != null && unsigned.containsKey("redacted_because")
|
||||
? Event.fromJson(unsigned["redacted_because"], room)
|
||||
unsigned != null && unsigned.containsKey('redacted_because')
|
||||
? Event.fromJson(unsigned['redacted_because'], room)
|
||||
: null;
|
||||
|
||||
bool get redacted => redactedBecause != null;
|
||||
|
@ -122,12 +122,9 @@ class Event {
|
|||
|
||||
/// Get a State event from a table row or from the event stream.
|
||||
factory Event.fromJson(Map<String, dynamic> jsonPayload, Room room) {
|
||||
final Map<String, dynamic> content =
|
||||
Event.getMapFromPayload(jsonPayload['content']);
|
||||
final Map<String, dynamic> unsigned =
|
||||
Event.getMapFromPayload(jsonPayload['unsigned']);
|
||||
final Map<String, dynamic> prevContent =
|
||||
Event.getMapFromPayload(jsonPayload['prev_content']);
|
||||
final content = Event.getMapFromPayload(jsonPayload['content']);
|
||||
final unsigned = Event.getMapFromPayload(jsonPayload['unsigned']);
|
||||
final prevContent = Event.getMapFromPayload(jsonPayload['prev_content']);
|
||||
return Event(
|
||||
status: jsonPayload['status'] ?? defaultStatus,
|
||||
stateKey: jsonPayload['state_key'],
|
||||
|
@ -146,19 +143,19 @@ class Event {
|
|||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
final Map<String, dynamic> data = Map<String, dynamic>();
|
||||
if (this.stateKey != null) data['state_key'] = this.stateKey;
|
||||
if (this.prevContent != null && this.prevContent.isNotEmpty) {
|
||||
data['prev_content'] = this.prevContent;
|
||||
final data = <String, dynamic>{};
|
||||
if (stateKey != null) data['state_key'] = stateKey;
|
||||
if (prevContent != null && prevContent.isNotEmpty) {
|
||||
data['prev_content'] = prevContent;
|
||||
}
|
||||
data['content'] = this.content;
|
||||
data['type'] = this.typeKey;
|
||||
data['event_id'] = this.eventId;
|
||||
data['room_id'] = this.roomId;
|
||||
data['sender'] = this.senderId;
|
||||
data['origin_server_ts'] = this.time.millisecondsSinceEpoch;
|
||||
if (this.unsigned != null && this.unsigned.isNotEmpty) {
|
||||
data['unsigned'] = this.unsigned;
|
||||
data['content'] = content;
|
||||
data['type'] = typeKey;
|
||||
data['event_id'] = eventId;
|
||||
data['room_id'] = roomId;
|
||||
data['sender'] = senderId;
|
||||
data['origin_server_ts'] = time.millisecondsSinceEpoch;
|
||||
if (unsigned != null && unsigned.isNotEmpty) {
|
||||
data['unsigned'] = unsigned;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
@ -183,45 +180,45 @@ class Event {
|
|||
/// Get the real type.
|
||||
EventTypes get type {
|
||||
switch (typeKey) {
|
||||
case "m.room.avatar":
|
||||
case 'm.room.avatar':
|
||||
return EventTypes.RoomAvatar;
|
||||
case "m.room.name":
|
||||
case 'm.room.name':
|
||||
return EventTypes.RoomName;
|
||||
case "m.room.topic":
|
||||
case 'm.room.topic':
|
||||
return EventTypes.RoomTopic;
|
||||
case "m.room.aliases":
|
||||
case 'm.room.aliases':
|
||||
return EventTypes.RoomAliases;
|
||||
case "m.room.canonical_alias":
|
||||
case 'm.room.canonical_alias':
|
||||
return EventTypes.RoomCanonicalAlias;
|
||||
case "m.room.create":
|
||||
case 'm.room.create':
|
||||
return EventTypes.RoomCreate;
|
||||
case "m.room.redaction":
|
||||
case 'm.room.redaction':
|
||||
return EventTypes.Redaction;
|
||||
case "m.room.join_rules":
|
||||
case 'm.room.join_rules':
|
||||
return EventTypes.RoomJoinRules;
|
||||
case "m.room.member":
|
||||
case 'm.room.member':
|
||||
return EventTypes.RoomMember;
|
||||
case "m.room.power_levels":
|
||||
case 'm.room.power_levels':
|
||||
return EventTypes.RoomPowerLevels;
|
||||
case "m.room.guest_access":
|
||||
case 'm.room.guest_access':
|
||||
return EventTypes.GuestAccess;
|
||||
case "m.room.history_visibility":
|
||||
case 'm.room.history_visibility':
|
||||
return EventTypes.HistoryVisibility;
|
||||
case "m.sticker":
|
||||
case 'm.sticker':
|
||||
return EventTypes.Sticker;
|
||||
case "m.room.message":
|
||||
case 'm.room.message':
|
||||
return EventTypes.Message;
|
||||
case "m.room.encrypted":
|
||||
case 'm.room.encrypted':
|
||||
return EventTypes.Encrypted;
|
||||
case "m.room.encryption":
|
||||
case 'm.room.encryption':
|
||||
return EventTypes.Encryption;
|
||||
case "m.call.invite":
|
||||
case 'm.call.invite':
|
||||
return EventTypes.CallInvite;
|
||||
case "m.call.answer":
|
||||
case 'm.call.answer':
|
||||
return EventTypes.CallAnswer;
|
||||
case "m.call.candidates":
|
||||
case 'm.call.candidates':
|
||||
return EventTypes.CallCandidates;
|
||||
case "m.call.hangup":
|
||||
case 'm.call.hangup':
|
||||
return EventTypes.CallHangup;
|
||||
}
|
||||
return EventTypes.Unknown;
|
||||
|
@ -229,29 +226,29 @@ class Event {
|
|||
|
||||
///
|
||||
MessageTypes get messageType {
|
||||
switch (content["msgtype"] ?? "m.text") {
|
||||
case "m.text":
|
||||
if (content.containsKey("m.relates_to")) {
|
||||
switch (content['msgtype'] ?? 'm.text') {
|
||||
case 'm.text':
|
||||
if (content.containsKey('m.relates_to')) {
|
||||
return MessageTypes.Reply;
|
||||
}
|
||||
return MessageTypes.Text;
|
||||
case "m.notice":
|
||||
case 'm.notice':
|
||||
return MessageTypes.Notice;
|
||||
case "m.emote":
|
||||
case 'm.emote':
|
||||
return MessageTypes.Emote;
|
||||
case "m.image":
|
||||
case 'm.image':
|
||||
return MessageTypes.Image;
|
||||
case "m.video":
|
||||
case 'm.video':
|
||||
return MessageTypes.Video;
|
||||
case "m.audio":
|
||||
case 'm.audio':
|
||||
return MessageTypes.Audio;
|
||||
case "m.file":
|
||||
case 'm.file':
|
||||
return MessageTypes.File;
|
||||
case "m.sticker":
|
||||
case 'm.sticker':
|
||||
return MessageTypes.Sticker;
|
||||
case "m.location":
|
||||
case 'm.location':
|
||||
return MessageTypes.Location;
|
||||
case "m.bad.encrypted":
|
||||
case 'm.bad.encrypted':
|
||||
return MessageTypes.BadEncrypted;
|
||||
default:
|
||||
if (type == EventTypes.Message) {
|
||||
|
@ -263,40 +260,40 @@ class Event {
|
|||
|
||||
void setRedactionEvent(Event redactedBecause) {
|
||||
unsigned = {
|
||||
"redacted_because": redactedBecause.toJson(),
|
||||
'redacted_because': redactedBecause.toJson(),
|
||||
};
|
||||
prevContent = null;
|
||||
List<String> contentKeyWhiteList = [];
|
||||
var contentKeyWhiteList = <String>[];
|
||||
switch (type) {
|
||||
case EventTypes.RoomMember:
|
||||
contentKeyWhiteList.add("membership");
|
||||
contentKeyWhiteList.add('membership');
|
||||
break;
|
||||
case EventTypes.RoomCreate:
|
||||
contentKeyWhiteList.add("creator");
|
||||
contentKeyWhiteList.add('creator');
|
||||
break;
|
||||
case EventTypes.RoomJoinRules:
|
||||
contentKeyWhiteList.add("join_rule");
|
||||
contentKeyWhiteList.add('join_rule');
|
||||
break;
|
||||
case EventTypes.RoomPowerLevels:
|
||||
contentKeyWhiteList.add("ban");
|
||||
contentKeyWhiteList.add("events");
|
||||
contentKeyWhiteList.add("events_default");
|
||||
contentKeyWhiteList.add("kick");
|
||||
contentKeyWhiteList.add("redact");
|
||||
contentKeyWhiteList.add("state_default");
|
||||
contentKeyWhiteList.add("users");
|
||||
contentKeyWhiteList.add("users_default");
|
||||
contentKeyWhiteList.add('ban');
|
||||
contentKeyWhiteList.add('events');
|
||||
contentKeyWhiteList.add('events_default');
|
||||
contentKeyWhiteList.add('kick');
|
||||
contentKeyWhiteList.add('redact');
|
||||
contentKeyWhiteList.add('state_default');
|
||||
contentKeyWhiteList.add('users');
|
||||
contentKeyWhiteList.add('users_default');
|
||||
break;
|
||||
case EventTypes.RoomAliases:
|
||||
contentKeyWhiteList.add("aliases");
|
||||
contentKeyWhiteList.add('aliases');
|
||||
break;
|
||||
case EventTypes.HistoryVisibility:
|
||||
contentKeyWhiteList.add("history_visibility");
|
||||
contentKeyWhiteList.add('history_visibility');
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
List<String> toRemoveList = [];
|
||||
var toRemoveList = <String>[];
|
||||
for (var entry in content.entries) {
|
||||
if (!contentKeyWhiteList.contains(entry.key)) {
|
||||
toRemoveList.add(entry.key);
|
||||
|
@ -306,30 +303,30 @@ class Event {
|
|||
}
|
||||
|
||||
/// Returns the body of this event if it has a body.
|
||||
String get text => content["body"] ?? "";
|
||||
String get text => content['body'] ?? '';
|
||||
|
||||
/// Returns the formatted boy of this event if it has a formatted body.
|
||||
String get formattedText => content["formatted_body"] ?? "";
|
||||
String get formattedText => content['formatted_body'] ?? '';
|
||||
|
||||
@Deprecated("Use [body] instead.")
|
||||
@Deprecated('Use [body] instead.')
|
||||
String getBody() => body;
|
||||
|
||||
/// Use this to get the body.
|
||||
String get body {
|
||||
if (redacted) return "Redacted";
|
||||
if (text != "") return text;
|
||||
if (formattedText != "") return formattedText;
|
||||
return "$type";
|
||||
if (redacted) return 'Redacted';
|
||||
if (text != '') return text;
|
||||
if (formattedText != '') return formattedText;
|
||||
return '$type';
|
||||
}
|
||||
|
||||
/// Returns a list of [Receipt] instances for this event.
|
||||
List<Receipt> get receipts {
|
||||
if (!(room.roomAccountData.containsKey("m.receipt"))) return [];
|
||||
List<Receipt> receiptsList = [];
|
||||
for (var entry in room.roomAccountData["m.receipt"].content.entries) {
|
||||
if (entry.value["event_id"] == eventId) {
|
||||
if (!(room.roomAccountData.containsKey('m.receipt'))) return [];
|
||||
var receiptsList = <Receipt>[];
|
||||
for (var entry in room.roomAccountData['m.receipt'].content.entries) {
|
||||
if (entry.value['event_id'] == eventId) {
|
||||
receiptsList.add(Receipt(room.getUserByMXIDSync(entry.key),
|
||||
DateTime.fromMillisecondsSinceEpoch(entry.value["ts"])));
|
||||
DateTime.fromMillisecondsSinceEpoch(entry.value['ts'])));
|
||||
}
|
||||
}
|
||||
return receiptsList;
|
||||
|
@ -345,12 +342,12 @@ class Event {
|
|||
|
||||
room.client.onEvent.add(EventUpdate(
|
||||
roomID: room.id,
|
||||
type: "timeline",
|
||||
type: 'timeline',
|
||||
eventType: typeKey,
|
||||
content: {
|
||||
"event_id": eventId,
|
||||
"status": -2,
|
||||
"content": {"body": "Removed..."}
|
||||
'event_id': eventId,
|
||||
'status': -2,
|
||||
'content': {'body': 'Removed...'}
|
||||
}));
|
||||
return true;
|
||||
}
|
||||
|
@ -361,7 +358,7 @@ class Event {
|
|||
Future<String> sendAgain({String txid}) async {
|
||||
if (status != -1) return null;
|
||||
await remove();
|
||||
final String eventID = await room.sendTextEvent(text, txid: txid);
|
||||
final eventID = await room.sendTextEvent(text, txid: txid);
|
||||
return eventID;
|
||||
}
|
||||
|
||||
|
@ -397,34 +394,34 @@ class Event {
|
|||
/// in the room. If the event is not encrypted or the decryption failed because
|
||||
/// of a different error, this throws an exception.
|
||||
Future<void> requestKey() async {
|
||||
if (this.type != EventTypes.Encrypted ||
|
||||
this.messageType != MessageTypes.BadEncrypted ||
|
||||
this.content["body"] != DecryptError.UNKNOWN_SESSION) {
|
||||
throw ("Session key not unknown");
|
||||
if (type != EventTypes.Encrypted ||
|
||||
messageType != MessageTypes.BadEncrypted ||
|
||||
content['body'] != DecryptError.UNKNOWN_SESSION) {
|
||||
throw ('Session key not unknown');
|
||||
}
|
||||
final List<User> users = await room.requestParticipants();
|
||||
final users = await room.requestParticipants();
|
||||
await room.client.sendToDevice(
|
||||
[],
|
||||
"m.room_key_request",
|
||||
'm.room_key_request',
|
||||
{
|
||||
"action": "request_cancellation",
|
||||
"request_id": base64.encode(utf8.encode(content["session_id"])),
|
||||
"requesting_device_id": room.client.deviceID,
|
||||
'action': 'request_cancellation',
|
||||
'request_id': base64.encode(utf8.encode(content['session_id'])),
|
||||
'requesting_device_id': room.client.deviceID,
|
||||
},
|
||||
toUsers: users);
|
||||
await room.client.sendToDevice(
|
||||
[],
|
||||
"m.room_key_request",
|
||||
'm.room_key_request',
|
||||
{
|
||||
"action": "request",
|
||||
"body": {
|
||||
"algorithm": "m.megolm.v1.aes-sha2",
|
||||
"room_id": roomId,
|
||||
"sender_key": content["sender_key"],
|
||||
"session_id": content["session_id"],
|
||||
'action': 'request',
|
||||
'body': {
|
||||
'algorithm': 'm.megolm.v1.aes-sha2',
|
||||
'room_id': roomId,
|
||||
'sender_key': content['sender_key'],
|
||||
'session_id': content['session_id'],
|
||||
},
|
||||
"request_id": base64.encode(utf8.encode(content["session_id"])),
|
||||
"requesting_device_id": room.client.deviceID,
|
||||
'request_id': base64.encode(utf8.encode(content['session_id'])),
|
||||
'requesting_device_id': room.client.deviceID,
|
||||
},
|
||||
encrypted: false,
|
||||
toUsers: users);
|
||||
|
@ -435,27 +432,27 @@ class Event {
|
|||
/// event and returns it as a [MatrixFile]. If this event doesn't
|
||||
/// contain an attachment, this throws an error.
|
||||
Future<MatrixFile> downloadAndDecryptAttachment() async {
|
||||
if (![EventTypes.Message, EventTypes.Sticker].contains(this.type)) {
|
||||
if (![EventTypes.Message, EventTypes.Sticker].contains(type)) {
|
||||
throw ("This event has the type '$typeKey' and so it can't contain an attachment.");
|
||||
}
|
||||
if (!content.containsKey("url") && !content.containsKey("file")) {
|
||||
if (!content.containsKey('url') && !content.containsKey('file')) {
|
||||
throw ("This event hasn't any attachment.");
|
||||
}
|
||||
final bool isEncrypted = !content.containsKey("url");
|
||||
final isEncrypted = !content.containsKey('url');
|
||||
|
||||
if (isEncrypted && !room.client.encryptionEnabled) {
|
||||
throw ("Encryption is not enabled in your Client.");
|
||||
throw ('Encryption is not enabled in your Client.');
|
||||
}
|
||||
MxContent mxContent =
|
||||
MxContent(isEncrypted ? content["file"]["url"] : content["url"]);
|
||||
var mxContent =
|
||||
MxContent(isEncrypted ? content['file']['url'] : content['url']);
|
||||
|
||||
Uint8List uint8list;
|
||||
|
||||
// Is this file storeable?
|
||||
final bool storeable = room.client.storeAPI.extended &&
|
||||
content["info"] is Map<String, dynamic> &&
|
||||
content["info"]["size"] is int &&
|
||||
content["info"]["size"] <= ExtendedStoreAPI.MAX_FILE_SIZE;
|
||||
final storeable = room.client.storeAPI.extended &&
|
||||
content['info'] is Map<String, dynamic> &&
|
||||
content['info']['size'] is int &&
|
||||
content['info']['size'] <= ExtendedStoreAPI.MAX_FILE_SIZE;
|
||||
|
||||
if (storeable) {
|
||||
uint8list = await room.client.store.getFile(mxContent.mxc);
|
||||
|
@ -470,18 +467,18 @@ class Event {
|
|||
|
||||
// Decrypt the file
|
||||
if (isEncrypted) {
|
||||
if (!content.containsKey("file") ||
|
||||
!content["file"]["key"]["key_ops"].contains("decrypt")) {
|
||||
if (!content.containsKey('file') ||
|
||||
!content['file']['key']['key_ops'].contains('decrypt')) {
|
||||
throw ("Missing 'decrypt' in 'key_ops'.");
|
||||
}
|
||||
final EncryptedFile encryptedFile = EncryptedFile();
|
||||
final encryptedFile = EncryptedFile();
|
||||
encryptedFile.data = uint8list;
|
||||
encryptedFile.iv = content["file"]["iv"];
|
||||
encryptedFile.k = content["file"]["key"]["k"];
|
||||
encryptedFile.sha256 = content["file"]["hashes"]["sha256"];
|
||||
encryptedFile.iv = content['file']['iv'];
|
||||
encryptedFile.k = content['file']['key']['k'];
|
||||
encryptedFile.sha256 = content['file']['hashes']['sha256'];
|
||||
uint8list = await decryptFile(encryptedFile);
|
||||
}
|
||||
return MatrixFile(bytes: uint8list, path: "/$body");
|
||||
return MatrixFile(bytes: uint8list, path: '/$body');
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -44,7 +44,7 @@ class Presence {
|
|||
Presence.fromJson(Map<String, dynamic> json)
|
||||
: sender = json['sender'],
|
||||
displayname = json['content']['displayname'],
|
||||
avatarUrl = MxContent(json['content']['avatar_url'] ?? ""),
|
||||
avatarUrl = MxContent(json['content']['avatar_url'] ?? ''),
|
||||
currentlyActive = json['content']['currently_active'],
|
||||
lastActiveAgo = json['content']['last_active_ago'],
|
||||
time = DateTime.fromMillisecondsSinceEpoch(
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -39,8 +39,7 @@ class RoomAccountData extends AccountData {
|
|||
/// Get a State event from a table row or from the event stream.
|
||||
factory RoomAccountData.fromJson(
|
||||
Map<String, dynamic> jsonPayload, Room room) {
|
||||
final Map<String, dynamic> content =
|
||||
Event.getMapFromPayload(jsonPayload['content']);
|
||||
final content = Event.getMapFromPayload(jsonPayload['content']);
|
||||
return RoomAccountData(
|
||||
content: content,
|
||||
typeKey: jsonPayload['type'],
|
||||
|
|
|
@ -66,13 +66,14 @@ abstract class ExtendedStoreAPI extends StoreAPI {
|
|||
|
||||
/// Whether this is a simple store which only stores the client credentials and
|
||||
/// end to end encryption stuff or the whole sync payloads.
|
||||
@override
|
||||
final bool extended = true;
|
||||
|
||||
/// The current trans
|
||||
Future<void> setRoomPrevBatch(String roomId, String prevBatch);
|
||||
|
||||
/// Performs these query or queries inside of an transaction.
|
||||
Future<void> transaction(void queries());
|
||||
Future<void> transaction(void Function() queries);
|
||||
|
||||
/// Will be automatically called on every synchronisation. Must be called inside of
|
||||
// /// [transaction].
|
||||
|
|
|
@ -43,11 +43,11 @@ class EventUpdate {
|
|||
EventUpdate({this.eventType, this.roomID, this.type, this.content});
|
||||
|
||||
EventUpdate decrypt(Room room) {
|
||||
if (eventType != "m.room.encrypted") {
|
||||
if (eventType != 'm.room.encrypted') {
|
||||
return this;
|
||||
}
|
||||
try {
|
||||
Event decrpytedEvent =
|
||||
var decrpytedEvent =
|
||||
room.decryptGroupMessage(Event.fromJson(content, room));
|
||||
return EventUpdate(
|
||||
eventType: eventType,
|
||||
|
@ -56,7 +56,7 @@ class EventUpdate {
|
|||
content: decrpytedEvent.toJson(),
|
||||
);
|
||||
} catch (e) {
|
||||
print("[LibOlm] Could not decrypt megolm event: " + e.toString());
|
||||
print('[LibOlm] Could not decrypt megolm event: ' + e.toString());
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -25,7 +25,6 @@ import 'dart:async';
|
|||
|
||||
import 'event.dart';
|
||||
import 'room.dart';
|
||||
import 'user.dart';
|
||||
import 'sync/event_update.dart';
|
||||
|
||||
typedef onTimelineUpdateCallback = void Function();
|
||||
|
@ -45,17 +44,17 @@ class Timeline {
|
|||
StreamSubscription<String> sessionIdReceivedSub;
|
||||
bool _requestingHistoryLock = false;
|
||||
|
||||
Map<String, Event> _eventCache = {};
|
||||
final Map<String, Event> _eventCache = {};
|
||||
|
||||
/// Searches for the event in this timeline. If not
|
||||
/// found, requests from the server. Requested events
|
||||
/// are cached.
|
||||
Future<Event> getEventById(String id) async {
|
||||
for (int i = 0; i < events.length; i++) {
|
||||
for (var i = 0; i < events.length; i++) {
|
||||
if (events[i].eventId == id) return events[i];
|
||||
}
|
||||
if (_eventCache.containsKey(id)) return _eventCache[id];
|
||||
final Event requestedEvent = await room.getEventById(id);
|
||||
final requestedEvent = await room.getEventById(id);
|
||||
if (requestedEvent == null) return null;
|
||||
_eventCache[id] = requestedEvent;
|
||||
return _eventCache[id];
|
||||
|
@ -89,12 +88,12 @@ class Timeline {
|
|||
}
|
||||
|
||||
void _sessionKeyReceived(String sessionId) {
|
||||
bool decryptAtLeastOneEvent = false;
|
||||
for (int i = 0; i < events.length; i++) {
|
||||
var decryptAtLeastOneEvent = false;
|
||||
for (var i = 0; i < events.length; i++) {
|
||||
if (events[i].type == EventTypes.Encrypted &&
|
||||
events[i].messageType == MessageTypes.BadEncrypted &&
|
||||
events[i].content["body"] == DecryptError.UNKNOWN_SESSION &&
|
||||
events[i].content["session_id"] == sessionId) {
|
||||
events[i].content['body'] == DecryptError.UNKNOWN_SESSION &&
|
||||
events[i].content['session_id'] == sessionId) {
|
||||
events[i] = events[i].decrypted;
|
||||
if (events[i].type != EventTypes.Encrypted) {
|
||||
decryptAtLeastOneEvent = true;
|
||||
|
@ -117,26 +116,25 @@ class Timeline {
|
|||
try {
|
||||
if (eventUpdate.roomID != room.id) return;
|
||||
|
||||
if (eventUpdate.type == "timeline" || eventUpdate.type == "history") {
|
||||
if (eventUpdate.type == 'timeline' || eventUpdate.type == 'history') {
|
||||
// Redaction events are handled as modification for existing events.
|
||||
if (eventUpdate.eventType == "m.room.redaction") {
|
||||
final int eventId =
|
||||
_findEvent(event_id: eventUpdate.content["redacts"]);
|
||||
if (eventUpdate.eventType == 'm.room.redaction') {
|
||||
final eventId = _findEvent(event_id: eventUpdate.content['redacts']);
|
||||
if (eventId != null) {
|
||||
events[eventId]
|
||||
.setRedactionEvent(Event.fromJson(eventUpdate.content, room));
|
||||
}
|
||||
} else if (eventUpdate.content["status"] == -2) {
|
||||
int i = _findEvent(event_id: eventUpdate.content["event_id"]);
|
||||
} else if (eventUpdate.content['status'] == -2) {
|
||||
var i = _findEvent(event_id: eventUpdate.content['event_id']);
|
||||
if (i < events.length) events.removeAt(i);
|
||||
}
|
||||
// Is this event already in the timeline?
|
||||
else if (eventUpdate.content.containsKey("unsigned") &&
|
||||
eventUpdate.content["unsigned"]["transaction_id"] is String) {
|
||||
int i = _findEvent(
|
||||
event_id: eventUpdate.content["event_id"],
|
||||
unsigned_txid: eventUpdate.content.containsKey("unsigned")
|
||||
? eventUpdate.content["unsigned"]["transaction_id"]
|
||||
else if (eventUpdate.content.containsKey('unsigned') &&
|
||||
eventUpdate.content['unsigned']['transaction_id'] is String) {
|
||||
var i = _findEvent(
|
||||
event_id: eventUpdate.content['event_id'],
|
||||
unsigned_txid: eventUpdate.content.containsKey('unsigned')
|
||||
? eventUpdate.content['unsigned']['transaction_id']
|
||||
: null);
|
||||
|
||||
if (i < events.length) {
|
||||
|
@ -144,18 +142,18 @@ class Timeline {
|
|||
}
|
||||
} else {
|
||||
Event newEvent;
|
||||
User senderUser = await room.client.store
|
||||
?.getUser(matrixID: eventUpdate.content["sender"], room: room);
|
||||
var senderUser = await room.client.store
|
||||
?.getUser(matrixID: eventUpdate.content['sender'], room: room);
|
||||
if (senderUser != null) {
|
||||
eventUpdate.content["displayname"] = senderUser.displayName;
|
||||
eventUpdate.content["avatar_url"] = senderUser.avatarUrl.mxc;
|
||||
eventUpdate.content['displayname'] = senderUser.displayName;
|
||||
eventUpdate.content['avatar_url'] = senderUser.avatarUrl.mxc;
|
||||
}
|
||||
|
||||
newEvent = Event.fromJson(eventUpdate.content, room);
|
||||
|
||||
if (eventUpdate.type == "history" &&
|
||||
if (eventUpdate.type == 'history' &&
|
||||
events.indexWhere(
|
||||
(e) => e.eventId == eventUpdate.content["event_id"]) !=
|
||||
(e) => e.eventId == eventUpdate.content['event_id']) !=
|
||||
-1) return;
|
||||
|
||||
events.insert(0, newEvent);
|
||||
|
@ -165,14 +163,14 @@ class Timeline {
|
|||
sortAndUpdate();
|
||||
} catch (e) {
|
||||
if (room.client.debug) {
|
||||
print("[WARNING] (_handleEventUpdate) ${e.toString()}");
|
||||
print('[WARNING] (_handleEventUpdate) ${e.toString()}');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool sortLock = false;
|
||||
|
||||
sort() {
|
||||
void sort() {
|
||||
if (sortLock || events.length < 2) return;
|
||||
sortLock = true;
|
||||
events?.sort((a, b) =>
|
||||
|
@ -180,7 +178,7 @@ class Timeline {
|
|||
sortLock = false;
|
||||
}
|
||||
|
||||
sortAndUpdate() {
|
||||
void sortAndUpdate() async {
|
||||
sort();
|
||||
if (onUpdate != null) onUpdate();
|
||||
}
|
||||
|
|
|
@ -37,14 +37,14 @@ class User extends Event {
|
|||
String avatarUrl,
|
||||
Room room,
|
||||
}) {
|
||||
Map<String, String> content = {};
|
||||
if (membership != null) content["membership"] = membership;
|
||||
if (displayName != null) content["displayname"] = displayName;
|
||||
if (avatarUrl != null) content["avatar_url"] = avatarUrl;
|
||||
var content = <String, String>{};
|
||||
if (membership != null) content['membership'] = membership;
|
||||
if (displayName != null) content['displayname'] = displayName;
|
||||
if (avatarUrl != null) content['avatar_url'] = avatarUrl;
|
||||
return User.fromState(
|
||||
stateKey: id,
|
||||
content: content,
|
||||
typeKey: "m.room.member",
|
||||
typeKey: 'm.room.member',
|
||||
roomId: room?.id,
|
||||
room: room,
|
||||
time: DateTime.now(),
|
||||
|
@ -78,7 +78,7 @@ class User extends Event {
|
|||
String get id => stateKey;
|
||||
|
||||
/// The displayname of the user if the user has set one.
|
||||
String get displayName => content != null ? content["displayname"] : null;
|
||||
String get displayName => content != null ? content['displayname'] : null;
|
||||
|
||||
/// Returns the power level of this user.
|
||||
int get powerLevel => room?.getPowerLevelByUserId(id);
|
||||
|
@ -89,21 +89,21 @@ class User extends Event {
|
|||
/// leave
|
||||
/// ban
|
||||
Membership get membership => Membership.values.firstWhere((e) {
|
||||
if (content["membership"] != null) {
|
||||
if (content['membership'] != null) {
|
||||
return e.toString() == 'Membership.' + content['membership'];
|
||||
}
|
||||
return false;
|
||||
}, orElse: () => Membership.join);
|
||||
|
||||
/// The avatar if the user has one.
|
||||
MxContent get avatarUrl => content != null && content["avatar_url"] is String
|
||||
? MxContent(content["avatar_url"])
|
||||
: MxContent("");
|
||||
MxContent get avatarUrl => content != null && content['avatar_url'] is String
|
||||
? MxContent(content['avatar_url'])
|
||||
: MxContent('');
|
||||
|
||||
/// Returns the displayname or the local part of the Matrix ID if the user
|
||||
/// has no displayname.
|
||||
String calcDisplayname() => (displayName == null || displayName.isEmpty)
|
||||
? (stateKey != null ? stateKey.localpart : "Unknown User")
|
||||
? (stateKey != null ? stateKey.localpart : 'Unknown User')
|
||||
: displayName;
|
||||
|
||||
/// Call the Matrix API to kick this user from this room.
|
||||
|
@ -122,20 +122,20 @@ class User extends Event {
|
|||
/// Returns null on error.
|
||||
Future<String> startDirectChat() async {
|
||||
// Try to find an existing direct chat
|
||||
String roomID = await room.client?.getDirectChatFromUserId(id);
|
||||
var roomID = await room.client?.getDirectChatFromUserId(id);
|
||||
if (roomID != null) return roomID;
|
||||
|
||||
// Start a new direct chat
|
||||
final dynamic resp = await room.client.jsonRequest(
|
||||
type: HTTPType.POST,
|
||||
action: "/client/r0/createRoom",
|
||||
action: '/client/r0/createRoom',
|
||||
data: {
|
||||
"invite": [id],
|
||||
"is_direct": true,
|
||||
"preset": "trusted_private_chat"
|
||||
'invite': [id],
|
||||
'is_direct': true,
|
||||
'preset': 'trusted_private_chat'
|
||||
});
|
||||
|
||||
final String newRoomID = resp["room_id"];
|
||||
final String newRoomID = resp['room_id'];
|
||||
|
||||
if (newRoomID == null) return newRoomID;
|
||||
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
import 'dart:convert';
|
||||
|
||||
import '../client.dart';
|
||||
import '../room.dart';
|
||||
|
||||
class DeviceKeysList {
|
||||
String userId;
|
||||
|
@ -19,18 +18,20 @@ class DeviceKeysList {
|
|||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
final Map<String, dynamic> data = Map<String, dynamic>();
|
||||
data['user_id'] = this.userId;
|
||||
data['outdated'] = this.outdated ?? true;
|
||||
var map = <String, dynamic>{};
|
||||
final data = map;
|
||||
data['user_id'] = userId;
|
||||
data['outdated'] = outdated ?? true;
|
||||
|
||||
Map<String, dynamic> rawDeviceKeys = {};
|
||||
for (final deviceKeyEntry in this.deviceKeys.entries) {
|
||||
var rawDeviceKeys = <String, dynamic>{};
|
||||
for (final deviceKeyEntry in deviceKeys.entries) {
|
||||
rawDeviceKeys[deviceKeyEntry.key] = deviceKeyEntry.value.toJson();
|
||||
}
|
||||
data['device_keys'] = rawDeviceKeys;
|
||||
return data;
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() => json.encode(toJson());
|
||||
|
||||
DeviceKeysList(this.userId);
|
||||
|
@ -46,8 +47,8 @@ class DeviceKeys {
|
|||
bool verified;
|
||||
bool blocked;
|
||||
|
||||
String get curve25519Key => keys["curve25519:$deviceId"];
|
||||
String get ed25519Key => keys["ed25519:$deviceId"];
|
||||
String get curve25519Key => keys['curve25519:$deviceId'];
|
||||
String get ed25519Key => keys['ed25519:$deviceId'];
|
||||
|
||||
Future<void> setVerified(bool newVerified, Client client) {
|
||||
verified = newVerified;
|
||||
|
@ -56,7 +57,7 @@ class DeviceKeys {
|
|||
|
||||
Future<void> setBlocked(bool newBlocked, Client client) {
|
||||
blocked = newBlocked;
|
||||
for (Room room in client.rooms) {
|
||||
for (var room in client.rooms) {
|
||||
if (!room.encrypted) continue;
|
||||
if (room.getParticipants().indexWhere((u) => u.id == userId) != -1) {
|
||||
room.clearOutboundGroupSession();
|
||||
|
@ -92,21 +93,21 @@ class DeviceKeys {
|
|||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
final Map<String, dynamic> data = Map<String, dynamic>();
|
||||
data['user_id'] = this.userId;
|
||||
data['device_id'] = this.deviceId;
|
||||
data['algorithms'] = this.algorithms;
|
||||
if (this.keys != null) {
|
||||
data['keys'] = this.keys;
|
||||
final data = <String, dynamic>{};
|
||||
data['user_id'] = userId;
|
||||
data['device_id'] = deviceId;
|
||||
data['algorithms'] = algorithms;
|
||||
if (keys != null) {
|
||||
data['keys'] = keys;
|
||||
}
|
||||
if (this.signatures != null) {
|
||||
data['signatures'] = this.signatures;
|
||||
if (signatures != null) {
|
||||
data['signatures'] = signatures;
|
||||
}
|
||||
if (this.unsigned != null) {
|
||||
data['unsigned'] = this.unsigned;
|
||||
if (unsigned != null) {
|
||||
data['unsigned'] = unsigned;
|
||||
}
|
||||
data['verified'] = this.verified;
|
||||
data['blocked'] = this.blocked;
|
||||
data['verified'] = verified;
|
||||
data['blocked'] = blocked;
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -48,34 +48,34 @@ class MatrixException implements Exception {
|
|||
|
||||
/// The unique identifier for this error.
|
||||
String get errcode =>
|
||||
raw["errcode"] ??
|
||||
(requireAdditionalAuthentication ? "M_FORBIDDEN" : "M_UNKNOWN");
|
||||
raw['errcode'] ??
|
||||
(requireAdditionalAuthentication ? 'M_FORBIDDEN' : 'M_UNKNOWN');
|
||||
|
||||
/// A human readable error description.
|
||||
String get errorMessage =>
|
||||
raw["error"] ??
|
||||
raw['error'] ??
|
||||
(requireAdditionalAuthentication
|
||||
? "Require additional authentication"
|
||||
: "Unknown error");
|
||||
? 'Require additional authentication'
|
||||
: 'Unknown error');
|
||||
|
||||
/// The frozen request which triggered this Error
|
||||
http.Response response;
|
||||
|
||||
MatrixException(this.response) : this.raw = json.decode(response.body);
|
||||
MatrixException(this.response) : raw = json.decode(response.body);
|
||||
|
||||
@override
|
||||
String toString() => "$errcode: $errorMessage";
|
||||
String toString() => '$errcode: $errorMessage';
|
||||
|
||||
/// Returns the [ResponseError]. Is ResponseError.NONE if there wasn't an error.
|
||||
MatrixError get error => MatrixError.values.firstWhere(
|
||||
(e) => e.toString() == 'MatrixError.${(raw["errcode"] ?? "")}',
|
||||
orElse: () => MatrixError.M_UNKNOWN);
|
||||
|
||||
int get retryAfterMs => raw["retry_after_ms"];
|
||||
int get retryAfterMs => raw['retry_after_ms'];
|
||||
|
||||
/// This is a session identifier that the client must pass back to the homeserver, if one is provided,
|
||||
/// in subsequent attempts to authenticate in the same API call.
|
||||
String get session => raw["session"];
|
||||
String get session => raw['session'];
|
||||
|
||||
/// Returns true if the server requires additional authentication.
|
||||
bool get requireAdditionalAuthentication => response.statusCode == 401;
|
||||
|
@ -84,11 +84,11 @@ class MatrixException implements Exception {
|
|||
/// to authenticate itself. Each flow comprises a series of stages. If this request
|
||||
/// doesn't need additional authentication, then this is null.
|
||||
List<AuthenticationFlow> get authenticationFlows {
|
||||
if (!raw.containsKey("flows") || !(raw["flows"] is List)) return null;
|
||||
List<AuthenticationFlow> flows = [];
|
||||
for (Map<String, dynamic> flow in raw["flows"]) {
|
||||
if (flow["stages"] is List) {
|
||||
flows.add(AuthenticationFlow(List<String>.from(flow["stages"])));
|
||||
if (!raw.containsKey('flows') || !(raw['flows'] is List)) return null;
|
||||
var flows = <AuthenticationFlow>[];
|
||||
for (Map<String, dynamic> flow in raw['flows']) {
|
||||
if (flow['stages'] is List) {
|
||||
flows.add(AuthenticationFlow(List<String>.from(flow['stages'])));
|
||||
}
|
||||
}
|
||||
return flows;
|
||||
|
@ -97,10 +97,11 @@ class MatrixException implements Exception {
|
|||
/// This section contains any information that the client will need to know in order to use a given type
|
||||
/// of authentication. For each authentication type presented, that type may be present as a key in this
|
||||
/// dictionary. For example, the public part of an OAuth client ID could be given here.
|
||||
Map<String, dynamic> get authenticationParams => raw["params"];
|
||||
Map<String, dynamic> get authenticationParams => raw['params'];
|
||||
|
||||
/// Returns the list of already completed authentication flows from previous requests.
|
||||
List<String> get completedAuthenticationFlows => List<String>.from(raw["completed"] ?? []);
|
||||
List<String> get completedAuthenticationFlows =>
|
||||
List<String>.from(raw['completed'] ?? []);
|
||||
}
|
||||
|
||||
/// For each endpoint, a server offers one or more 'flows' that the client can use
|
||||
|
|
|
@ -11,11 +11,12 @@ class MatrixFile {
|
|||
/// Encrypts this file, changes the [bytes] and returns the
|
||||
/// encryption information as an [EncryptedFile].
|
||||
Future<EncryptedFile> encrypt() async {
|
||||
final EncryptedFile encryptedFile = await encryptFile(bytes);
|
||||
this.bytes = encryptedFile.data;
|
||||
var encryptFile2 = encryptFile(bytes);
|
||||
final encryptedFile = await encryptFile2;
|
||||
bytes = encryptedFile.data;
|
||||
return encryptedFile;
|
||||
}
|
||||
|
||||
MatrixFile({this.bytes, String path}) : this.path = path.toLowerCase();
|
||||
MatrixFile({this.bytes, String path}) : path = path.toLowerCase();
|
||||
int get size => bytes.length;
|
||||
}
|
||||
|
|
|
@ -1,27 +1,27 @@
|
|||
extension MatrixIdExtension on String {
|
||||
static const Set<String> VALID_SIGILS = {"@", "!", "#", "\$", "+"};
|
||||
static const Set<String> VALID_SIGILS = {'@', '!', '#', '\$', '+'};
|
||||
|
||||
static const int MAX_LENGTH = 255;
|
||||
|
||||
bool get isValidMatrixId {
|
||||
if (this?.isEmpty ?? true) return false;
|
||||
if (this.length > MAX_LENGTH) return false;
|
||||
if (!VALID_SIGILS.contains(this.substring(0, 1))) {
|
||||
if (isEmpty ?? true) return false;
|
||||
if (length > MAX_LENGTH) return false;
|
||||
if (!VALID_SIGILS.contains(substring(0, 1))) {
|
||||
return false;
|
||||
}
|
||||
final List<String> parts = this.substring(1).split(":");
|
||||
final parts = substring(1).split(':');
|
||||
if (parts.length != 2 || parts[0].isEmpty || parts[1].isEmpty) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
String get sigil => isValidMatrixId ? this.substring(0, 1) : null;
|
||||
String get sigil => isValidMatrixId ? substring(0, 1) : null;
|
||||
|
||||
String get localpart =>
|
||||
isValidMatrixId ? this.substring(1).split(":").first : null;
|
||||
isValidMatrixId ? substring(1).split(':').first : null;
|
||||
|
||||
String get domain => isValidMatrixId ? this.substring(1).split(":")[1] : null;
|
||||
String get domain => isValidMatrixId ? substring(1).split(':')[1] : null;
|
||||
|
||||
bool equals(String other) => this?.toLowerCase() == other?.toLowerCase();
|
||||
bool equals(String other) => toLowerCase() == other?.toLowerCase();
|
||||
}
|
||||
|
|
|
@ -29,7 +29,7 @@ class MxContent {
|
|||
final String _mxc;
|
||||
|
||||
/// Insert a mxc:// uri here.
|
||||
MxContent(String mxcUrl) : this._mxc = mxcUrl ?? "";
|
||||
MxContent(String mxcUrl) : _mxc = mxcUrl ?? '';
|
||||
|
||||
/// Returns the mxc uri.
|
||||
String get mxc => _mxc;
|
||||
|
@ -37,20 +37,20 @@ class MxContent {
|
|||
/// Returns a download Link to this content.
|
||||
String getDownloadLink(Client matrix) => matrix.homeserver != null
|
||||
? "${matrix.homeserver}/_matrix/media/r0/download/${_mxc.replaceFirst("mxc://", "")}"
|
||||
: "";
|
||||
: '';
|
||||
|
||||
/// Returns a scaled thumbnail link to this content with the given [width] and
|
||||
/// [height]. [method] can be [ThumbnailMethod.crop] or
|
||||
/// [ThumbnailMethod.scale] and defaults to [ThumbnailMethod.scale].
|
||||
String getThumbnail(Client matrix,
|
||||
{num width, num height, ThumbnailMethod method}) {
|
||||
String methodStr = "crop";
|
||||
if (method == ThumbnailMethod.scale) methodStr = "scale";
|
||||
var methodStr = 'crop';
|
||||
if (method == ThumbnailMethod.scale) methodStr = 'scale';
|
||||
width = width.round();
|
||||
height = height.round();
|
||||
return matrix.homeserver != null
|
||||
? "${matrix.homeserver}/_matrix/media/r0/thumbnail/${_mxc.replaceFirst("mxc://", "")}?width=$width&height=$height&method=$methodStr"
|
||||
: "";
|
||||
: '';
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -18,11 +18,12 @@ class OpenIdCredentials {
|
|||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
final Map<String, dynamic> data = Map<String, dynamic>();
|
||||
data['access_token'] = this.accessToken;
|
||||
data['token_type'] = this.tokenType;
|
||||
data['matrix_server_name'] = this.matrixServerName;
|
||||
data['expires_in'] = this.expiresIn;
|
||||
var map = <String, dynamic>{};
|
||||
final data = map;
|
||||
data['access_token'] = accessToken;
|
||||
data['token_type'] = tokenType;
|
||||
data['matrix_server_name'] = matrixServerName;
|
||||
data['expires_in'] = expiresIn;
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -16,7 +16,7 @@ class Profile {
|
|||
displayname = json['displayname'],
|
||||
content = json;
|
||||
|
||||
@override
|
||||
bool operator ==(dynamic other) =>
|
||||
this.avatarUrl.mxc == other.avatarUrl.mxc &&
|
||||
this.displayname == other.displayname;
|
||||
avatarUrl.mxc == other.avatarUrl.mxc && displayname == other.displayname;
|
||||
}
|
||||
|
|
|
@ -21,7 +21,7 @@ class PublicRoomsResponse {
|
|||
client = client,
|
||||
totalRoomCountEstimate = json['total_room_count_estimate'] {
|
||||
if (json['chunk'] != null) {
|
||||
publicRooms = List<PublicRoomEntry>();
|
||||
publicRooms = <PublicRoomEntry>[];
|
||||
json['chunk'].forEach((v) {
|
||||
publicRooms.add(PublicRoomEntry.fromJson(v, client));
|
||||
});
|
||||
|
|
|
@ -3,7 +3,7 @@ class PushRules {
|
|||
final GlobalPushRules global;
|
||||
|
||||
PushRules.fromJson(Map<String, dynamic> json)
|
||||
: this.global = GlobalPushRules.fromJson(json["global"]);
|
||||
: global = GlobalPushRules.fromJson(json['global']);
|
||||
}
|
||||
|
||||
/// The global ruleset.
|
||||
|
@ -15,20 +15,20 @@ class GlobalPushRules {
|
|||
final List<PushRule> underride;
|
||||
|
||||
GlobalPushRules.fromJson(Map<String, dynamic> json)
|
||||
: this.content = json.containsKey("content")
|
||||
? PushRule.fromJsonList(json["content"])
|
||||
: content = json.containsKey('content')
|
||||
? PushRule.fromJsonList(json['content'])
|
||||
: null,
|
||||
this.override = json.containsKey("override")
|
||||
? PushRule.fromJsonList(json["content"])
|
||||
override = json.containsKey('override')
|
||||
? PushRule.fromJsonList(json['content'])
|
||||
: null,
|
||||
this.room = json.containsKey("room")
|
||||
? PushRule.fromJsonList(json["room"])
|
||||
room = json.containsKey('room')
|
||||
? PushRule.fromJsonList(json['room'])
|
||||
: null,
|
||||
this.sender = json.containsKey("sender")
|
||||
? PushRule.fromJsonList(json["sender"])
|
||||
sender = json.containsKey('sender')
|
||||
? PushRule.fromJsonList(json['sender'])
|
||||
: null,
|
||||
this.underride = json.containsKey("underride")
|
||||
? PushRule.fromJsonList(json["underride"])
|
||||
underride = json.containsKey('underride')
|
||||
? PushRule.fromJsonList(json['underride'])
|
||||
: null;
|
||||
}
|
||||
|
||||
|
@ -42,7 +42,7 @@ class PushRule {
|
|||
final String pattern;
|
||||
|
||||
static List<PushRule> fromJsonList(List<dynamic> list) {
|
||||
List<PushRule> objList = [];
|
||||
var objList = <PushRule>[];
|
||||
list.forEach((json) {
|
||||
objList.add(PushRule.fromJson(json));
|
||||
});
|
||||
|
@ -50,14 +50,14 @@ class PushRule {
|
|||
}
|
||||
|
||||
PushRule.fromJson(Map<String, dynamic> json)
|
||||
: this.actions = json["actions"],
|
||||
this.isDefault = json["default"],
|
||||
this.enabled = json["enabled"],
|
||||
this.ruleId = json["rule_id"],
|
||||
this.conditions = json.containsKey("conditions")
|
||||
? PushRuleConditions.fromJsonList(json["conditions"])
|
||||
: actions = json['actions'],
|
||||
isDefault = json['default'],
|
||||
enabled = json['enabled'],
|
||||
ruleId = json['rule_id'],
|
||||
conditions = json.containsKey('conditions')
|
||||
? PushRuleConditions.fromJsonList(json['conditions'])
|
||||
: null,
|
||||
this.pattern = json["pattern"];
|
||||
pattern = json['pattern'];
|
||||
}
|
||||
|
||||
/// Conditions when this pushrule should be active.
|
||||
|
@ -68,7 +68,7 @@ class PushRuleConditions {
|
|||
final String is_;
|
||||
|
||||
static List<PushRuleConditions> fromJsonList(List<dynamic> list) {
|
||||
List<PushRuleConditions> objList = [];
|
||||
var objList = <PushRuleConditions>[];
|
||||
list.forEach((json) {
|
||||
objList.add(PushRuleConditions.fromJson(json));
|
||||
});
|
||||
|
@ -76,8 +76,8 @@ class PushRuleConditions {
|
|||
}
|
||||
|
||||
PushRuleConditions.fromJson(Map<String, dynamic> json)
|
||||
: this.kind = json["kind"],
|
||||
this.key = json["key"],
|
||||
this.pattern = json["pattern"],
|
||||
this.is_ = json["is"];
|
||||
: kind = json['kind'],
|
||||
key = json['key'],
|
||||
pattern = json['pattern'],
|
||||
is_ = json['is'];
|
||||
}
|
||||
|
|
|
@ -1,35 +1,33 @@
|
|||
import 'package:famedlysdk/famedlysdk.dart';
|
||||
import 'package:famedlysdk/src/utils/session_key.dart';
|
||||
|
||||
class RoomKeyRequest extends ToDeviceEvent {
|
||||
Client client;
|
||||
RoomKeyRequest.fromToDeviceEvent(ToDeviceEvent toDeviceEvent, Client client) {
|
||||
this.client = client;
|
||||
this.sender = toDeviceEvent.sender;
|
||||
this.content = toDeviceEvent.content;
|
||||
this.type = toDeviceEvent.type;
|
||||
sender = toDeviceEvent.sender;
|
||||
content = toDeviceEvent.content;
|
||||
type = toDeviceEvent.type;
|
||||
}
|
||||
|
||||
Room get room => client.getRoomById(this.content["body"]["room_id"]);
|
||||
Room get room => client.getRoomById(content['body']['room_id']);
|
||||
|
||||
DeviceKeys get requestingDevice =>
|
||||
client.userDeviceKeys[sender].deviceKeys[content["requesting_device_id"]];
|
||||
client.userDeviceKeys[sender].deviceKeys[content['requesting_device_id']];
|
||||
|
||||
Future<void> forwardKey() async {
|
||||
Room room = this.room;
|
||||
final SessionKey session =
|
||||
room.sessionKeys[this.content["body"]["session_id"]];
|
||||
List<dynamic> forwardedKeys = [client.identityKey];
|
||||
var room = this.room;
|
||||
final session = room.sessionKeys[content['body']['session_id']];
|
||||
var forwardedKeys = <dynamic>[client.identityKey];
|
||||
for (final key in session.forwardingCurve25519KeyChain) {
|
||||
forwardedKeys.add(key);
|
||||
}
|
||||
await requestingDevice.setVerified(true, client);
|
||||
Map<String, dynamic> message = session.content;
|
||||
message["forwarding_curve25519_key_chain"] = forwardedKeys;
|
||||
message["session_key"] = session.inboundGroupSession.export_session(0);
|
||||
var message = session.content;
|
||||
message['forwarding_curve25519_key_chain'] = forwardedKeys;
|
||||
message['session_key'] = session.inboundGroupSession.export_session(0);
|
||||
await client.sendToDevice(
|
||||
[requestingDevice],
|
||||
"m.forwarded_room_key",
|
||||
'm.forwarded_room_key',
|
||||
message,
|
||||
);
|
||||
}
|
||||
|
|
|
@ -8,35 +8,36 @@ class SessionKey {
|
|||
InboundGroupSession inboundGroupSession;
|
||||
final String key;
|
||||
List<dynamic> get forwardingCurve25519KeyChain =>
|
||||
content["forwarding_curve25519_key_chain"] ?? [];
|
||||
content['forwarding_curve25519_key_chain'] ?? [];
|
||||
String get senderClaimedEd25519Key =>
|
||||
content["sender_claimed_ed25519_key"] ?? "";
|
||||
content['sender_claimed_ed25519_key'] ?? '';
|
||||
|
||||
SessionKey({this.content, this.inboundGroupSession, this.key, this.indexes});
|
||||
|
||||
SessionKey.fromJson(Map<String, dynamic> json, String key) : this.key = key {
|
||||
SessionKey.fromJson(Map<String, dynamic> json, String key) : key = key {
|
||||
content = json['content'] != null
|
||||
? Map<String, dynamic>.from(json['content'])
|
||||
: null;
|
||||
indexes = json['indexes'] != null
|
||||
? Map<String, int>.from(json['indexes'])
|
||||
: Map<String, int>();
|
||||
InboundGroupSession newInboundGroupSession = InboundGroupSession();
|
||||
: <String, int>{};
|
||||
var newInboundGroupSession = InboundGroupSession();
|
||||
newInboundGroupSession.unpickle(key, json['inboundGroupSession']);
|
||||
inboundGroupSession = newInboundGroupSession;
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
final Map<String, dynamic> data = Map<String, dynamic>();
|
||||
if (this.content != null) {
|
||||
data['content'] = this.content;
|
||||
final data = <String, dynamic>{};
|
||||
if (content != null) {
|
||||
data['content'] = content;
|
||||
}
|
||||
if (this.indexes != null) {
|
||||
data['indexes'] = this.indexes;
|
||||
if (indexes != null) {
|
||||
data['indexes'] = indexes;
|
||||
}
|
||||
data['inboundGroupSession'] = this.inboundGroupSession.pickle(this.key);
|
||||
data['inboundGroupSession'] = inboundGroupSession.pickle(key);
|
||||
return data;
|
||||
}
|
||||
|
||||
String toString() => json.encode(this.toJson());
|
||||
@override
|
||||
String toString() => json.encode(toJson());
|
||||
}
|
||||
|
|
|
@ -10,13 +10,13 @@ class StatesMap {
|
|||
dynamic operator [](String key) {
|
||||
//print("[Warning] This method will be depracated in the future!");
|
||||
if (key == null) return null;
|
||||
if (key.startsWith("@") && key.contains(":")) {
|
||||
if (!states.containsKey("m.room.member")) states["m.room.member"] = {};
|
||||
return states["m.room.member"][key];
|
||||
if (key.startsWith('@') && key.contains(':')) {
|
||||
if (!states.containsKey('m.room.member')) states['m.room.member'] = {};
|
||||
return states['m.room.member'][key];
|
||||
}
|
||||
if (!states.containsKey(key)) states[key] = {};
|
||||
if (states[key][""] is Event) {
|
||||
return states[key][""];
|
||||
if (states[key][''] is Event) {
|
||||
return states[key][''];
|
||||
} else if (states[key].isEmpty) {
|
||||
return null;
|
||||
} else {
|
||||
|
@ -26,12 +26,12 @@ class StatesMap {
|
|||
|
||||
void operator []=(String key, Event val) {
|
||||
//print("[Warning] This method will be depracated in the future!");
|
||||
if (key.startsWith("@") && key.contains(":")) {
|
||||
if (!states.containsKey("m.room.member")) states["m.room.member"] = {};
|
||||
states["m.room.member"][key] = val;
|
||||
if (key.startsWith('@') && key.contains(':')) {
|
||||
if (!states.containsKey('m.room.member')) states['m.room.member'] = {};
|
||||
states['m.room.member'][key] = val;
|
||||
}
|
||||
if (!states.containsKey(key)) states[key] = {};
|
||||
states[key][val.stateKey ?? ""] = val;
|
||||
states[key][val.stateKey ?? ''] = val;
|
||||
}
|
||||
|
||||
bool containsKey(String key) => states.containsKey(key);
|
||||
|
|
|
@ -14,11 +14,12 @@ class ToDeviceEvent {
|
|||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
final Map<String, dynamic> data = Map<String, dynamic>();
|
||||
data['sender'] = this.sender;
|
||||
data['type'] = this.type;
|
||||
if (this.content != null) {
|
||||
data['content'] = this.content;
|
||||
var map = <String, dynamic>{};
|
||||
final data = map;
|
||||
data['sender'] = sender;
|
||||
data['type'] = type;
|
||||
if (content != null) {
|
||||
data['content'] = content;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
|
|
@ -20,8 +20,8 @@ class UserDevice {
|
|||
Future<void> updateMetaData(String newName) async {
|
||||
await _client.jsonRequest(
|
||||
type: HTTPType.PUT,
|
||||
action: "/client/r0/devices/$deviceId",
|
||||
data: {"display_name": newName},
|
||||
action: '/client/r0/devices/$deviceId',
|
||||
data: {'display_name': newName},
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
@ -30,8 +30,8 @@ class UserDevice {
|
|||
Future<void> deleteDevice(Map<String, dynamic> auth) async {
|
||||
await _client.jsonRequest(
|
||||
type: HTTPType.DELETE,
|
||||
action: "/client/r0/devices/$deviceId",
|
||||
data: auth != null ? {"auth": auth} : null,
|
||||
action: '/client/r0/devices/$deviceId',
|
||||
data: auth != null ? {'auth': auth} : null,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
|
|
@ -196,7 +196,7 @@ packages:
|
|||
name: http
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "0.12.0+2"
|
||||
version: "0.12.0+4"
|
||||
http_multi_server:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
@ -333,7 +333,7 @@ packages:
|
|||
name: pedantic
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "1.8.0+1"
|
||||
version: "1.9.0"
|
||||
pointycastle:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
|
|
@ -25,4 +25,4 @@ dependencies:
|
|||
dev_dependencies:
|
||||
test: ^1.0.0
|
||||
build_runner: ^1.5.2
|
||||
pedantic: ^1.5.0 # DO NOT UPDATE AS THIS WOULD CAUSE FLUTTER TO FAIL
|
||||
pedantic: ^1.9.0 # DO NOT UPDATE AS THIS WOULD CAUSE FLUTTER TO FAIL
|
||||
|
|
|
@ -26,26 +26,26 @@ import 'package:test/test.dart';
|
|||
|
||||
void main() {
|
||||
/// All Tests related to the ChatTime
|
||||
group("Canonical Json", () {
|
||||
Map<String, Map<String, dynamic>> textMap = {
|
||||
group('Canonical Json', () {
|
||||
var textMap = <String, Map<String, dynamic>>{
|
||||
'{}': {},
|
||||
'{"one":1,"two":"Two"}': {"one": 1, "two": "Two"},
|
||||
'{"a":"1","b":"2"}': {"b": "2", "a": "1"},
|
||||
'{"one":1,"two":"Two"}': {'one': 1, 'two': 'Two'},
|
||||
'{"a":"1","b":"2"}': {'b': '2', 'a': '1'},
|
||||
'{"auth":{"mxid":"@john.doe:example.com","profile":{"display_name":"John Doe","three_pids":[{"address":"john.doe@example.org","medium":"email"},{"address":"123456789","medium":"msisdn"}]},"success":true}}':
|
||||
{
|
||||
"auth": {
|
||||
"success": true,
|
||||
"mxid": "@john.doe:example.com",
|
||||
"profile": {
|
||||
"display_name": "John Doe",
|
||||
"three_pids": [
|
||||
{"medium": "email", "address": "john.doe@example.org"},
|
||||
{"medium": "msisdn", "address": "123456789"}
|
||||
'auth': {
|
||||
'success': true,
|
||||
'mxid': '@john.doe:example.com',
|
||||
'profile': {
|
||||
'display_name': 'John Doe',
|
||||
'three_pids': [
|
||||
{'medium': 'email', 'address': 'john.doe@example.org'},
|
||||
{'medium': 'msisdn', 'address': '123456789'}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
'{"a":null}': {"a": null},
|
||||
'{"a":null}': {'a': null},
|
||||
};
|
||||
for (final entry in textMap.entries) {
|
||||
test(entry.key, () async {
|
||||
|
|
|
@ -29,15 +29,12 @@ import 'package:famedlysdk/famedlysdk.dart';
|
|||
import 'package:famedlysdk/src/account_data.dart';
|
||||
import 'package:famedlysdk/src/client.dart';
|
||||
import 'package:famedlysdk/src/presence.dart';
|
||||
import 'package:famedlysdk/src/room.dart';
|
||||
import 'package:famedlysdk/src/user.dart';
|
||||
import 'package:famedlysdk/src/sync/event_update.dart';
|
||||
import 'package:famedlysdk/src/sync/room_update.dart';
|
||||
import 'package:famedlysdk/src/sync/user_update.dart';
|
||||
import 'package:famedlysdk/src/utils/matrix_exception.dart';
|
||||
import 'package:famedlysdk/src/utils/matrix_file.dart';
|
||||
import 'package:famedlysdk/src/utils/profile.dart';
|
||||
import 'package:famedlysdk/src/utils/user_device.dart';
|
||||
import 'package:olm/olm.dart' as olm;
|
||||
import 'package:test/test.dart';
|
||||
|
||||
|
@ -52,35 +49,35 @@ void main() {
|
|||
Future<List<UserUpdate>> userUpdateListFuture;
|
||||
Future<List<ToDeviceEvent>> toDeviceUpdateListFuture;
|
||||
|
||||
const String pickledOlmAccount =
|
||||
"N2v1MkIFGcl0mQpo2OCwSopxPQJ0wnl7oe7PKiT4141AijfdTIhRu+ceXzXKy3Kr00nLqXtRv7kid6hU4a+V0rfJWLL0Y51+3Rp/ORDVnQy+SSeo6Fn4FHcXrxifJEJ0djla5u98fBcJ8BSkhIDmtXRPi5/oJAvpiYn+8zMjFHobOeZUAxYR0VfQ9JzSYBsSovoQ7uFkNks1M4EDUvHtuweStA+EKZvvHZO0SnwRp0Hw7sv8UMYvXw";
|
||||
const String identityKey = "7rvl3jORJkBiK4XX1e5TnGnqz068XfYJ0W++Ml63rgk";
|
||||
const String fingerprintKey = "gjL//fyaFHADt9KBADGag8g7F8Up78B/K1zXeiEPLJo";
|
||||
const pickledOlmAccount =
|
||||
'N2v1MkIFGcl0mQpo2OCwSopxPQJ0wnl7oe7PKiT4141AijfdTIhRu+ceXzXKy3Kr00nLqXtRv7kid6hU4a+V0rfJWLL0Y51+3Rp/ORDVnQy+SSeo6Fn4FHcXrxifJEJ0djla5u98fBcJ8BSkhIDmtXRPi5/oJAvpiYn+8zMjFHobOeZUAxYR0VfQ9JzSYBsSovoQ7uFkNks1M4EDUvHtuweStA+EKZvvHZO0SnwRp0Hw7sv8UMYvXw';
|
||||
const identityKey = '7rvl3jORJkBiK4XX1e5TnGnqz068XfYJ0W++Ml63rgk';
|
||||
const fingerprintKey = 'gjL//fyaFHADt9KBADGag8g7F8Up78B/K1zXeiEPLJo';
|
||||
|
||||
/// All Tests related to the Login
|
||||
group("FluffyMatrix", () {
|
||||
group('FluffyMatrix', () {
|
||||
/// Check if all Elements get created
|
||||
|
||||
matrix = Client("testclient", debug: true);
|
||||
matrix = Client('testclient', debug: true);
|
||||
matrix.httpClient = FakeMatrixApi();
|
||||
|
||||
roomUpdateListFuture = matrix.onRoomUpdate.stream.toList();
|
||||
eventUpdateListFuture = matrix.onEvent.stream.toList();
|
||||
userUpdateListFuture = matrix.onUserEvent.stream.toList();
|
||||
toDeviceUpdateListFuture = matrix.onToDeviceEvent.stream.toList();
|
||||
bool olmEnabled = true;
|
||||
var olmEnabled = true;
|
||||
try {
|
||||
olm.init();
|
||||
olm.Account();
|
||||
} catch (_) {
|
||||
olmEnabled = false;
|
||||
print("[LibOlm] Failed to load LibOlm: " + _.toString());
|
||||
print('[LibOlm] Failed to load LibOlm: ' + _.toString());
|
||||
}
|
||||
print("[LibOlm] Enabled: $olmEnabled");
|
||||
print('[LibOlm] Enabled: $olmEnabled');
|
||||
|
||||
test('Login', () async {
|
||||
int presenceCounter = 0;
|
||||
int accountDataCounter = 0;
|
||||
var presenceCounter = 0;
|
||||
var accountDataCounter = 0;
|
||||
matrix.onPresence.stream.listen((Presence data) {
|
||||
presenceCounter++;
|
||||
});
|
||||
|
@ -92,46 +89,45 @@ void main() {
|
|||
expect(matrix.matrixVersions, null);
|
||||
|
||||
try {
|
||||
await matrix.checkServer("https://fakeserver.wrongaddress");
|
||||
await matrix.checkServer('https://fakeserver.wrongaddress');
|
||||
} on FormatException catch (exception) {
|
||||
expect(exception != null, true);
|
||||
}
|
||||
await matrix.checkServer("https://fakeserver.notexisting");
|
||||
expect(matrix.homeserver, "https://fakeserver.notexisting");
|
||||
await matrix.checkServer('https://fakeserver.notexisting');
|
||||
expect(matrix.homeserver, 'https://fakeserver.notexisting');
|
||||
expect(matrix.matrixVersions,
|
||||
["r0.0.1", "r0.1.0", "r0.2.0", "r0.3.0", "r0.4.0", "r0.5.0"]);
|
||||
['r0.0.1', 'r0.1.0', 'r0.2.0', 'r0.3.0', 'r0.4.0', 'r0.5.0']);
|
||||
|
||||
final Map<String, dynamic> resp = await matrix
|
||||
.jsonRequest(type: HTTPType.POST, action: "/client/r0/login", data: {
|
||||
"type": "m.login.password",
|
||||
"user": "test",
|
||||
"password": "1234",
|
||||
"initial_device_display_name": "Fluffy Matrix Client"
|
||||
final resp = await matrix
|
||||
.jsonRequest(type: HTTPType.POST, action: '/client/r0/login', data: {
|
||||
'type': 'm.login.password',
|
||||
'user': 'test',
|
||||
'password': '1234',
|
||||
'initial_device_display_name': 'Fluffy Matrix Client'
|
||||
});
|
||||
|
||||
final bool available = await matrix.usernameAvailable("testuser");
|
||||
final available = await matrix.usernameAvailable('testuser');
|
||||
expect(available, true);
|
||||
|
||||
Map registerResponse = await matrix.register(username: "testuser");
|
||||
expect(registerResponse["user_id"], "@testuser:example.com");
|
||||
Map registerResponse = await matrix.register(username: 'testuser');
|
||||
expect(registerResponse['user_id'], '@testuser:example.com');
|
||||
registerResponse =
|
||||
await matrix.register(username: "testuser", kind: "user");
|
||||
expect(registerResponse["user_id"], "@testuser:example.com");
|
||||
await matrix.register(username: 'testuser', kind: 'user');
|
||||
expect(registerResponse['user_id'], '@testuser:example.com');
|
||||
registerResponse =
|
||||
await matrix.register(username: "testuser", kind: "guest");
|
||||
expect(registerResponse["user_id"], "@testuser:example.com");
|
||||
await matrix.register(username: 'testuser', kind: 'guest');
|
||||
expect(registerResponse['user_id'], '@testuser:example.com');
|
||||
|
||||
Future<LoginState> loginStateFuture =
|
||||
matrix.onLoginStateChanged.stream.first;
|
||||
Future<bool> firstSyncFuture = matrix.onFirstSync.stream.first;
|
||||
Future<dynamic> syncFuture = matrix.onSync.stream.first;
|
||||
var loginStateFuture = matrix.onLoginStateChanged.stream.first;
|
||||
var firstSyncFuture = matrix.onFirstSync.stream.first;
|
||||
var syncFuture = matrix.onSync.stream.first;
|
||||
|
||||
matrix.connect(
|
||||
newToken: resp["access_token"],
|
||||
newUserID: resp["user_id"],
|
||||
newToken: resp['access_token'],
|
||||
newUserID: resp['user_id'],
|
||||
newHomeserver: matrix.homeserver,
|
||||
newDeviceName: "Text Matrix Client",
|
||||
newDeviceID: resp["device_id"],
|
||||
newDeviceName: 'Text Matrix Client',
|
||||
newDeviceID: resp['device_id'],
|
||||
newMatrixVersions: matrix.matrixVersions,
|
||||
newLazyLoadMembers: matrix.lazyLoadMembers,
|
||||
newOlmAccount: pickledOlmAccount,
|
||||
|
@ -139,13 +135,13 @@ void main() {
|
|||
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
|
||||
expect(matrix.accessToken == resp["access_token"], true);
|
||||
expect(matrix.deviceName == "Text Matrix Client", true);
|
||||
expect(matrix.deviceID == resp["device_id"], true);
|
||||
expect(matrix.userID == resp["user_id"], true);
|
||||
expect(matrix.accessToken == resp['access_token'], true);
|
||||
expect(matrix.deviceName == 'Text Matrix Client', true);
|
||||
expect(matrix.deviceID == resp['device_id'], true);
|
||||
expect(matrix.userID == resp['user_id'], true);
|
||||
|
||||
LoginState loginState = await loginStateFuture;
|
||||
bool firstSync = await firstSyncFuture;
|
||||
var loginState = await loginStateFuture;
|
||||
var firstSync = await firstSyncFuture;
|
||||
dynamic sync = await syncFuture;
|
||||
|
||||
expect(loginState, LoginState.logged);
|
||||
|
@ -156,91 +152,91 @@ void main() {
|
|||
expect(matrix.identityKey, identityKey);
|
||||
expect(matrix.fingerprintKey, fingerprintKey);
|
||||
}
|
||||
expect(sync["next_batch"] == matrix.prevBatch, true);
|
||||
expect(sync['next_batch'] == matrix.prevBatch, true);
|
||||
|
||||
expect(matrix.accountData.length, 3);
|
||||
expect(matrix.getDirectChatFromUserId("@bob:example.com"),
|
||||
"!726s6s6q:example.com");
|
||||
expect(matrix.rooms[1].directChatMatrixID, "@bob:example.com");
|
||||
expect(matrix.directChats, matrix.accountData["m.direct"].content);
|
||||
expect(matrix.getDirectChatFromUserId('@bob:example.com'),
|
||||
'!726s6s6q:example.com');
|
||||
expect(matrix.rooms[1].directChatMatrixID, '@bob:example.com');
|
||||
expect(matrix.directChats, matrix.accountData['m.direct'].content);
|
||||
expect(matrix.presences.length, 1);
|
||||
expect(matrix.rooms[1].ephemerals.length, 2);
|
||||
expect(matrix.rooms[1].sessionKeys.length, 1);
|
||||
expect(
|
||||
matrix
|
||||
.rooms[1]
|
||||
.sessionKeys["ciM/JWTPrmiWPPZNkRLDPQYf9AW/I46bxyLSr+Bx5oU"]
|
||||
.content["session_key"],
|
||||
"AgAAAAAQcQ6XrFJk6Prm8FikZDqfry/NbDz8Xw7T6e+/9Yf/q3YHIPEQlzv7IZMNcYb51ifkRzFejVvtphS7wwG2FaXIp4XS2obla14iKISR0X74ugB2vyb1AydIHE/zbBQ1ic5s3kgjMFlWpu/S3FQCnCrv+DPFGEt3ERGWxIl3Bl5X53IjPyVkz65oljz2TZESwz0GH/QFvyOOm8ci0q/gceaF3S7Dmafg3dwTKYwcA5xkcc+BLyrLRzB6Hn+oMAqSNSscnm4mTeT5zYibIhrzqyUTMWr32spFtI9dNR/RFSzfCw");
|
||||
.sessionKeys['ciM/JWTPrmiWPPZNkRLDPQYf9AW/I46bxyLSr+Bx5oU']
|
||||
.content['session_key'],
|
||||
'AgAAAAAQcQ6XrFJk6Prm8FikZDqfry/NbDz8Xw7T6e+/9Yf/q3YHIPEQlzv7IZMNcYb51ifkRzFejVvtphS7wwG2FaXIp4XS2obla14iKISR0X74ugB2vyb1AydIHE/zbBQ1ic5s3kgjMFlWpu/S3FQCnCrv+DPFGEt3ERGWxIl3Bl5X53IjPyVkz65oljz2TZESwz0GH/QFvyOOm8ci0q/gceaF3S7Dmafg3dwTKYwcA5xkcc+BLyrLRzB6Hn+oMAqSNSscnm4mTeT5zYibIhrzqyUTMWr32spFtI9dNR/RFSzfCw');
|
||||
if (olmEnabled) {
|
||||
expect(
|
||||
matrix
|
||||
.rooms[1]
|
||||
.sessionKeys["ciM/JWTPrmiWPPZNkRLDPQYf9AW/I46bxyLSr+Bx5oU"]
|
||||
.sessionKeys['ciM/JWTPrmiWPPZNkRLDPQYf9AW/I46bxyLSr+Bx5oU']
|
||||
.inboundGroupSession !=
|
||||
null,
|
||||
true);
|
||||
}
|
||||
expect(matrix.rooms[1].typingUsers.length, 1);
|
||||
expect(matrix.rooms[1].typingUsers[0].id, "@alice:example.com");
|
||||
expect(matrix.rooms[1].typingUsers[0].id, '@alice:example.com');
|
||||
expect(matrix.rooms[1].roomAccountData.length, 3);
|
||||
expect(matrix.rooms[1].encrypted, true);
|
||||
expect(matrix.rooms[1].encryptionAlgorithm,
|
||||
Client.supportedGroupEncryptionAlgorithms.first);
|
||||
expect(
|
||||
matrix.rooms[1].roomAccountData["m.receipt"]
|
||||
.content["@alice:example.com"]["ts"],
|
||||
matrix.rooms[1].roomAccountData['m.receipt']
|
||||
.content['@alice:example.com']['ts'],
|
||||
1436451550453);
|
||||
expect(
|
||||
matrix.rooms[1].roomAccountData["m.receipt"]
|
||||
.content["@alice:example.com"]["event_id"],
|
||||
"7365636s6r6432:example.com");
|
||||
matrix.rooms[1].roomAccountData['m.receipt']
|
||||
.content['@alice:example.com']['event_id'],
|
||||
'7365636s6r6432:example.com');
|
||||
expect(matrix.rooms.length, 2);
|
||||
expect(matrix.rooms[1].canonicalAlias,
|
||||
"#famedlyContactDiscovery:${matrix.userID.split(":")[1]}");
|
||||
final List<User> contacts = await matrix.loadFamedlyContacts();
|
||||
final contacts = await matrix.loadFamedlyContacts();
|
||||
expect(contacts.length, 1);
|
||||
expect(contacts[0].senderId, "@alice:example.com");
|
||||
expect(contacts[0].senderId, '@alice:example.com');
|
||||
expect(
|
||||
matrix.presences["@alice:example.com"].presence, PresenceType.online);
|
||||
matrix.presences['@alice:example.com'].presence, PresenceType.online);
|
||||
expect(presenceCounter, 1);
|
||||
expect(accountDataCounter, 3);
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
expect(matrix.userDeviceKeys.length, 2);
|
||||
expect(matrix.userDeviceKeys["@alice:example.com"].outdated, false);
|
||||
expect(matrix.userDeviceKeys["@alice:example.com"].deviceKeys.length, 1);
|
||||
expect(matrix.userDeviceKeys['@alice:example.com'].outdated, false);
|
||||
expect(matrix.userDeviceKeys['@alice:example.com'].deviceKeys.length, 1);
|
||||
expect(
|
||||
matrix.userDeviceKeys["@alice:example.com"].deviceKeys["JLAFKJWSCS"]
|
||||
matrix.userDeviceKeys['@alice:example.com'].deviceKeys['JLAFKJWSCS']
|
||||
.verified,
|
||||
false);
|
||||
|
||||
matrix.handleSync({
|
||||
"device_lists": {
|
||||
"changed": [
|
||||
"@alice:example.com",
|
||||
'device_lists': {
|
||||
'changed': [
|
||||
'@alice:example.com',
|
||||
],
|
||||
"left": [
|
||||
"@bob:example.com",
|
||||
'left': [
|
||||
'@bob:example.com',
|
||||
],
|
||||
}
|
||||
});
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
expect(matrix.userDeviceKeys.length, 2);
|
||||
expect(matrix.userDeviceKeys["@alice:example.com"].outdated, true);
|
||||
expect(matrix.userDeviceKeys['@alice:example.com'].outdated, true);
|
||||
|
||||
matrix.handleSync({
|
||||
"rooms": {
|
||||
"join": {
|
||||
"!726s6s6q:example.com": {
|
||||
"state": {
|
||||
"events": [
|
||||
'rooms': {
|
||||
'join': {
|
||||
'!726s6s6q:example.com': {
|
||||
'state': {
|
||||
'events': [
|
||||
{
|
||||
"sender": "@alice:example.com",
|
||||
"type": "m.room.canonical_alias",
|
||||
"content": {"alias": ""},
|
||||
"state_key": "",
|
||||
"origin_server_ts": 1417731086799,
|
||||
"event_id": "66697273743033:example.com"
|
||||
'sender': '@alice:example.com',
|
||||
'type': 'm.room.canonical_alias',
|
||||
'content': {'alias': ''},
|
||||
'state_key': '',
|
||||
'origin_server_ts': 1417731086799,
|
||||
'event_id': '66697273743033:example.com'
|
||||
}
|
||||
]
|
||||
}
|
||||
|
@ -254,17 +250,17 @@ void main() {
|
|||
matrix.getRoomByAlias(
|
||||
"#famedlyContactDiscovery:${matrix.userID.split(":")[1]}"),
|
||||
null);
|
||||
final List<User> altContacts = await matrix.loadFamedlyContacts();
|
||||
final altContacts = await matrix.loadFamedlyContacts();
|
||||
altContacts.forEach((u) => print(u.id));
|
||||
expect(altContacts.length, 2);
|
||||
expect(altContacts[0].senderId, "@alice:example.com");
|
||||
expect(altContacts[0].senderId, '@alice:example.com');
|
||||
});
|
||||
|
||||
test('Try to get ErrorResponse', () async {
|
||||
MatrixException expectedException;
|
||||
try {
|
||||
await matrix.jsonRequest(
|
||||
type: HTTPType.PUT, action: "/non/existing/path");
|
||||
type: HTTPType.PUT, action: '/non/existing/path');
|
||||
} on MatrixException catch (exception) {
|
||||
expectedException = exception;
|
||||
}
|
||||
|
@ -273,10 +269,9 @@ void main() {
|
|||
|
||||
test('Logout', () async {
|
||||
await matrix.jsonRequest(
|
||||
type: HTTPType.POST, action: "/client/r0/logout");
|
||||
type: HTTPType.POST, action: '/client/r0/logout');
|
||||
|
||||
Future<LoginState> loginStateFuture =
|
||||
matrix.onLoginStateChanged.stream.first;
|
||||
var loginStateFuture = matrix.onLoginStateChanged.stream.first;
|
||||
|
||||
matrix.clear();
|
||||
|
||||
|
@ -289,27 +284,27 @@ void main() {
|
|||
expect(matrix.lazyLoadMembers == null, true);
|
||||
expect(matrix.prevBatch == null, true);
|
||||
|
||||
LoginState loginState = await loginStateFuture;
|
||||
var loginState = await loginStateFuture;
|
||||
expect(loginState, LoginState.loggedOut);
|
||||
});
|
||||
|
||||
test('Room Update Test', () async {
|
||||
await matrix.onRoomUpdate.close();
|
||||
|
||||
List<RoomUpdate> roomUpdateList = await roomUpdateListFuture;
|
||||
var roomUpdateList = await roomUpdateListFuture;
|
||||
|
||||
expect(roomUpdateList.length, 3);
|
||||
|
||||
expect(roomUpdateList[0].id == "!726s6s6q:example.com", true);
|
||||
expect(roomUpdateList[0].id == '!726s6s6q:example.com', true);
|
||||
expect(roomUpdateList[0].membership == Membership.join, true);
|
||||
expect(roomUpdateList[0].prev_batch == "t34-23535_0_0", true);
|
||||
expect(roomUpdateList[0].prev_batch == 't34-23535_0_0', true);
|
||||
expect(roomUpdateList[0].limitedTimeline == true, true);
|
||||
expect(roomUpdateList[0].notification_count == 2, true);
|
||||
expect(roomUpdateList[0].highlight_count == 2, true);
|
||||
|
||||
expect(roomUpdateList[1].id == "!696r7674:example.com", true);
|
||||
expect(roomUpdateList[1].id == '!696r7674:example.com', true);
|
||||
expect(roomUpdateList[1].membership == Membership.invite, true);
|
||||
expect(roomUpdateList[1].prev_batch == "", true);
|
||||
expect(roomUpdateList[1].prev_batch == '', true);
|
||||
expect(roomUpdateList[1].limitedTimeline == false, true);
|
||||
expect(roomUpdateList[1].notification_count == 0, true);
|
||||
expect(roomUpdateList[1].highlight_count == 0, true);
|
||||
|
@ -318,194 +313,193 @@ void main() {
|
|||
test('Event Update Test', () async {
|
||||
await matrix.onEvent.close();
|
||||
|
||||
List<EventUpdate> eventUpdateList = await eventUpdateListFuture;
|
||||
var eventUpdateList = await eventUpdateListFuture;
|
||||
|
||||
expect(eventUpdateList.length, 13);
|
||||
|
||||
expect(eventUpdateList[0].eventType, "m.room.member");
|
||||
expect(eventUpdateList[0].roomID, "!726s6s6q:example.com");
|
||||
expect(eventUpdateList[0].type, "state");
|
||||
expect(eventUpdateList[0].eventType, 'm.room.member');
|
||||
expect(eventUpdateList[0].roomID, '!726s6s6q:example.com');
|
||||
expect(eventUpdateList[0].type, 'state');
|
||||
|
||||
expect(eventUpdateList[1].eventType, "m.room.canonical_alias");
|
||||
expect(eventUpdateList[1].roomID, "!726s6s6q:example.com");
|
||||
expect(eventUpdateList[1].type, "state");
|
||||
expect(eventUpdateList[1].eventType, 'm.room.canonical_alias');
|
||||
expect(eventUpdateList[1].roomID, '!726s6s6q:example.com');
|
||||
expect(eventUpdateList[1].type, 'state');
|
||||
|
||||
expect(eventUpdateList[2].eventType, "m.room.encryption");
|
||||
expect(eventUpdateList[2].roomID, "!726s6s6q:example.com");
|
||||
expect(eventUpdateList[2].type, "state");
|
||||
expect(eventUpdateList[2].eventType, 'm.room.encryption');
|
||||
expect(eventUpdateList[2].roomID, '!726s6s6q:example.com');
|
||||
expect(eventUpdateList[2].type, 'state');
|
||||
|
||||
expect(eventUpdateList[3].eventType, "m.room.member");
|
||||
expect(eventUpdateList[3].roomID, "!726s6s6q:example.com");
|
||||
expect(eventUpdateList[3].type, "timeline");
|
||||
expect(eventUpdateList[3].eventType, 'm.room.member');
|
||||
expect(eventUpdateList[3].roomID, '!726s6s6q:example.com');
|
||||
expect(eventUpdateList[3].type, 'timeline');
|
||||
|
||||
expect(eventUpdateList[4].eventType, "m.room.message");
|
||||
expect(eventUpdateList[4].roomID, "!726s6s6q:example.com");
|
||||
expect(eventUpdateList[4].type, "timeline");
|
||||
expect(eventUpdateList[4].eventType, 'm.room.message');
|
||||
expect(eventUpdateList[4].roomID, '!726s6s6q:example.com');
|
||||
expect(eventUpdateList[4].type, 'timeline');
|
||||
|
||||
expect(eventUpdateList[5].eventType, "m.typing");
|
||||
expect(eventUpdateList[5].roomID, "!726s6s6q:example.com");
|
||||
expect(eventUpdateList[5].type, "ephemeral");
|
||||
expect(eventUpdateList[5].eventType, 'm.typing');
|
||||
expect(eventUpdateList[5].roomID, '!726s6s6q:example.com');
|
||||
expect(eventUpdateList[5].type, 'ephemeral');
|
||||
|
||||
expect(eventUpdateList[6].eventType, "m.receipt");
|
||||
expect(eventUpdateList[6].roomID, "!726s6s6q:example.com");
|
||||
expect(eventUpdateList[6].type, "ephemeral");
|
||||
expect(eventUpdateList[6].eventType, 'm.receipt');
|
||||
expect(eventUpdateList[6].roomID, '!726s6s6q:example.com');
|
||||
expect(eventUpdateList[6].type, 'ephemeral');
|
||||
|
||||
expect(eventUpdateList[7].eventType, "m.receipt");
|
||||
expect(eventUpdateList[7].roomID, "!726s6s6q:example.com");
|
||||
expect(eventUpdateList[7].type, "account_data");
|
||||
expect(eventUpdateList[7].eventType, 'm.receipt');
|
||||
expect(eventUpdateList[7].roomID, '!726s6s6q:example.com');
|
||||
expect(eventUpdateList[7].type, 'account_data');
|
||||
|
||||
expect(eventUpdateList[8].eventType, "m.tag");
|
||||
expect(eventUpdateList[8].roomID, "!726s6s6q:example.com");
|
||||
expect(eventUpdateList[8].type, "account_data");
|
||||
expect(eventUpdateList[8].eventType, 'm.tag');
|
||||
expect(eventUpdateList[8].roomID, '!726s6s6q:example.com');
|
||||
expect(eventUpdateList[8].type, 'account_data');
|
||||
|
||||
expect(eventUpdateList[9].eventType, "org.example.custom.room.config");
|
||||
expect(eventUpdateList[9].roomID, "!726s6s6q:example.com");
|
||||
expect(eventUpdateList[9].type, "account_data");
|
||||
expect(eventUpdateList[9].eventType, 'org.example.custom.room.config');
|
||||
expect(eventUpdateList[9].roomID, '!726s6s6q:example.com');
|
||||
expect(eventUpdateList[9].type, 'account_data');
|
||||
|
||||
expect(eventUpdateList[10].eventType, "m.room.name");
|
||||
expect(eventUpdateList[10].roomID, "!696r7674:example.com");
|
||||
expect(eventUpdateList[10].type, "invite_state");
|
||||
expect(eventUpdateList[10].eventType, 'm.room.name');
|
||||
expect(eventUpdateList[10].roomID, '!696r7674:example.com');
|
||||
expect(eventUpdateList[10].type, 'invite_state');
|
||||
|
||||
expect(eventUpdateList[11].eventType, "m.room.member");
|
||||
expect(eventUpdateList[11].roomID, "!696r7674:example.com");
|
||||
expect(eventUpdateList[11].type, "invite_state");
|
||||
expect(eventUpdateList[11].eventType, 'm.room.member');
|
||||
expect(eventUpdateList[11].roomID, '!696r7674:example.com');
|
||||
expect(eventUpdateList[11].type, 'invite_state');
|
||||
});
|
||||
|
||||
test('User Update Test', () async {
|
||||
await matrix.onUserEvent.close();
|
||||
|
||||
List<UserUpdate> eventUpdateList = await userUpdateListFuture;
|
||||
var eventUpdateList = await userUpdateListFuture;
|
||||
|
||||
expect(eventUpdateList.length, 4);
|
||||
|
||||
expect(eventUpdateList[0].eventType, "m.presence");
|
||||
expect(eventUpdateList[0].type, "presence");
|
||||
expect(eventUpdateList[0].eventType, 'm.presence');
|
||||
expect(eventUpdateList[0].type, 'presence');
|
||||
|
||||
expect(eventUpdateList[1].eventType, "m.push_rules");
|
||||
expect(eventUpdateList[1].type, "account_data");
|
||||
expect(eventUpdateList[1].eventType, 'm.push_rules');
|
||||
expect(eventUpdateList[1].type, 'account_data');
|
||||
|
||||
expect(eventUpdateList[2].eventType, "org.example.custom.config");
|
||||
expect(eventUpdateList[2].type, "account_data");
|
||||
expect(eventUpdateList[2].eventType, 'org.example.custom.config');
|
||||
expect(eventUpdateList[2].type, 'account_data');
|
||||
});
|
||||
|
||||
test('To Device Update Test', () async {
|
||||
await matrix.onToDeviceEvent.close();
|
||||
|
||||
List<ToDeviceEvent> eventUpdateList = await toDeviceUpdateListFuture;
|
||||
var eventUpdateList = await toDeviceUpdateListFuture;
|
||||
|
||||
expect(eventUpdateList.length, 2);
|
||||
|
||||
expect(eventUpdateList[0].type, "m.new_device");
|
||||
expect(eventUpdateList[1].type, "m.room_key");
|
||||
expect(eventUpdateList[0].type, 'm.new_device');
|
||||
expect(eventUpdateList[1].type, 'm.room_key');
|
||||
});
|
||||
|
||||
test('Login', () async {
|
||||
matrix = Client("testclient", debug: true);
|
||||
matrix = Client('testclient', debug: true);
|
||||
matrix.httpClient = FakeMatrixApi();
|
||||
|
||||
roomUpdateListFuture = matrix.onRoomUpdate.stream.toList();
|
||||
eventUpdateListFuture = matrix.onEvent.stream.toList();
|
||||
userUpdateListFuture = matrix.onUserEvent.stream.toList();
|
||||
final bool checkResp =
|
||||
await matrix.checkServer("https://fakeServer.notExisting");
|
||||
final checkResp =
|
||||
await matrix.checkServer('https://fakeServer.notExisting');
|
||||
|
||||
final bool loginResp = await matrix.login("test", "1234");
|
||||
final loginResp = await matrix.login('test', '1234');
|
||||
|
||||
expect(checkResp, true);
|
||||
expect(loginResp, true);
|
||||
});
|
||||
|
||||
test('createRoom', () async {
|
||||
final OpenIdCredentials openId = await matrix.requestOpenIdCredentials();
|
||||
expect(openId.accessToken, "SomeT0kenHere");
|
||||
expect(openId.tokenType, "Bearer");
|
||||
expect(openId.matrixServerName, "example.com");
|
||||
final openId = await matrix.requestOpenIdCredentials();
|
||||
expect(openId.accessToken, 'SomeT0kenHere');
|
||||
expect(openId.tokenType, 'Bearer');
|
||||
expect(openId.matrixServerName, 'example.com');
|
||||
expect(openId.expiresIn, 3600);
|
||||
});
|
||||
|
||||
test('createRoom', () async {
|
||||
final List<User> users = [
|
||||
User("@alice:fakeServer.notExisting"),
|
||||
User("@bob:fakeServer.notExisting")
|
||||
final users = [
|
||||
User('@alice:fakeServer.notExisting'),
|
||||
User('@bob:fakeServer.notExisting')
|
||||
];
|
||||
final String newID = await matrix.createRoom(invite: users);
|
||||
expect(newID, "!1234:fakeServer.notExisting");
|
||||
final newID = await matrix.createRoom(invite: users);
|
||||
expect(newID, '!1234:fakeServer.notExisting');
|
||||
});
|
||||
|
||||
test('setAvatar', () async {
|
||||
final MatrixFile testFile =
|
||||
MatrixFile(bytes: Uint8List(0), path: "fake/path/file.jpeg");
|
||||
final testFile =
|
||||
MatrixFile(bytes: Uint8List(0), path: 'fake/path/file.jpeg');
|
||||
await matrix.setAvatar(testFile);
|
||||
});
|
||||
|
||||
test('setPushers', () async {
|
||||
await matrix.setPushers("abcdefg", "http", "com.famedly.famedlysdk",
|
||||
"famedlySDK", "GitLabCi", "en", "https://examplepushserver.com",
|
||||
format: "event_id_only");
|
||||
await matrix.setPushers('abcdefg', 'http', 'com.famedly.famedlysdk',
|
||||
'famedlySDK', 'GitLabCi', 'en', 'https://examplepushserver.com',
|
||||
format: 'event_id_only');
|
||||
});
|
||||
|
||||
test('joinRoomById', () async {
|
||||
final String roomID = "1234";
|
||||
final roomID = '1234';
|
||||
final Map<String, dynamic> resp = await matrix.joinRoomById(roomID);
|
||||
expect(resp["room_id"], roomID);
|
||||
expect(resp['room_id'], roomID);
|
||||
});
|
||||
|
||||
test('requestUserDevices', () async {
|
||||
final List<UserDevice> userDevices = await matrix.requestUserDevices();
|
||||
final userDevices = await matrix.requestUserDevices();
|
||||
expect(userDevices.length, 1);
|
||||
expect(userDevices.first.deviceId, "QBUAZIFURK");
|
||||
expect(userDevices.first.displayName, "android");
|
||||
expect(userDevices.first.lastSeenIp, "1.2.3.4");
|
||||
expect(userDevices.first.deviceId, 'QBUAZIFURK');
|
||||
expect(userDevices.first.displayName, 'android');
|
||||
expect(userDevices.first.lastSeenIp, '1.2.3.4');
|
||||
expect(
|
||||
userDevices.first.lastSeenTs.millisecondsSinceEpoch, 1474491775024);
|
||||
});
|
||||
|
||||
test('get archive', () async {
|
||||
List<Room> archive = await matrix.archive;
|
||||
var archive = await matrix.archive;
|
||||
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
expect(archive.length, 2);
|
||||
expect(archive[0].id, "!5345234234:example.com");
|
||||
expect(archive[0].id, '!5345234234:example.com');
|
||||
expect(archive[0].membership, Membership.leave);
|
||||
expect(archive[0].name, "The room name");
|
||||
expect(archive[0].lastMessage, "This is an example text message");
|
||||
expect(archive[0].name, 'The room name');
|
||||
expect(archive[0].lastMessage, 'This is an example text message');
|
||||
expect(archive[0].roomAccountData.length, 1);
|
||||
expect(archive[1].id, "!5345234235:example.com");
|
||||
expect(archive[1].id, '!5345234235:example.com');
|
||||
expect(archive[1].membership, Membership.leave);
|
||||
expect(archive[1].name, "The room name 2");
|
||||
expect(archive[1].name, 'The room name 2');
|
||||
});
|
||||
|
||||
test('getProfileFromUserId', () async {
|
||||
final Profile profile =
|
||||
await matrix.getProfileFromUserId("@getme:example.com");
|
||||
expect(profile.avatarUrl.mxc, "mxc://test");
|
||||
expect(profile.displayname, "You got me");
|
||||
expect(profile.content["avatar_url"], profile.avatarUrl.mxc);
|
||||
expect(profile.content["displayname"], profile.displayname);
|
||||
final profile = await matrix.getProfileFromUserId('@getme:example.com');
|
||||
expect(profile.avatarUrl.mxc, 'mxc://test');
|
||||
expect(profile.displayname, 'You got me');
|
||||
expect(profile.content['avatar_url'], profile.avatarUrl.mxc);
|
||||
expect(profile.content['displayname'], profile.displayname);
|
||||
});
|
||||
|
||||
test('signJson', () {
|
||||
if (matrix.encryptionEnabled) {
|
||||
expect(matrix.fingerprintKey.isNotEmpty, true);
|
||||
expect(matrix.identityKey.isNotEmpty, true);
|
||||
Map<String, dynamic> payload = {
|
||||
"unsigned": {
|
||||
"foo": "bar",
|
||||
var payload = <String, dynamic>{
|
||||
'unsigned': {
|
||||
'foo': 'bar',
|
||||
},
|
||||
"auth": {
|
||||
"success": true,
|
||||
"mxid": "@john.doe:example.com",
|
||||
"profile": {
|
||||
"display_name": "John Doe",
|
||||
"three_pids": [
|
||||
{"medium": "email", "address": "john.doe@example.org"},
|
||||
{"medium": "msisdn", "address": "123456789"}
|
||||
'auth': {
|
||||
'success': true,
|
||||
'mxid': '@john.doe:example.com',
|
||||
'profile': {
|
||||
'display_name': 'John Doe',
|
||||
'three_pids': [
|
||||
{'medium': 'email', 'address': 'john.doe@example.org'},
|
||||
{'medium': 'msisdn', 'address': '123456789'}
|
||||
]
|
||||
}
|
||||
}
|
||||
};
|
||||
Map<String, dynamic> payloadWithoutUnsigned = Map.from(payload);
|
||||
payloadWithoutUnsigned.remove("unsigned");
|
||||
var payloadWithoutUnsigned = Map<String, dynamic>.from(payload);
|
||||
payloadWithoutUnsigned.remove('unsigned');
|
||||
|
||||
expect(
|
||||
matrix.checkJsonSignature(
|
||||
|
@ -517,8 +511,8 @@ void main() {
|
|||
false);
|
||||
payload = matrix.signJson(payload);
|
||||
payloadWithoutUnsigned = matrix.signJson(payloadWithoutUnsigned);
|
||||
expect(payload["signatures"], payloadWithoutUnsigned["signatures"]);
|
||||
print(payload["signatures"]);
|
||||
expect(payload['signatures'], payloadWithoutUnsigned['signatures']);
|
||||
print(payload['signatures']);
|
||||
expect(
|
||||
matrix.checkJsonSignature(
|
||||
matrix.fingerprintKey, payload, matrix.userID, matrix.deviceID),
|
||||
|
@ -531,9 +525,9 @@ void main() {
|
|||
});
|
||||
test('Track oneTimeKeys', () async {
|
||||
if (matrix.encryptionEnabled) {
|
||||
DateTime last = matrix.lastTimeKeysUploaded ?? DateTime.now();
|
||||
var last = matrix.lastTimeKeysUploaded ?? DateTime.now();
|
||||
matrix.handleSync({
|
||||
"device_one_time_keys_count": {"signed_curve25519": 49}
|
||||
'device_one_time_keys_count': {'signed_curve25519': 49}
|
||||
});
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
expect(
|
||||
|
@ -548,12 +542,12 @@ void main() {
|
|||
await matrix.rooms[1].createOutboundGroupSession();
|
||||
expect(matrix.rooms[1].outboundGroupSession != null, true);
|
||||
matrix.handleSync({
|
||||
"device_lists": {
|
||||
"changed": [
|
||||
"@alice:example.com",
|
||||
'device_lists': {
|
||||
'changed': [
|
||||
'@alice:example.com',
|
||||
],
|
||||
"left": [
|
||||
"@bob:example.com",
|
||||
'left': [
|
||||
'@bob:example.com',
|
||||
],
|
||||
}
|
||||
});
|
||||
|
@ -568,19 +562,19 @@ void main() {
|
|||
await matrix.rooms[1].createOutboundGroupSession();
|
||||
expect(matrix.rooms[1].outboundGroupSession != null, true);
|
||||
matrix.handleSync({
|
||||
"rooms": {
|
||||
"join": {
|
||||
"!726s6s6q:example.com": {
|
||||
"state": {
|
||||
"events": [
|
||||
'rooms': {
|
||||
'join': {
|
||||
'!726s6s6q:example.com': {
|
||||
'state': {
|
||||
'events': [
|
||||
{
|
||||
"content": {"membership": "leave"},
|
||||
"event_id": "143273582443PhrSn:example.org",
|
||||
"origin_server_ts": 1432735824653,
|
||||
"room_id": "!726s6s6q:example.com",
|
||||
"sender": "@alice:example.com",
|
||||
"state_key": "@alice:example.com",
|
||||
"type": "m.room.member"
|
||||
'content': {'membership': 'leave'},
|
||||
'event_id': '143273582443PhrSn:example.org',
|
||||
'origin_server_ts': 1432735824653,
|
||||
'room_id': '!726s6s6q:example.com',
|
||||
'sender': '@alice:example.com',
|
||||
'state_key': '@alice:example.com',
|
||||
'type': 'm.room.member'
|
||||
}
|
||||
]
|
||||
}
|
||||
|
@ -592,18 +586,18 @@ void main() {
|
|||
expect(matrix.rooms[1].outboundGroupSession != null, true);
|
||||
}
|
||||
});
|
||||
DeviceKeys deviceKeys = DeviceKeys.fromJson({
|
||||
"user_id": "@alice:example.com",
|
||||
"device_id": "JLAFKJWSCS",
|
||||
"algorithms": ["m.olm.v1.curve25519-aes-sha2", "m.megolm.v1.aes-sha2"],
|
||||
"keys": {
|
||||
"curve25519:JLAFKJWSCS": "3C5BFWi2Y8MaVvjM8M22DBmh24PmgR0nPvJOIArzgyI",
|
||||
"ed25519:JLAFKJWSCS": "lEuiRJBit0IG6nUf5pUzWTUEsRVVe/HJkoKuEww9ULI"
|
||||
var deviceKeys = DeviceKeys.fromJson({
|
||||
'user_id': '@alice:example.com',
|
||||
'device_id': 'JLAFKJWSCS',
|
||||
'algorithms': ['m.olm.v1.curve25519-aes-sha2', 'm.megolm.v1.aes-sha2'],
|
||||
'keys': {
|
||||
'curve25519:JLAFKJWSCS': '3C5BFWi2Y8MaVvjM8M22DBmh24PmgR0nPvJOIArzgyI',
|
||||
'ed25519:JLAFKJWSCS': 'lEuiRJBit0IG6nUf5pUzWTUEsRVVe/HJkoKuEww9ULI'
|
||||
},
|
||||
"signatures": {
|
||||
"@alice:example.com": {
|
||||
"ed25519:JLAFKJWSCS":
|
||||
"dSO80A01XiigH3uBiDVx/EjzaoycHcjq9lfQX0uWsqxl2giMIiSPR8a4d291W1ihKJL/a+myXS367WT6NAIcBA"
|
||||
'signatures': {
|
||||
'@alice:example.com': {
|
||||
'ed25519:JLAFKJWSCS':
|
||||
'dSO80A01XiigH3uBiDVx/EjzaoycHcjq9lfQX0uWsqxl2giMIiSPR8a4d291W1ihKJL/a+myXS367WT6NAIcBA'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
@ -614,52 +608,51 @@ void main() {
|
|||
.startOutgoingOlmSessions([deviceKeys], checkSignature: false);
|
||||
expect(matrix.olmSessions.length, 1);
|
||||
expect(matrix.olmSessions.entries.first.key,
|
||||
"3C5BFWi2Y8MaVvjM8M22DBmh24PmgR0nPvJOIArzgyI");
|
||||
'3C5BFWi2Y8MaVvjM8M22DBmh24PmgR0nPvJOIArzgyI');
|
||||
}
|
||||
});
|
||||
test('sendToDevice', () async {
|
||||
await matrix.sendToDevice(
|
||||
[deviceKeys],
|
||||
"m.message",
|
||||
'm.message',
|
||||
{
|
||||
"msgtype": "m.text",
|
||||
"body": "Hello world",
|
||||
'msgtype': 'm.text',
|
||||
'body': 'Hello world',
|
||||
});
|
||||
});
|
||||
test('Logout when token is unknown', () async {
|
||||
Future<LoginState> loginStateFuture =
|
||||
matrix.onLoginStateChanged.stream.first;
|
||||
var loginStateFuture = matrix.onLoginStateChanged.stream.first;
|
||||
|
||||
try {
|
||||
await matrix.jsonRequest(
|
||||
type: HTTPType.DELETE, action: "/unknown/token");
|
||||
type: HTTPType.DELETE, action: '/unknown/token');
|
||||
} on MatrixException catch (exception) {
|
||||
expect(exception.error, MatrixError.M_UNKNOWN_TOKEN);
|
||||
}
|
||||
|
||||
LoginState state = await loginStateFuture;
|
||||
var state = await loginStateFuture;
|
||||
expect(state, LoginState.loggedOut);
|
||||
expect(matrix.isLogged(), false);
|
||||
});
|
||||
test('Test the fake store api', () async {
|
||||
Client client1 = Client("testclient", debug: true);
|
||||
var client1 = Client('testclient', debug: true);
|
||||
client1.httpClient = FakeMatrixApi();
|
||||
FakeStore fakeStore = FakeStore(client1, {});
|
||||
var fakeStore = FakeStore(client1, {});
|
||||
client1.storeAPI = fakeStore;
|
||||
|
||||
client1.connect(
|
||||
newToken: "abc123",
|
||||
newUserID: "@test:fakeServer.notExisting",
|
||||
newHomeserver: "https://fakeServer.notExisting",
|
||||
newDeviceName: "Text Matrix Client",
|
||||
newDeviceID: "GHTYAJCE",
|
||||
newToken: 'abc123',
|
||||
newUserID: '@test:fakeServer.notExisting',
|
||||
newHomeserver: 'https://fakeServer.notExisting',
|
||||
newDeviceName: 'Text Matrix Client',
|
||||
newDeviceID: 'GHTYAJCE',
|
||||
newMatrixVersions: [
|
||||
"r0.0.1",
|
||||
"r0.1.0",
|
||||
"r0.2.0",
|
||||
"r0.3.0",
|
||||
"r0.4.0",
|
||||
"r0.5.0"
|
||||
'r0.0.1',
|
||||
'r0.1.0',
|
||||
'r0.2.0',
|
||||
'r0.3.0',
|
||||
'r0.4.0',
|
||||
'r0.5.0'
|
||||
],
|
||||
newLazyLoadMembers: true,
|
||||
newOlmAccount: pickledOlmAccount,
|
||||
|
@ -677,7 +670,7 @@ void main() {
|
|||
expect(client1.isLogged(), true);
|
||||
expect(client1.rooms.length, 2);
|
||||
|
||||
Client client2 = Client("testclient", debug: true);
|
||||
var client2 = Client('testclient', debug: true);
|
||||
client2.httpClient = FakeMatrixApi();
|
||||
client2.storeAPI = FakeStore(client2, fakeStore.storeMap);
|
||||
|
||||
|
|
|
@ -28,38 +28,38 @@ import 'package:test/test.dart';
|
|||
|
||||
void main() {
|
||||
/// All Tests related to device keys
|
||||
group("Device keys", () {
|
||||
test("fromJson", () async {
|
||||
Map<String, dynamic> rawJson = {
|
||||
"user_id": "@alice:example.com",
|
||||
"device_id": "JLAFKJWSCS",
|
||||
"algorithms": ["m.olm.v1.curve25519-aes-sha2", "m.megolm.v1.aes-sha2"],
|
||||
"keys": {
|
||||
"curve25519:JLAFKJWSCS":
|
||||
"3C5BFWi2Y8MaVvjM8M22DBmh24PmgR0nPvJOIArzgyI",
|
||||
"ed25519:JLAFKJWSCS": "lEuiRJBit0IG6nUf5pUzWTUEsRVVe/HJkoKuEww9ULI"
|
||||
group('Device keys', () {
|
||||
test('fromJson', () async {
|
||||
var rawJson = <String, dynamic>{
|
||||
'user_id': '@alice:example.com',
|
||||
'device_id': 'JLAFKJWSCS',
|
||||
'algorithms': ['m.olm.v1.curve25519-aes-sha2', 'm.megolm.v1.aes-sha2'],
|
||||
'keys': {
|
||||
'curve25519:JLAFKJWSCS':
|
||||
'3C5BFWi2Y8MaVvjM8M22DBmh24PmgR0nPvJOIArzgyI',
|
||||
'ed25519:JLAFKJWSCS': 'lEuiRJBit0IG6nUf5pUzWTUEsRVVe/HJkoKuEww9ULI'
|
||||
},
|
||||
"signatures": {
|
||||
"@alice:example.com": {
|
||||
"ed25519:JLAFKJWSCS":
|
||||
"dSO80A01XiigH3uBiDVx/EjzaoycHcjq9lfQX0uWsqxl2giMIiSPR8a4d291W1ihKJL/a+myXS367WT6NAIcBA"
|
||||
'signatures': {
|
||||
'@alice:example.com': {
|
||||
'ed25519:JLAFKJWSCS':
|
||||
'dSO80A01XiigH3uBiDVx/EjzaoycHcjq9lfQX0uWsqxl2giMIiSPR8a4d291W1ihKJL/a+myXS367WT6NAIcBA'
|
||||
}
|
||||
},
|
||||
"unsigned": {"device_display_name": "Alice's mobile phone"},
|
||||
"verified": false,
|
||||
"blocked": true,
|
||||
'unsigned': {'device_display_name': "Alice's mobile phone"},
|
||||
'verified': false,
|
||||
'blocked': true,
|
||||
};
|
||||
Map<String, dynamic> rawListJson = {
|
||||
"user_id": "@alice:example.com",
|
||||
"outdated": true,
|
||||
"device_keys": {"JLAFKJWSCS": rawJson},
|
||||
var rawListJson = <String, dynamic>{
|
||||
'user_id': '@alice:example.com',
|
||||
'outdated': true,
|
||||
'device_keys': {'JLAFKJWSCS': rawJson},
|
||||
};
|
||||
|
||||
Map<String, DeviceKeysList> userDeviceKeys = {
|
||||
"@alice:example.com": DeviceKeysList.fromJson(rawListJson),
|
||||
var userDeviceKeys = <String, DeviceKeysList>{
|
||||
'@alice:example.com': DeviceKeysList.fromJson(rawListJson),
|
||||
};
|
||||
Map<String, dynamic> userDeviceKeyRaw = {
|
||||
"@alice:example.com": rawListJson,
|
||||
var userDeviceKeyRaw = <String, dynamic>{
|
||||
'@alice:example.com': rawListJson,
|
||||
};
|
||||
|
||||
expect(json.encode(DeviceKeys.fromJson(rawJson).toJson()),
|
||||
|
@ -67,7 +67,7 @@ void main() {
|
|||
expect(json.encode(DeviceKeysList.fromJson(rawListJson).toJson()),
|
||||
json.encode(rawListJson));
|
||||
|
||||
Map<String, DeviceKeysList> mapFromRaw = {};
|
||||
var mapFromRaw = <String, DeviceKeysList>{};
|
||||
for (final rawListEntry in userDeviceKeyRaw.entries) {
|
||||
mapFromRaw[rawListEntry.key] =
|
||||
DeviceKeysList.fromJson(rawListEntry.value);
|
||||
|
|
|
@ -31,34 +31,34 @@ import 'fake_matrix_api.dart';
|
|||
|
||||
void main() {
|
||||
/// All Tests related to the Event
|
||||
group("Event", () {
|
||||
final int timestamp = DateTime.now().millisecondsSinceEpoch;
|
||||
final String id = "!4fsdfjisjf:server.abc";
|
||||
final String senderID = "@alice:server.abc";
|
||||
final String type = "m.room.message";
|
||||
final String msgtype = "m.text";
|
||||
final String body = "Hello World";
|
||||
final String formatted_body = "<b>Hello</b> World";
|
||||
group('Event', () {
|
||||
final timestamp = DateTime.now().millisecondsSinceEpoch;
|
||||
final id = '!4fsdfjisjf:server.abc';
|
||||
final senderID = '@alice:server.abc';
|
||||
final type = 'm.room.message';
|
||||
final msgtype = 'm.text';
|
||||
final body = 'Hello World';
|
||||
final formatted_body = '<b>Hello</b> World';
|
||||
|
||||
final String contentJson =
|
||||
final contentJson =
|
||||
'{"msgtype":"$msgtype","body":"$body","formatted_body":"$formatted_body","m.relates_to":{"m.in_reply_to":{"event_id":"\$1234:example.com"}}}';
|
||||
|
||||
Map<String, dynamic> jsonObj = {
|
||||
"event_id": id,
|
||||
"sender": senderID,
|
||||
"origin_server_ts": timestamp,
|
||||
"type": type,
|
||||
"room_id": "1234",
|
||||
"status": 2,
|
||||
"content": contentJson,
|
||||
var jsonObj = <String, dynamic>{
|
||||
'event_id': id,
|
||||
'sender': senderID,
|
||||
'origin_server_ts': timestamp,
|
||||
'type': type,
|
||||
'room_id': '1234',
|
||||
'status': 2,
|
||||
'content': contentJson,
|
||||
};
|
||||
|
||||
test("Create from json", () async {
|
||||
Event event = Event.fromJson(jsonObj, null);
|
||||
jsonObj.remove("status");
|
||||
jsonObj["content"] = json.decode(contentJson);
|
||||
test('Create from json', () async {
|
||||
var event = Event.fromJson(jsonObj, null);
|
||||
jsonObj.remove('status');
|
||||
jsonObj['content'] = json.decode(contentJson);
|
||||
expect(event.toJson(), jsonObj);
|
||||
jsonObj["content"] = contentJson;
|
||||
jsonObj['content'] = contentJson;
|
||||
|
||||
expect(event.eventId, id);
|
||||
expect(event.senderId, senderID);
|
||||
|
@ -68,181 +68,180 @@ void main() {
|
|||
expect(event.body, body);
|
||||
expect(event.type, EventTypes.Message);
|
||||
expect(event.isReply, true);
|
||||
jsonObj["state_key"] = "";
|
||||
Event state = Event.fromJson(jsonObj, null);
|
||||
jsonObj['state_key'] = '';
|
||||
var state = Event.fromJson(jsonObj, null);
|
||||
expect(state.eventId, id);
|
||||
expect(state.stateKey, "");
|
||||
expect(state.stateKey, '');
|
||||
expect(state.status, 2);
|
||||
});
|
||||
test("Test all EventTypes", () async {
|
||||
test('Test all EventTypes', () async {
|
||||
Event event;
|
||||
|
||||
jsonObj["type"] = "m.room.avatar";
|
||||
jsonObj['type'] = 'm.room.avatar';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.type, EventTypes.RoomAvatar);
|
||||
|
||||
jsonObj["type"] = "m.room.name";
|
||||
jsonObj['type'] = 'm.room.name';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.type, EventTypes.RoomName);
|
||||
|
||||
jsonObj["type"] = "m.room.topic";
|
||||
jsonObj['type'] = 'm.room.topic';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.type, EventTypes.RoomTopic);
|
||||
|
||||
jsonObj["type"] = "m.room.aliases";
|
||||
jsonObj['type'] = 'm.room.aliases';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.type, EventTypes.RoomAliases);
|
||||
|
||||
jsonObj["type"] = "m.room.canonical_alias";
|
||||
jsonObj['type'] = 'm.room.canonical_alias';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.type, EventTypes.RoomCanonicalAlias);
|
||||
|
||||
jsonObj["type"] = "m.room.create";
|
||||
jsonObj['type'] = 'm.room.create';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.type, EventTypes.RoomCreate);
|
||||
|
||||
jsonObj["type"] = "m.room.join_rules";
|
||||
jsonObj['type'] = 'm.room.join_rules';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.type, EventTypes.RoomJoinRules);
|
||||
|
||||
jsonObj["type"] = "m.room.member";
|
||||
jsonObj['type'] = 'm.room.member';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.type, EventTypes.RoomMember);
|
||||
|
||||
jsonObj["type"] = "m.room.power_levels";
|
||||
jsonObj['type'] = 'm.room.power_levels';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.type, EventTypes.RoomPowerLevels);
|
||||
|
||||
jsonObj["type"] = "m.room.guest_access";
|
||||
jsonObj['type'] = 'm.room.guest_access';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.type, EventTypes.GuestAccess);
|
||||
|
||||
jsonObj["type"] = "m.room.history_visibility";
|
||||
jsonObj['type'] = 'm.room.history_visibility';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.type, EventTypes.HistoryVisibility);
|
||||
|
||||
jsonObj["type"] = "m.room.message";
|
||||
jsonObj["content"] = json.decode(jsonObj["content"]);
|
||||
jsonObj['type'] = 'm.room.message';
|
||||
jsonObj['content'] = json.decode(jsonObj['content']);
|
||||
|
||||
jsonObj["content"]["msgtype"] = "m.notice";
|
||||
jsonObj['content']['msgtype'] = 'm.notice';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.messageType, MessageTypes.Notice);
|
||||
|
||||
jsonObj["content"]["msgtype"] = "m.emote";
|
||||
jsonObj['content']['msgtype'] = 'm.emote';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.messageType, MessageTypes.Emote);
|
||||
|
||||
jsonObj["content"]["msgtype"] = "m.image";
|
||||
jsonObj['content']['msgtype'] = 'm.image';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.messageType, MessageTypes.Image);
|
||||
|
||||
jsonObj["content"]["msgtype"] = "m.video";
|
||||
jsonObj['content']['msgtype'] = 'm.video';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.messageType, MessageTypes.Video);
|
||||
|
||||
jsonObj["content"]["msgtype"] = "m.audio";
|
||||
jsonObj['content']['msgtype'] = 'm.audio';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.messageType, MessageTypes.Audio);
|
||||
|
||||
jsonObj["content"]["msgtype"] = "m.file";
|
||||
jsonObj['content']['msgtype'] = 'm.file';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.messageType, MessageTypes.File);
|
||||
|
||||
jsonObj["content"]["msgtype"] = "m.location";
|
||||
jsonObj['content']['msgtype'] = 'm.location';
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.messageType, MessageTypes.Location);
|
||||
|
||||
jsonObj["type"] = "m.room.message";
|
||||
jsonObj["content"]["msgtype"] = "m.text";
|
||||
jsonObj["content"]["m.relates_to"] = {};
|
||||
jsonObj["content"]["m.relates_to"]["m.in_reply_to"] = {
|
||||
"event_id": "1234",
|
||||
jsonObj['type'] = 'm.room.message';
|
||||
jsonObj['content']['msgtype'] = 'm.text';
|
||||
jsonObj['content']['m.relates_to'] = {};
|
||||
jsonObj['content']['m.relates_to']['m.in_reply_to'] = {
|
||||
'event_id': '1234',
|
||||
};
|
||||
event = Event.fromJson(jsonObj, null);
|
||||
expect(event.messageType, MessageTypes.Reply);
|
||||
});
|
||||
|
||||
test("redact", () async {
|
||||
final Room room =
|
||||
Room(id: "1234", client: Client("testclient", debug: true));
|
||||
final Map<String, dynamic> redactionEventJson = {
|
||||
"content": {"reason": "Spamming"},
|
||||
"event_id": "143273582443PhrSn:example.org",
|
||||
"origin_server_ts": 1432735824653,
|
||||
"redacts": id,
|
||||
"room_id": "1234",
|
||||
"sender": "@example:example.org",
|
||||
"type": "m.room.redaction",
|
||||
"unsigned": {"age": 1234}
|
||||
test('redact', () async {
|
||||
final room = Room(id: '1234', client: Client('testclient', debug: true));
|
||||
final redactionEventJson = {
|
||||
'content': {'reason': 'Spamming'},
|
||||
'event_id': '143273582443PhrSn:example.org',
|
||||
'origin_server_ts': 1432735824653,
|
||||
'redacts': id,
|
||||
'room_id': '1234',
|
||||
'sender': '@example:example.org',
|
||||
'type': 'm.room.redaction',
|
||||
'unsigned': {'age': 1234}
|
||||
};
|
||||
Event redactedBecause = Event.fromJson(redactionEventJson, room);
|
||||
Event event = Event.fromJson(jsonObj, room);
|
||||
var redactedBecause = Event.fromJson(redactionEventJson, room);
|
||||
var event = Event.fromJson(jsonObj, room);
|
||||
event.setRedactionEvent(redactedBecause);
|
||||
expect(event.redacted, true);
|
||||
expect(event.redactedBecause.toJson(), redactedBecause.toJson());
|
||||
expect(event.content.isEmpty, true);
|
||||
redactionEventJson.remove("redacts");
|
||||
expect(event.unsigned["redacted_because"], redactionEventJson);
|
||||
redactionEventJson.remove('redacts');
|
||||
expect(event.unsigned['redacted_because'], redactionEventJson);
|
||||
});
|
||||
|
||||
test("remove", () async {
|
||||
Event event = Event.fromJson(
|
||||
jsonObj, Room(id: "1234", client: Client("testclient", debug: true)));
|
||||
final bool removed1 = await event.remove();
|
||||
test('remove', () async {
|
||||
var event = Event.fromJson(
|
||||
jsonObj, Room(id: '1234', client: Client('testclient', debug: true)));
|
||||
final removed1 = await event.remove();
|
||||
event.status = 0;
|
||||
final bool removed2 = await event.remove();
|
||||
final removed2 = await event.remove();
|
||||
expect(removed1, false);
|
||||
expect(removed2, true);
|
||||
});
|
||||
|
||||
test("sendAgain", () async {
|
||||
Client matrix = Client("testclient", debug: true);
|
||||
test('sendAgain', () async {
|
||||
var matrix = Client('testclient', debug: true);
|
||||
matrix.httpClient = FakeMatrixApi();
|
||||
await matrix.checkServer("https://fakeServer.notExisting");
|
||||
await matrix.login("test", "1234");
|
||||
await matrix.checkServer('https://fakeServer.notExisting');
|
||||
await matrix.login('test', '1234');
|
||||
|
||||
Event event = Event.fromJson(
|
||||
jsonObj, Room(id: "!1234:example.com", client: matrix));
|
||||
final String resp1 = await event.sendAgain();
|
||||
var event = Event.fromJson(
|
||||
jsonObj, Room(id: '!1234:example.com', client: matrix));
|
||||
final resp1 = await event.sendAgain();
|
||||
event.status = -1;
|
||||
final String resp2 = await event.sendAgain(txid: "1234");
|
||||
final resp2 = await event.sendAgain(txid: '1234');
|
||||
expect(resp1, null);
|
||||
expect(resp2, "42");
|
||||
expect(resp2, '42');
|
||||
});
|
||||
|
||||
test("requestKey", () async {
|
||||
Client matrix = Client("testclient", debug: true);
|
||||
test('requestKey', () async {
|
||||
var matrix = Client('testclient', debug: true);
|
||||
matrix.httpClient = FakeMatrixApi();
|
||||
await matrix.checkServer("https://fakeServer.notExisting");
|
||||
await matrix.login("test", "1234");
|
||||
await matrix.checkServer('https://fakeServer.notExisting');
|
||||
await matrix.login('test', '1234');
|
||||
|
||||
Event event = Event.fromJson(
|
||||
jsonObj, Room(id: "!1234:example.com", client: matrix));
|
||||
var event = Event.fromJson(
|
||||
jsonObj, Room(id: '!1234:example.com', client: matrix));
|
||||
String exception;
|
||||
try {
|
||||
await event.requestKey();
|
||||
} catch (e) {
|
||||
exception = e;
|
||||
}
|
||||
expect(exception, "Session key not unknown");
|
||||
expect(exception, 'Session key not unknown');
|
||||
|
||||
event = Event.fromJson({
|
||||
"event_id": id,
|
||||
"sender": senderID,
|
||||
"origin_server_ts": timestamp,
|
||||
"type": "m.room.encrypted",
|
||||
"room_id": "1234",
|
||||
"status": 2,
|
||||
"content": json.encode({
|
||||
"msgtype": "m.bad.encrypted",
|
||||
"body": DecryptError.UNKNOWN_SESSION,
|
||||
"algorithm": "m.megolm.v1.aes-sha2",
|
||||
"ciphertext": "AwgAEnACgAkLmt6qF84IK++J7UDH2Za1YVchHyprqTqsg...",
|
||||
"device_id": "RJYKSTBOIE",
|
||||
"sender_key": "IlRMeOPX2e0MurIyfWEucYBRVOEEUMrOHqn/8mLqMjA",
|
||||
"session_id": "X3lUlvLELLYxeTx4yOVu6UDpasGEVO0Jbu+QFnm0cKQ"
|
||||
'event_id': id,
|
||||
'sender': senderID,
|
||||
'origin_server_ts': timestamp,
|
||||
'type': 'm.room.encrypted',
|
||||
'room_id': '1234',
|
||||
'status': 2,
|
||||
'content': json.encode({
|
||||
'msgtype': 'm.bad.encrypted',
|
||||
'body': DecryptError.UNKNOWN_SESSION,
|
||||
'algorithm': 'm.megolm.v1.aes-sha2',
|
||||
'ciphertext': 'AwgAEnACgAkLmt6qF84IK++J7UDH2Za1YVchHyprqTqsg...',
|
||||
'device_id': 'RJYKSTBOIE',
|
||||
'sender_key': 'IlRMeOPX2e0MurIyfWEucYBRVOEEUMrOHqn/8mLqMjA',
|
||||
'session_id': 'X3lUlvLELLYxeTx4yOVu6UDpasGEVO0Jbu+QFnm0cKQ'
|
||||
}),
|
||||
}, Room(id: "!1234:example.com", client: matrix));
|
||||
}, Room(id: '!1234:example.com', client: matrix));
|
||||
|
||||
await event.requestKey();
|
||||
});
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -5,83 +5,91 @@ import 'package:famedlysdk/famedlysdk.dart';
|
|||
class FakeStore implements StoreAPI {
|
||||
/// Whether this is a simple store which only stores the client credentials and
|
||||
/// end to end encryption stuff or the whole sync payloads.
|
||||
@override
|
||||
final bool extended = false;
|
||||
|
||||
Map<String, dynamic> storeMap = {};
|
||||
|
||||
/// Link back to the client.
|
||||
@override
|
||||
Client client;
|
||||
|
||||
FakeStore(this.client, this.storeMap) {
|
||||
_init();
|
||||
}
|
||||
|
||||
_init() async {
|
||||
Future<void> _init() async {
|
||||
final credentialsStr = await getItem(client.clientName);
|
||||
|
||||
if (credentialsStr == null || credentialsStr.isEmpty) {
|
||||
client.onLoginStateChanged.add(LoginState.loggedOut);
|
||||
return;
|
||||
}
|
||||
print("[Matrix] Restoring account credentials");
|
||||
print('[Matrix] Restoring account credentials');
|
||||
final Map<String, dynamic> credentials = json.decode(credentialsStr);
|
||||
client.connect(
|
||||
newDeviceID: credentials["deviceID"],
|
||||
newDeviceName: credentials["deviceName"],
|
||||
newHomeserver: credentials["homeserver"],
|
||||
newLazyLoadMembers: credentials["lazyLoadMembers"],
|
||||
newMatrixVersions: List<String>.from(credentials["matrixVersions"]),
|
||||
newToken: credentials["token"],
|
||||
newUserID: credentials["userID"],
|
||||
newPrevBatch: credentials["prev_batch"],
|
||||
newOlmAccount: credentials["olmAccount"],
|
||||
newDeviceID: credentials['deviceID'],
|
||||
newDeviceName: credentials['deviceName'],
|
||||
newHomeserver: credentials['homeserver'],
|
||||
newLazyLoadMembers: credentials['lazyLoadMembers'],
|
||||
newMatrixVersions: List<String>.from(credentials['matrixVersions']),
|
||||
newToken: credentials['token'],
|
||||
newUserID: credentials['userID'],
|
||||
newPrevBatch: credentials['prev_batch'],
|
||||
newOlmAccount: credentials['olmAccount'],
|
||||
);
|
||||
}
|
||||
|
||||
/// Will be automatically called when the client is logged in successfully.
|
||||
@override
|
||||
Future<void> storeClient() async {
|
||||
final Map<String, dynamic> credentials = {
|
||||
"deviceID": client.deviceID,
|
||||
"deviceName": client.deviceName,
|
||||
"homeserver": client.homeserver,
|
||||
"lazyLoadMembers": client.lazyLoadMembers,
|
||||
"matrixVersions": client.matrixVersions,
|
||||
"token": client.accessToken,
|
||||
"userID": client.userID,
|
||||
"olmAccount": client.pickledOlmAccount,
|
||||
final credentials = {
|
||||
'deviceID': client.deviceID,
|
||||
'deviceName': client.deviceName,
|
||||
'homeserver': client.homeserver,
|
||||
'lazyLoadMembers': client.lazyLoadMembers,
|
||||
'matrixVersions': client.matrixVersions,
|
||||
'token': client.accessToken,
|
||||
'userID': client.userID,
|
||||
'olmAccount': client.pickledOlmAccount,
|
||||
};
|
||||
await setItem(client.clientName, json.encode(credentials));
|
||||
return;
|
||||
}
|
||||
|
||||
/// Clears all tables from the database.
|
||||
@override
|
||||
Future<void> clear() async {
|
||||
storeMap = {};
|
||||
return;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<dynamic> getItem(String key) async {
|
||||
return storeMap[key];
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setItem(String key, String value) async {
|
||||
storeMap[key] = value;
|
||||
return;
|
||||
}
|
||||
|
||||
String get _UserDeviceKeysKey => "${client.clientName}.user_device_keys";
|
||||
String get _UserDeviceKeysKey => '${client.clientName}.user_device_keys';
|
||||
|
||||
@override
|
||||
Future<Map<String, DeviceKeysList>> getUserDeviceKeys() async {
|
||||
final deviceKeysListString = await getItem(_UserDeviceKeysKey);
|
||||
if (deviceKeysListString == null) return {};
|
||||
Map<String, dynamic> rawUserDeviceKeys = json.decode(deviceKeysListString);
|
||||
Map<String, DeviceKeysList> userDeviceKeys = {};
|
||||
var userDeviceKeys = <String, DeviceKeysList>{};
|
||||
for (final entry in rawUserDeviceKeys.entries) {
|
||||
userDeviceKeys[entry.key] = DeviceKeysList.fromJson(entry.value);
|
||||
}
|
||||
return userDeviceKeys;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> storeUserDeviceKeys(
|
||||
Map<String, DeviceKeysList> userDeviceKeys) async {
|
||||
await setItem(_UserDeviceKeysKey, json.encode(userDeviceKeys));
|
||||
|
|
|
@ -26,25 +26,25 @@ import 'package:famedlysdk/src/utils/matrix_id_string_extension.dart';
|
|||
|
||||
void main() {
|
||||
/// All Tests related to the ChatTime
|
||||
group("Matrix ID String Extension", () {
|
||||
test("Matrix ID String Extension", () async {
|
||||
final String mxId = "@test:example.com";
|
||||
group('Matrix ID String Extension', () {
|
||||
test('Matrix ID String Extension', () async {
|
||||
final mxId = '@test:example.com';
|
||||
expect(mxId.isValidMatrixId, true);
|
||||
expect("#test:example.com".isValidMatrixId, true);
|
||||
expect("!test:example.com".isValidMatrixId, true);
|
||||
expect("+test:example.com".isValidMatrixId, true);
|
||||
expect("\$test:example.com".isValidMatrixId, true);
|
||||
expect("test:example.com".isValidMatrixId, false);
|
||||
expect("@testexample.com".isValidMatrixId, false);
|
||||
expect("@:example.com".isValidMatrixId, false);
|
||||
expect("@test:".isValidMatrixId, false);
|
||||
expect(mxId.sigil, "@");
|
||||
expect("#test:example.com".sigil, "#");
|
||||
expect("!test:example.com".sigil, "!");
|
||||
expect("+test:example.com".sigil, "+");
|
||||
expect("\$test:example.com".sigil, "\$");
|
||||
expect(mxId.localpart, "test");
|
||||
expect(mxId.domain, "example.com");
|
||||
expect('#test:example.com'.isValidMatrixId, true);
|
||||
expect('!test:example.com'.isValidMatrixId, true);
|
||||
expect('+test:example.com'.isValidMatrixId, true);
|
||||
expect('\$test:example.com'.isValidMatrixId, true);
|
||||
expect('test:example.com'.isValidMatrixId, false);
|
||||
expect('@testexample.com'.isValidMatrixId, false);
|
||||
expect('@:example.com'.isValidMatrixId, false);
|
||||
expect('@test:'.isValidMatrixId, false);
|
||||
expect(mxId.sigil, '@');
|
||||
expect('#test:example.com'.sigil, '#');
|
||||
expect('!test:example.com'.sigil, '!');
|
||||
expect('+test:example.com'.sigil, '+');
|
||||
expect('\$test:example.com'.sigil, '\$');
|
||||
expect(mxId.localpart, 'test');
|
||||
expect(mxId.domain, 'example.com');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
@ -29,30 +29,30 @@ import 'fake_matrix_api.dart';
|
|||
|
||||
void main() {
|
||||
/// All Tests related to the MxContent
|
||||
group("MxContent", () {
|
||||
test("Formatting", () async {
|
||||
Client client = Client("testclient");
|
||||
group('MxContent', () {
|
||||
test('Formatting', () async {
|
||||
var client = Client('testclient');
|
||||
client.httpClient = FakeMatrixApi();
|
||||
await client.checkServer("https://fakeserver.notexisting");
|
||||
final String mxc = "mxc://exampleserver.abc/abcdefghijklmn";
|
||||
final MxContent content = MxContent(mxc);
|
||||
await client.checkServer('https://fakeserver.notexisting');
|
||||
final mxc = 'mxc://exampleserver.abc/abcdefghijklmn';
|
||||
final content = MxContent(mxc);
|
||||
|
||||
expect(content.getDownloadLink(client),
|
||||
"${client.homeserver}/_matrix/media/r0/download/exampleserver.abc/abcdefghijklmn");
|
||||
'${client.homeserver}/_matrix/media/r0/download/exampleserver.abc/abcdefghijklmn');
|
||||
expect(content.getThumbnail(client, width: 50, height: 50),
|
||||
"${client.homeserver}/_matrix/media/r0/thumbnail/exampleserver.abc/abcdefghijklmn?width=50&height=50&method=crop");
|
||||
'${client.homeserver}/_matrix/media/r0/thumbnail/exampleserver.abc/abcdefghijklmn?width=50&height=50&method=crop');
|
||||
expect(
|
||||
content.getThumbnail(client,
|
||||
width: 50, height: 50, method: ThumbnailMethod.scale),
|
||||
"${client.homeserver}/_matrix/media/r0/thumbnail/exampleserver.abc/abcdefghijklmn?width=50&height=50&method=scale");
|
||||
'${client.homeserver}/_matrix/media/r0/thumbnail/exampleserver.abc/abcdefghijklmn?width=50&height=50&method=scale');
|
||||
});
|
||||
test("Not crashing if null", () async {
|
||||
Client client = Client("testclient");
|
||||
test('Not crashing if null', () async {
|
||||
var client = Client('testclient');
|
||||
client.httpClient = FakeMatrixApi();
|
||||
await client.checkServer("https://fakeserver.notexisting");
|
||||
final MxContent content = MxContent(null);
|
||||
await client.checkServer('https://fakeserver.notexisting');
|
||||
final content = MxContent(null);
|
||||
expect(content.getDownloadLink(client),
|
||||
"${client.homeserver}/_matrix/media/r0/download/");
|
||||
'${client.homeserver}/_matrix/media/r0/download/');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
@ -26,26 +26,26 @@ import 'package:test/test.dart';
|
|||
|
||||
void main() {
|
||||
/// All Tests related to the ChatTime
|
||||
group("Presence", () {
|
||||
test("fromJson", () async {
|
||||
Map<String, dynamic> rawPresence = {
|
||||
"content": {
|
||||
"avatar_url": "mxc://localhost:wefuiwegh8742w",
|
||||
"currently_active": false,
|
||||
"last_active_ago": 2478593,
|
||||
"presence": "online",
|
||||
"status_msg": "Making cupcakes"
|
||||
group('Presence', () {
|
||||
test('fromJson', () async {
|
||||
var rawPresence = <String, dynamic>{
|
||||
'content': {
|
||||
'avatar_url': 'mxc://localhost:wefuiwegh8742w',
|
||||
'currently_active': false,
|
||||
'last_active_ago': 2478593,
|
||||
'presence': 'online',
|
||||
'status_msg': 'Making cupcakes'
|
||||
},
|
||||
"sender": "@example:localhost",
|
||||
"type": "m.presence"
|
||||
'sender': '@example:localhost',
|
||||
'type': 'm.presence'
|
||||
};
|
||||
Presence presence = Presence.fromJson(rawPresence);
|
||||
expect(presence.sender, "@example:localhost");
|
||||
expect(presence.avatarUrl.mxc, "mxc://localhost:wefuiwegh8742w");
|
||||
var presence = Presence.fromJson(rawPresence);
|
||||
expect(presence.sender, '@example:localhost');
|
||||
expect(presence.avatarUrl.mxc, 'mxc://localhost:wefuiwegh8742w');
|
||||
expect(presence.currentlyActive, false);
|
||||
expect(presence.lastActiveAgo, 2478593);
|
||||
expect(presence.presence, PresenceType.online);
|
||||
expect(presence.statusMsg, "Making cupcakes");
|
||||
expect(presence.statusMsg, 'Making cupcakes');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
@ -26,154 +26,154 @@ import 'package:test/test.dart';
|
|||
|
||||
void main() {
|
||||
/// All Tests related to the MxContent
|
||||
group("PushRules", () {
|
||||
test("Create", () async {
|
||||
final Map<String, dynamic> json = {
|
||||
"global": {
|
||||
"content": [
|
||||
group('PushRules', () {
|
||||
test('Create', () async {
|
||||
final json = {
|
||||
'global': {
|
||||
'content': [
|
||||
{
|
||||
"actions": [
|
||||
"notify",
|
||||
{"set_tweak": "sound", "value": "default"},
|
||||
{"set_tweak": "highlight"}
|
||||
'actions': [
|
||||
'notify',
|
||||
{'set_tweak': 'sound', 'value': 'default'},
|
||||
{'set_tweak': 'highlight'}
|
||||
],
|
||||
"default": true,
|
||||
"enabled": true,
|
||||
"pattern": "alice",
|
||||
"rule_id": ".m.rule.contains_user_name"
|
||||
'default': true,
|
||||
'enabled': true,
|
||||
'pattern': 'alice',
|
||||
'rule_id': '.m.rule.contains_user_name'
|
||||
}
|
||||
],
|
||||
"override": [
|
||||
'override': [
|
||||
{
|
||||
"actions": ["dont_notify"],
|
||||
"conditions": [],
|
||||
"default": true,
|
||||
"enabled": false,
|
||||
"rule_id": ".m.rule.master"
|
||||
'actions': ['dont_notify'],
|
||||
'conditions': [],
|
||||
'default': true,
|
||||
'enabled': false,
|
||||
'rule_id': '.m.rule.master'
|
||||
},
|
||||
{
|
||||
"actions": ["dont_notify"],
|
||||
"conditions": [
|
||||
'actions': ['dont_notify'],
|
||||
'conditions': [
|
||||
{
|
||||
"key": "content.msgtype",
|
||||
"kind": "event_match",
|
||||
"pattern": "m.notice"
|
||||
'key': 'content.msgtype',
|
||||
'kind': 'event_match',
|
||||
'pattern': 'm.notice'
|
||||
}
|
||||
],
|
||||
"default": true,
|
||||
"enabled": true,
|
||||
"rule_id": ".m.rule.suppress_notices"
|
||||
'default': true,
|
||||
'enabled': true,
|
||||
'rule_id': '.m.rule.suppress_notices'
|
||||
}
|
||||
],
|
||||
"room": [],
|
||||
"sender": [],
|
||||
"underride": [
|
||||
'room': [],
|
||||
'sender': [],
|
||||
'underride': [
|
||||
{
|
||||
"actions": [
|
||||
"notify",
|
||||
{"set_tweak": "sound", "value": "ring"},
|
||||
{"set_tweak": "highlight", "value": false}
|
||||
'actions': [
|
||||
'notify',
|
||||
{'set_tweak': 'sound', 'value': 'ring'},
|
||||
{'set_tweak': 'highlight', 'value': false}
|
||||
],
|
||||
"conditions": [
|
||||
'conditions': [
|
||||
{
|
||||
"key": "type",
|
||||
"kind": "event_match",
|
||||
"pattern": "m.call.invite"
|
||||
'key': 'type',
|
||||
'kind': 'event_match',
|
||||
'pattern': 'm.call.invite'
|
||||
}
|
||||
],
|
||||
"default": true,
|
||||
"enabled": true,
|
||||
"rule_id": ".m.rule.call"
|
||||
'default': true,
|
||||
'enabled': true,
|
||||
'rule_id': '.m.rule.call'
|
||||
},
|
||||
{
|
||||
"actions": [
|
||||
"notify",
|
||||
{"set_tweak": "sound", "value": "default"},
|
||||
{"set_tweak": "highlight"}
|
||||
'actions': [
|
||||
'notify',
|
||||
{'set_tweak': 'sound', 'value': 'default'},
|
||||
{'set_tweak': 'highlight'}
|
||||
],
|
||||
"conditions": [
|
||||
{"kind": "contains_display_name"}
|
||||
'conditions': [
|
||||
{'kind': 'contains_display_name'}
|
||||
],
|
||||
"default": true,
|
||||
"enabled": true,
|
||||
"rule_id": ".m.rule.contains_display_name"
|
||||
'default': true,
|
||||
'enabled': true,
|
||||
'rule_id': '.m.rule.contains_display_name'
|
||||
},
|
||||
{
|
||||
"actions": [
|
||||
"notify",
|
||||
{"set_tweak": "sound", "value": "default"},
|
||||
{"set_tweak": "highlight", "value": false}
|
||||
'actions': [
|
||||
'notify',
|
||||
{'set_tweak': 'sound', 'value': 'default'},
|
||||
{'set_tweak': 'highlight', 'value': false}
|
||||
],
|
||||
"conditions": [
|
||||
{"kind": "room_member_count", "is": "2"},
|
||||
'conditions': [
|
||||
{'kind': 'room_member_count', 'is': '2'},
|
||||
{
|
||||
"kind": "event_match",
|
||||
"key": "type",
|
||||
"pattern": "m.room.message"
|
||||
'kind': 'event_match',
|
||||
'key': 'type',
|
||||
'pattern': 'm.room.message'
|
||||
}
|
||||
],
|
||||
"default": true,
|
||||
"enabled": true,
|
||||
"rule_id": ".m.rule.room_one_to_one"
|
||||
'default': true,
|
||||
'enabled': true,
|
||||
'rule_id': '.m.rule.room_one_to_one'
|
||||
},
|
||||
{
|
||||
"actions": [
|
||||
"notify",
|
||||
{"set_tweak": "sound", "value": "default"},
|
||||
{"set_tweak": "highlight", "value": false}
|
||||
'actions': [
|
||||
'notify',
|
||||
{'set_tweak': 'sound', 'value': 'default'},
|
||||
{'set_tweak': 'highlight', 'value': false}
|
||||
],
|
||||
"conditions": [
|
||||
'conditions': [
|
||||
{
|
||||
"key": "type",
|
||||
"kind": "event_match",
|
||||
"pattern": "m.room.member"
|
||||
'key': 'type',
|
||||
'kind': 'event_match',
|
||||
'pattern': 'm.room.member'
|
||||
},
|
||||
{
|
||||
"key": "content.membership",
|
||||
"kind": "event_match",
|
||||
"pattern": "invite"
|
||||
'key': 'content.membership',
|
||||
'kind': 'event_match',
|
||||
'pattern': 'invite'
|
||||
},
|
||||
{
|
||||
"key": "state_key",
|
||||
"kind": "event_match",
|
||||
"pattern": "@alice:example.com"
|
||||
'key': 'state_key',
|
||||
'kind': 'event_match',
|
||||
'pattern': '@alice:example.com'
|
||||
}
|
||||
],
|
||||
"default": true,
|
||||
"enabled": true,
|
||||
"rule_id": ".m.rule.invite_for_me"
|
||||
'default': true,
|
||||
'enabled': true,
|
||||
'rule_id': '.m.rule.invite_for_me'
|
||||
},
|
||||
{
|
||||
"actions": [
|
||||
"notify",
|
||||
{"set_tweak": "highlight", "value": false}
|
||||
'actions': [
|
||||
'notify',
|
||||
{'set_tweak': 'highlight', 'value': false}
|
||||
],
|
||||
"conditions": [
|
||||
'conditions': [
|
||||
{
|
||||
"key": "type",
|
||||
"kind": "event_match",
|
||||
"pattern": "m.room.member"
|
||||
'key': 'type',
|
||||
'kind': 'event_match',
|
||||
'pattern': 'm.room.member'
|
||||
}
|
||||
],
|
||||
"default": true,
|
||||
"enabled": true,
|
||||
"rule_id": ".m.rule.member_event"
|
||||
'default': true,
|
||||
'enabled': true,
|
||||
'rule_id': '.m.rule.member_event'
|
||||
},
|
||||
{
|
||||
"actions": [
|
||||
"notify",
|
||||
{"set_tweak": "highlight", "value": false}
|
||||
'actions': [
|
||||
'notify',
|
||||
{'set_tweak': 'highlight', 'value': false}
|
||||
],
|
||||
"conditions": [
|
||||
'conditions': [
|
||||
{
|
||||
"key": "type",
|
||||
"kind": "event_match",
|
||||
"pattern": "m.room.message"
|
||||
'key': 'type',
|
||||
'kind': 'event_match',
|
||||
'pattern': 'm.room.message'
|
||||
}
|
||||
],
|
||||
"default": true,
|
||||
"enabled": true,
|
||||
"rule_id": ".m.rule.message"
|
||||
'default': true,
|
||||
'enabled': true,
|
||||
'rule_id': '.m.rule.message'
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
@ -29,39 +29,39 @@ import 'fake_store.dart';
|
|||
|
||||
void main() {
|
||||
/// All Tests related to device keys
|
||||
group("Room Key Request", () {
|
||||
test("fromJson", () async {
|
||||
Map<String, dynamic> rawJson = {
|
||||
"content": {
|
||||
"action": "request",
|
||||
"body": {
|
||||
"algorithm": "m.megolm.v1.aes-sha2",
|
||||
"room_id": "!726s6s6q:example.com",
|
||||
"sender_key": "RF3s+E7RkTQTGF2d8Deol0FkQvgII2aJDf3/Jp5mxVU",
|
||||
"session_id": "X3lUlvLELLYxeTx4yOVu6UDpasGEVO0Jbu+QFnm0cKQ"
|
||||
group('Room Key Request', () {
|
||||
test('fromJson', () async {
|
||||
var rawJson = <String, dynamic>{
|
||||
'content': {
|
||||
'action': 'request',
|
||||
'body': {
|
||||
'algorithm': 'm.megolm.v1.aes-sha2',
|
||||
'room_id': '!726s6s6q:example.com',
|
||||
'sender_key': 'RF3s+E7RkTQTGF2d8Deol0FkQvgII2aJDf3/Jp5mxVU',
|
||||
'session_id': 'X3lUlvLELLYxeTx4yOVu6UDpasGEVO0Jbu+QFnm0cKQ'
|
||||
},
|
||||
"request_id": "1495474790150.19",
|
||||
"requesting_device_id": "JLAFKJWSCS"
|
||||
'request_id': '1495474790150.19',
|
||||
'requesting_device_id': 'JLAFKJWSCS'
|
||||
},
|
||||
"type": "m.room_key_request",
|
||||
"sender": "@alice:example.com"
|
||||
'type': 'm.room_key_request',
|
||||
'sender': '@alice:example.com'
|
||||
};
|
||||
ToDeviceEvent toDeviceEvent = ToDeviceEvent.fromJson(rawJson);
|
||||
expect(toDeviceEvent.content, rawJson["content"]);
|
||||
expect(toDeviceEvent.sender, rawJson["sender"]);
|
||||
expect(toDeviceEvent.type, rawJson["type"]);
|
||||
var toDeviceEvent = ToDeviceEvent.fromJson(rawJson);
|
||||
expect(toDeviceEvent.content, rawJson['content']);
|
||||
expect(toDeviceEvent.sender, rawJson['sender']);
|
||||
expect(toDeviceEvent.type, rawJson['type']);
|
||||
|
||||
Client matrix = Client("testclient", debug: true);
|
||||
var matrix = Client('testclient', debug: true);
|
||||
matrix.httpClient = FakeMatrixApi();
|
||||
matrix.storeAPI = FakeStore(matrix, {});
|
||||
await matrix.checkServer("https://fakeServer.notExisting");
|
||||
await matrix.login("test", "1234");
|
||||
Room room = matrix.getRoomById("!726s6s6q:example.com");
|
||||
await matrix.checkServer('https://fakeServer.notExisting');
|
||||
await matrix.login('test', '1234');
|
||||
var room = matrix.getRoomById('!726s6s6q:example.com');
|
||||
if (matrix.encryptionEnabled) {
|
||||
await room.createOutboundGroupSession();
|
||||
rawJson["content"]["body"]["session_id"] = room.sessionKeys.keys.first;
|
||||
rawJson['content']['body']['session_id'] = room.sessionKeys.keys.first;
|
||||
|
||||
RoomKeyRequest roomKeyRequest = RoomKeyRequest.fromToDeviceEvent(
|
||||
var roomKeyRequest = RoomKeyRequest.fromToDeviceEvent(
|
||||
ToDeviceEvent.fromJson(rawJson), matrix);
|
||||
await roomKeyRequest.forwardKey();
|
||||
}
|
||||
|
|
|
@ -24,7 +24,6 @@
|
|||
import 'package:famedlysdk/src/client.dart';
|
||||
import 'package:famedlysdk/src/event.dart';
|
||||
import 'package:famedlysdk/src/room.dart';
|
||||
import 'package:famedlysdk/src/timeline.dart';
|
||||
import 'package:famedlysdk/src/user.dart';
|
||||
import 'package:famedlysdk/src/utils/matrix_file.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
@ -38,61 +37,61 @@ void main() {
|
|||
Room room;
|
||||
|
||||
/// All Tests related to the Event
|
||||
group("Room", () {
|
||||
group('Room', () {
|
||||
test('Login', () async {
|
||||
matrix = Client("testclient", debug: true);
|
||||
matrix = Client('testclient', debug: true);
|
||||
matrix.httpClient = FakeMatrixApi();
|
||||
|
||||
final bool checkResp =
|
||||
await matrix.checkServer("https://fakeServer.notExisting");
|
||||
final checkResp =
|
||||
await matrix.checkServer('https://fakeServer.notExisting');
|
||||
|
||||
final bool loginResp = await matrix.login("test", "1234");
|
||||
final loginResp = await matrix.login('test', '1234');
|
||||
|
||||
expect(checkResp, true);
|
||||
expect(loginResp, true);
|
||||
});
|
||||
|
||||
test("Create from json", () async {
|
||||
final String id = "!localpart:server.abc";
|
||||
final Membership membership = Membership.join;
|
||||
final int notificationCount = 2;
|
||||
final int highlightCount = 1;
|
||||
final List<String> heroes = [
|
||||
"@alice:matrix.org",
|
||||
"@bob:example.com",
|
||||
"@charley:example.org"
|
||||
test('Create from json', () async {
|
||||
final id = '!localpart:server.abc';
|
||||
final membership = Membership.join;
|
||||
final notificationCount = 2;
|
||||
final highlightCount = 1;
|
||||
final heroes = [
|
||||
'@alice:matrix.org',
|
||||
'@bob:example.com',
|
||||
'@charley:example.org'
|
||||
];
|
||||
|
||||
Map<String, dynamic> jsonObj = {
|
||||
"room_id": id,
|
||||
"membership": membership.toString().split('.').last,
|
||||
"avatar_url": "",
|
||||
"notification_count": notificationCount,
|
||||
"highlight_count": highlightCount,
|
||||
"prev_batch": "",
|
||||
"joined_member_count": notificationCount,
|
||||
"invited_member_count": notificationCount,
|
||||
"heroes": heroes.join(","),
|
||||
var jsonObj = <String, dynamic>{
|
||||
'room_id': id,
|
||||
'membership': membership.toString().split('.').last,
|
||||
'avatar_url': '',
|
||||
'notification_count': notificationCount,
|
||||
'highlight_count': highlightCount,
|
||||
'prev_batch': '',
|
||||
'joined_member_count': notificationCount,
|
||||
'invited_member_count': notificationCount,
|
||||
'heroes': heroes.join(','),
|
||||
};
|
||||
|
||||
Function states = () async => [
|
||||
{
|
||||
"content": {"join_rule": "public"},
|
||||
"event_id": "143273582443PhrSn:example.org",
|
||||
"origin_server_ts": 1432735824653,
|
||||
"room_id": id,
|
||||
"sender": "@example:example.org",
|
||||
"state_key": "",
|
||||
"type": "m.room.join_rules",
|
||||
"unsigned": {"age": 1234}
|
||||
'content': {'join_rule': 'public'},
|
||||
'event_id': '143273582443PhrSn:example.org',
|
||||
'origin_server_ts': 1432735824653,
|
||||
'room_id': id,
|
||||
'sender': '@example:example.org',
|
||||
'state_key': '',
|
||||
'type': 'm.room.join_rules',
|
||||
'unsigned': {'age': 1234}
|
||||
}
|
||||
];
|
||||
|
||||
Function roomAccountData = () async => [
|
||||
{
|
||||
"content": {"foo": "bar"},
|
||||
"room_id": id,
|
||||
"type": "com.test.foo"
|
||||
'content': {'foo': 'bar'},
|
||||
'room_id': id,
|
||||
'type': 'com.test.foo'
|
||||
}
|
||||
];
|
||||
|
||||
|
@ -110,131 +109,131 @@ void main() {
|
|||
expect(room.mJoinedMemberCount, notificationCount);
|
||||
expect(room.mInvitedMemberCount, notificationCount);
|
||||
expect(room.mHeroes, heroes);
|
||||
expect(room.displayname, "alice, bob, charley");
|
||||
expect(room.getState("m.room.join_rules").content["join_rule"], "public");
|
||||
expect(room.roomAccountData["com.test.foo"].content["foo"], "bar");
|
||||
expect(room.displayname, 'alice, bob, charley');
|
||||
expect(room.getState('m.room.join_rules').content['join_rule'], 'public');
|
||||
expect(room.roomAccountData['com.test.foo'].content['foo'], 'bar');
|
||||
|
||||
room.states["m.room.canonical_alias"] = Event(
|
||||
senderId: "@test:example.com",
|
||||
typeKey: "m.room.canonical_alias",
|
||||
room.states['m.room.canonical_alias'] = Event(
|
||||
senderId: '@test:example.com',
|
||||
typeKey: 'm.room.canonical_alias',
|
||||
roomId: room.id,
|
||||
room: room,
|
||||
eventId: "123",
|
||||
content: {"alias": "#testalias:example.com"},
|
||||
stateKey: "");
|
||||
expect(room.displayname, "testalias");
|
||||
expect(room.canonicalAlias, "#testalias:example.com");
|
||||
eventId: '123',
|
||||
content: {'alias': '#testalias:example.com'},
|
||||
stateKey: '');
|
||||
expect(room.displayname, 'testalias');
|
||||
expect(room.canonicalAlias, '#testalias:example.com');
|
||||
|
||||
room.states["m.room.name"] = Event(
|
||||
senderId: "@test:example.com",
|
||||
typeKey: "m.room.name",
|
||||
room.states['m.room.name'] = Event(
|
||||
senderId: '@test:example.com',
|
||||
typeKey: 'm.room.name',
|
||||
roomId: room.id,
|
||||
room: room,
|
||||
eventId: "123",
|
||||
content: {"name": "testname"},
|
||||
stateKey: "");
|
||||
expect(room.displayname, "testname");
|
||||
eventId: '123',
|
||||
content: {'name': 'testname'},
|
||||
stateKey: '');
|
||||
expect(room.displayname, 'testname');
|
||||
|
||||
expect(room.topic, "");
|
||||
room.states["m.room.topic"] = Event(
|
||||
senderId: "@test:example.com",
|
||||
typeKey: "m.room.topic",
|
||||
expect(room.topic, '');
|
||||
room.states['m.room.topic'] = Event(
|
||||
senderId: '@test:example.com',
|
||||
typeKey: 'm.room.topic',
|
||||
roomId: room.id,
|
||||
room: room,
|
||||
eventId: "123",
|
||||
content: {"topic": "testtopic"},
|
||||
stateKey: "");
|
||||
expect(room.topic, "testtopic");
|
||||
eventId: '123',
|
||||
content: {'topic': 'testtopic'},
|
||||
stateKey: '');
|
||||
expect(room.topic, 'testtopic');
|
||||
|
||||
expect(room.avatar.mxc, "");
|
||||
room.states["m.room.avatar"] = Event(
|
||||
senderId: "@test:example.com",
|
||||
typeKey: "m.room.avatar",
|
||||
expect(room.avatar.mxc, '');
|
||||
room.states['m.room.avatar'] = Event(
|
||||
senderId: '@test:example.com',
|
||||
typeKey: 'm.room.avatar',
|
||||
roomId: room.id,
|
||||
room: room,
|
||||
eventId: "123",
|
||||
content: {"url": "mxc://testurl"},
|
||||
stateKey: "");
|
||||
expect(room.avatar.mxc, "mxc://testurl");
|
||||
room.states["m.room.message"] = Event(
|
||||
senderId: "@test:example.com",
|
||||
typeKey: "m.room.message",
|
||||
eventId: '123',
|
||||
content: {'url': 'mxc://testurl'},
|
||||
stateKey: '');
|
||||
expect(room.avatar.mxc, 'mxc://testurl');
|
||||
room.states['m.room.message'] = Event(
|
||||
senderId: '@test:example.com',
|
||||
typeKey: 'm.room.message',
|
||||
roomId: room.id,
|
||||
room: room,
|
||||
eventId: "12345",
|
||||
eventId: '12345',
|
||||
time: DateTime.now(),
|
||||
content: {"msgtype": "m.text", "body": "test"},
|
||||
stateKey: "");
|
||||
expect(room.lastEvent.eventId, "12345");
|
||||
expect(room.lastMessage, "test");
|
||||
content: {'msgtype': 'm.text', 'body': 'test'},
|
||||
stateKey: '');
|
||||
expect(room.lastEvent.eventId, '12345');
|
||||
expect(room.lastMessage, 'test');
|
||||
expect(room.timeCreated, room.lastEvent.time);
|
||||
});
|
||||
|
||||
test("sendReadReceipt", () async {
|
||||
await room.sendReadReceipt("§1234:fakeServer.notExisting");
|
||||
test('sendReadReceipt', () async {
|
||||
await room.sendReadReceipt('§1234:fakeServer.notExisting');
|
||||
});
|
||||
|
||||
test("requestParticipants", () async {
|
||||
final List<User> participants = await room.requestParticipants();
|
||||
test('requestParticipants', () async {
|
||||
final participants = await room.requestParticipants();
|
||||
expect(participants.length, 1);
|
||||
User user = participants[0];
|
||||
expect(user.id, "@alice:example.org");
|
||||
expect(user.displayName, "Alice Margatroid");
|
||||
var user = participants[0];
|
||||
expect(user.id, '@alice:example.org');
|
||||
expect(user.displayName, 'Alice Margatroid');
|
||||
expect(user.membership, Membership.join);
|
||||
expect(user.avatarUrl.mxc, "mxc://example.org/SEsfnsuifSDFSSEF");
|
||||
expect(user.room.id, "!localpart:server.abc");
|
||||
expect(user.avatarUrl.mxc, 'mxc://example.org/SEsfnsuifSDFSSEF');
|
||||
expect(user.room.id, '!localpart:server.abc');
|
||||
});
|
||||
|
||||
test("getEventByID", () async {
|
||||
final Event event = await room.getEventById("1234");
|
||||
expect(event.eventId, "143273582443PhrSn:example.org");
|
||||
test('getEventByID', () async {
|
||||
final event = await room.getEventById('1234');
|
||||
expect(event.eventId, '143273582443PhrSn:example.org');
|
||||
});
|
||||
|
||||
test("setName", () async {
|
||||
final String eventId = await room.setName("Testname");
|
||||
expect(eventId, "42");
|
||||
test('setName', () async {
|
||||
final eventId = await room.setName('Testname');
|
||||
expect(eventId, '42');
|
||||
});
|
||||
|
||||
test("setDescription", () async {
|
||||
final String eventId = await room.setDescription("Testname");
|
||||
expect(eventId, "42");
|
||||
test('setDescription', () async {
|
||||
final eventId = await room.setDescription('Testname');
|
||||
expect(eventId, '42');
|
||||
});
|
||||
|
||||
test("kick", () async {
|
||||
await room.kick("Testname");
|
||||
test('kick', () async {
|
||||
await room.kick('Testname');
|
||||
});
|
||||
|
||||
test("ban", () async {
|
||||
await room.ban("Testname");
|
||||
test('ban', () async {
|
||||
await room.ban('Testname');
|
||||
});
|
||||
|
||||
test("unban", () async {
|
||||
await room.unban("Testname");
|
||||
test('unban', () async {
|
||||
await room.unban('Testname');
|
||||
});
|
||||
|
||||
test("PowerLevels", () async {
|
||||
room.states["m.room.power_levels"] = Event(
|
||||
senderId: "@test:example.com",
|
||||
typeKey: "m.room.power_levels",
|
||||
test('PowerLevels', () async {
|
||||
room.states['m.room.power_levels'] = Event(
|
||||
senderId: '@test:example.com',
|
||||
typeKey: 'm.room.power_levels',
|
||||
roomId: room.id,
|
||||
room: room,
|
||||
eventId: "123",
|
||||
eventId: '123',
|
||||
content: {
|
||||
"ban": 50,
|
||||
"events": {"m.room.name": 100, "m.room.power_levels": 100},
|
||||
"events_default": 0,
|
||||
"invite": 50,
|
||||
"kick": 50,
|
||||
"notifications": {"room": 20},
|
||||
"redact": 50,
|
||||
"state_default": 50,
|
||||
"users": {"@test:fakeServer.notExisting": 100},
|
||||
"users_default": 10
|
||||
'ban': 50,
|
||||
'events': {'m.room.name': 100, 'm.room.power_levels': 100},
|
||||
'events_default': 0,
|
||||
'invite': 50,
|
||||
'kick': 50,
|
||||
'notifications': {'room': 20},
|
||||
'redact': 50,
|
||||
'state_default': 50,
|
||||
'users': {'@test:fakeServer.notExisting': 100},
|
||||
'users_default': 10
|
||||
},
|
||||
stateKey: "");
|
||||
stateKey: '');
|
||||
expect(room.ownPowerLevel, 100);
|
||||
expect(room.getPowerLevelByUserId(matrix.userID), room.ownPowerLevel);
|
||||
expect(room.getPowerLevelByUserId("@nouser:example.com"), 10);
|
||||
expect(room.getPowerLevelByUserId('@nouser:example.com'), 10);
|
||||
expect(room.ownPowerLevel, 100);
|
||||
expect(room.canBan, true);
|
||||
expect(room.canInvite, true);
|
||||
|
@ -243,31 +242,31 @@ void main() {
|
|||
expect(room.canSendDefaultMessages, true);
|
||||
expect(room.canSendDefaultStates, true);
|
||||
expect(room.canChangePowerLevel, true);
|
||||
expect(room.canSendEvent("m.room.name"), true);
|
||||
expect(room.canSendEvent("m.room.power_levels"), true);
|
||||
expect(room.canSendEvent("m.room.member"), true);
|
||||
expect(room.canSendEvent('m.room.name'), true);
|
||||
expect(room.canSendEvent('m.room.power_levels'), true);
|
||||
expect(room.canSendEvent('m.room.member'), true);
|
||||
expect(room.powerLevels,
|
||||
room.states["m.room.power_levels"].content["users"]);
|
||||
room.states['m.room.power_levels'].content['users']);
|
||||
|
||||
room.states["m.room.power_levels"] = Event(
|
||||
senderId: "@test:example.com",
|
||||
typeKey: "m.room.power_levels",
|
||||
room.states['m.room.power_levels'] = Event(
|
||||
senderId: '@test:example.com',
|
||||
typeKey: 'm.room.power_levels',
|
||||
roomId: room.id,
|
||||
room: room,
|
||||
eventId: "123abc",
|
||||
eventId: '123abc',
|
||||
content: {
|
||||
"ban": 50,
|
||||
"events": {"m.room.name": 0, "m.room.power_levels": 100},
|
||||
"events_default": 0,
|
||||
"invite": 50,
|
||||
"kick": 50,
|
||||
"notifications": {"room": 20},
|
||||
"redact": 50,
|
||||
"state_default": 50,
|
||||
"users": {},
|
||||
"users_default": 0
|
||||
'ban': 50,
|
||||
'events': {'m.room.name': 0, 'm.room.power_levels': 100},
|
||||
'events_default': 0,
|
||||
'invite': 50,
|
||||
'kick': 50,
|
||||
'notifications': {'room': 20},
|
||||
'redact': 50,
|
||||
'state_default': 50,
|
||||
'users': {},
|
||||
'users_default': 0
|
||||
},
|
||||
stateKey: "");
|
||||
stateKey: '');
|
||||
expect(room.ownPowerLevel, 0);
|
||||
expect(room.canBan, false);
|
||||
expect(room.canInvite, false);
|
||||
|
@ -276,70 +275,69 @@ void main() {
|
|||
expect(room.canSendDefaultMessages, true);
|
||||
expect(room.canSendDefaultStates, false);
|
||||
expect(room.canChangePowerLevel, false);
|
||||
expect(room.canSendEvent("m.room.name"), true);
|
||||
expect(room.canSendEvent("m.room.power_levels"), false);
|
||||
expect(room.canSendEvent("m.room.member"), false);
|
||||
expect(room.canSendEvent("m.room.message"), true);
|
||||
final String resp =
|
||||
await room.setPower("@test:fakeServer.notExisting", 90);
|
||||
expect(resp, "42");
|
||||
expect(room.canSendEvent('m.room.name'), true);
|
||||
expect(room.canSendEvent('m.room.power_levels'), false);
|
||||
expect(room.canSendEvent('m.room.member'), false);
|
||||
expect(room.canSendEvent('m.room.message'), true);
|
||||
final resp = await room.setPower('@test:fakeServer.notExisting', 90);
|
||||
expect(resp, '42');
|
||||
});
|
||||
|
||||
test("invite", () async {
|
||||
await room.invite("Testname");
|
||||
test('invite', () async {
|
||||
await room.invite('Testname');
|
||||
});
|
||||
|
||||
test("getParticipants", () async {
|
||||
test('getParticipants', () async {
|
||||
room.setState(Event(
|
||||
senderId: "@alice:test.abc",
|
||||
typeKey: "m.room.member",
|
||||
senderId: '@alice:test.abc',
|
||||
typeKey: 'm.room.member',
|
||||
roomId: room.id,
|
||||
room: room,
|
||||
eventId: "12345",
|
||||
eventId: '12345',
|
||||
time: DateTime.now(),
|
||||
content: {"displayname": "alice"},
|
||||
stateKey: "@alice:test.abc"));
|
||||
final List<User> userList = room.getParticipants();
|
||||
content: {'displayname': 'alice'},
|
||||
stateKey: '@alice:test.abc'));
|
||||
final userList = room.getParticipants();
|
||||
expect(userList.length, 5);
|
||||
expect(userList[3].displayName, "Alice Margatroid");
|
||||
expect(userList[3].displayName, 'Alice Margatroid');
|
||||
});
|
||||
|
||||
test("addToDirectChat", () async {
|
||||
await room.addToDirectChat("Testname");
|
||||
test('addToDirectChat', () async {
|
||||
await room.addToDirectChat('Testname');
|
||||
});
|
||||
|
||||
test("getTimeline", () async {
|
||||
final Timeline timeline = await room.getTimeline();
|
||||
test('getTimeline', () async {
|
||||
final timeline = await room.getTimeline();
|
||||
expect(timeline.events, []);
|
||||
});
|
||||
|
||||
test("getUserByMXID", () async {
|
||||
test('getUserByMXID', () async {
|
||||
User user;
|
||||
try {
|
||||
user = await room.getUserByMXID("@getme:example.com");
|
||||
user = await room.getUserByMXID('@getme:example.com');
|
||||
} catch (_) {}
|
||||
expect(user.stateKey, "@getme:example.com");
|
||||
expect(user.calcDisplayname(), "You got me");
|
||||
expect(user.stateKey, '@getme:example.com');
|
||||
expect(user.calcDisplayname(), 'You got me');
|
||||
});
|
||||
|
||||
test('setAvatar', () async {
|
||||
final MatrixFile testFile =
|
||||
MatrixFile(bytes: Uint8List(0), path: "fake/path/file.jpeg");
|
||||
final testFile =
|
||||
MatrixFile(bytes: Uint8List(0), path: 'fake/path/file.jpeg');
|
||||
final dynamic resp = await room.setAvatar(testFile);
|
||||
expect(resp, "YUwRidLecu:example.com");
|
||||
expect(resp, 'YUwRidLecu:example.com');
|
||||
});
|
||||
|
||||
test('sendEvent', () async {
|
||||
final dynamic resp = await room.sendEvent(
|
||||
{"msgtype": "m.text", "body": "hello world"},
|
||||
txid: "testtxid");
|
||||
expect(resp, "42");
|
||||
{'msgtype': 'm.text', 'body': 'hello world'},
|
||||
txid: 'testtxid');
|
||||
expect(resp, '42');
|
||||
});
|
||||
|
||||
test('sendEvent', () async {
|
||||
final dynamic resp =
|
||||
await room.sendTextEvent("Hello world", txid: "testtxid");
|
||||
expect(resp, "42");
|
||||
await room.sendTextEvent('Hello world', txid: 'testtxid');
|
||||
expect(resp, '42');
|
||||
});
|
||||
|
||||
// Not working because there is no real file to test it...
|
||||
|
@ -351,38 +349,38 @@ void main() {
|
|||
});*/
|
||||
|
||||
test('sendFileEvent', () async {
|
||||
final MatrixFile testFile =
|
||||
MatrixFile(bytes: Uint8List(0), path: "fake/path/file.jpeg");
|
||||
final testFile =
|
||||
MatrixFile(bytes: Uint8List(0), path: 'fake/path/file.jpeg');
|
||||
final dynamic resp = await room.sendFileEvent(testFile,
|
||||
msgType: "m.file", txid: "testtxid");
|
||||
expect(resp, "mxc://example.com/AQwafuaFswefuhsfAFAgsw");
|
||||
msgType: 'm.file', txid: 'testtxid');
|
||||
expect(resp, 'mxc://example.com/AQwafuaFswefuhsfAFAgsw');
|
||||
});
|
||||
|
||||
test('pushRuleState', () async {
|
||||
expect(room.pushRuleState, PushRuleState.mentions_only);
|
||||
matrix.accountData["m.push_rules"].content["global"]["override"]
|
||||
.add(matrix.accountData["m.push_rules"].content["global"]["room"][0]);
|
||||
matrix.accountData['m.push_rules'].content['global']['override']
|
||||
.add(matrix.accountData['m.push_rules'].content['global']['room'][0]);
|
||||
expect(room.pushRuleState, PushRuleState.dont_notify);
|
||||
});
|
||||
|
||||
test('Enable encryption', () async {
|
||||
room.setState(
|
||||
Event(
|
||||
senderId: "@alice:test.abc",
|
||||
typeKey: "m.room.encryption",
|
||||
senderId: '@alice:test.abc',
|
||||
typeKey: 'm.room.encryption',
|
||||
roomId: room.id,
|
||||
room: room,
|
||||
eventId: "12345",
|
||||
eventId: '12345',
|
||||
time: DateTime.now(),
|
||||
content: {
|
||||
"algorithm": "m.megolm.v1.aes-sha2",
|
||||
"rotation_period_ms": 604800000,
|
||||
"rotation_period_msgs": 100
|
||||
'algorithm': 'm.megolm.v1.aes-sha2',
|
||||
'rotation_period_ms': 604800000,
|
||||
'rotation_period_msgs': 100
|
||||
},
|
||||
stateKey: ""),
|
||||
stateKey: ''),
|
||||
);
|
||||
expect(room.encrypted, true);
|
||||
expect(room.encryptionAlgorithm, "m.megolm.v1.aes-sha2");
|
||||
expect(room.encryptionAlgorithm, 'm.megolm.v1.aes-sha2');
|
||||
expect(room.outboundGroupSession, null);
|
||||
});
|
||||
|
||||
|
@ -396,7 +394,7 @@ void main() {
|
|||
true);
|
||||
expect(
|
||||
room.sessionKeys[room.outboundGroupSession.session_id()]
|
||||
.content["session_key"],
|
||||
.content['session_key'],
|
||||
room.outboundGroupSession.session_key());
|
||||
expect(
|
||||
room.sessionKeys[room.outboundGroupSession.session_id()].indexes
|
||||
|
@ -412,30 +410,29 @@ void main() {
|
|||
|
||||
test('encryptGroupMessagePayload and decryptGroupMessage', () async {
|
||||
if (!room.client.encryptionEnabled) return;
|
||||
final Map<String, dynamic> payload = {
|
||||
"msgtype": "m.text",
|
||||
"body": "Hello world",
|
||||
final payload = {
|
||||
'msgtype': 'm.text',
|
||||
'body': 'Hello world',
|
||||
};
|
||||
final Map<String, dynamic> encryptedPayload =
|
||||
await room.encryptGroupMessagePayload(payload);
|
||||
expect(encryptedPayload["algorithm"], "m.megolm.v1.aes-sha2");
|
||||
expect(encryptedPayload["ciphertext"].isNotEmpty, true);
|
||||
expect(encryptedPayload["device_id"], room.client.deviceID);
|
||||
expect(encryptedPayload["sender_key"], room.client.identityKey);
|
||||
expect(encryptedPayload["session_id"],
|
||||
final encryptedPayload = await room.encryptGroupMessagePayload(payload);
|
||||
expect(encryptedPayload['algorithm'], 'm.megolm.v1.aes-sha2');
|
||||
expect(encryptedPayload['ciphertext'].isNotEmpty, true);
|
||||
expect(encryptedPayload['device_id'], room.client.deviceID);
|
||||
expect(encryptedPayload['sender_key'], room.client.identityKey);
|
||||
expect(encryptedPayload['session_id'],
|
||||
room.outboundGroupSession.session_id());
|
||||
|
||||
Event encryptedEvent = Event(
|
||||
var encryptedEvent = Event(
|
||||
content: encryptedPayload,
|
||||
typeKey: "m.room.encrypted",
|
||||
typeKey: 'm.room.encrypted',
|
||||
senderId: room.client.userID,
|
||||
eventId: "1234",
|
||||
eventId: '1234',
|
||||
roomId: room.id,
|
||||
room: room,
|
||||
time: DateTime.now(),
|
||||
);
|
||||
Event decryptedEvent = room.decryptGroupMessage(encryptedEvent);
|
||||
expect(decryptedEvent.typeKey, "m.room.message");
|
||||
var decryptedEvent = room.decryptGroupMessage(encryptedEvent);
|
||||
expect(decryptedEvent.typeKey, 'm.room.message');
|
||||
expect(decryptedEvent.content, payload);
|
||||
});
|
||||
});
|
||||
|
|
|
@ -27,48 +27,48 @@ import 'package:famedlysdk/src/utils/states_map.dart';
|
|||
|
||||
void main() {
|
||||
/// All Tests related to the ChatTime
|
||||
group("StateKeys", () {
|
||||
test("Operator overload", () async {
|
||||
StatesMap states = StatesMap();
|
||||
states["m.room.name"] = Event(
|
||||
eventId: "1",
|
||||
content: {"name": "test"},
|
||||
typeKey: "m.room.name",
|
||||
stateKey: "",
|
||||
roomId: "!test:test.test",
|
||||
senderId: "@alice:test.test");
|
||||
group('StateKeys', () {
|
||||
test('Operator overload', () async {
|
||||
var states = StatesMap();
|
||||
states['m.room.name'] = Event(
|
||||
eventId: '1',
|
||||
content: {'name': 'test'},
|
||||
typeKey: 'm.room.name',
|
||||
stateKey: '',
|
||||
roomId: '!test:test.test',
|
||||
senderId: '@alice:test.test');
|
||||
|
||||
states["@alice:test.test"] = Event(
|
||||
eventId: "2",
|
||||
content: {"membership": "join"},
|
||||
typeKey: "m.room.name",
|
||||
stateKey: "@alice:test.test",
|
||||
roomId: "!test:test.test",
|
||||
senderId: "@alice:test.test");
|
||||
states['@alice:test.test'] = Event(
|
||||
eventId: '2',
|
||||
content: {'membership': 'join'},
|
||||
typeKey: 'm.room.name',
|
||||
stateKey: '@alice:test.test',
|
||||
roomId: '!test:test.test',
|
||||
senderId: '@alice:test.test');
|
||||
|
||||
states["m.room.member"]["@bob:test.test"] = Event(
|
||||
eventId: "3",
|
||||
content: {"membership": "join"},
|
||||
typeKey: "m.room.name",
|
||||
stateKey: "@bob:test.test",
|
||||
roomId: "!test:test.test",
|
||||
senderId: "@bob:test.test");
|
||||
states['m.room.member']['@bob:test.test'] = Event(
|
||||
eventId: '3',
|
||||
content: {'membership': 'join'},
|
||||
typeKey: 'm.room.name',
|
||||
stateKey: '@bob:test.test',
|
||||
roomId: '!test:test.test',
|
||||
senderId: '@bob:test.test');
|
||||
|
||||
states["com.test.custom"] = Event(
|
||||
eventId: "4",
|
||||
content: {"custom": "stuff"},
|
||||
typeKey: "com.test.custom",
|
||||
stateKey: "customStateKey",
|
||||
roomId: "!test:test.test",
|
||||
senderId: "@bob:test.test");
|
||||
states['com.test.custom'] = Event(
|
||||
eventId: '4',
|
||||
content: {'custom': 'stuff'},
|
||||
typeKey: 'com.test.custom',
|
||||
stateKey: 'customStateKey',
|
||||
roomId: '!test:test.test',
|
||||
senderId: '@bob:test.test');
|
||||
|
||||
expect(states["m.room.name"].eventId, "1");
|
||||
expect(states["@alice:test.test"].eventId, "2");
|
||||
expect(states["m.room.member"]["@alice:test.test"].eventId, "2");
|
||||
expect(states["@bob:test.test"].eventId, "3");
|
||||
expect(states["m.room.member"]["@bob:test.test"].eventId, "3");
|
||||
expect(states["m.room.member"].length, 2);
|
||||
expect(states["com.test.custom"]["customStateKey"].eventId, "4");
|
||||
expect(states['m.room.name'].eventId, '1');
|
||||
expect(states['@alice:test.test'].eventId, '2');
|
||||
expect(states['m.room.member']['@alice:test.test'].eventId, '2');
|
||||
expect(states['@bob:test.test'].eventId, '3');
|
||||
expect(states['m.room.member']['@bob:test.test'].eventId, '3');
|
||||
expect(states['m.room.member'].length, 2);
|
||||
expect(states['com.test.custom']['customStateKey'].eventId, '4');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
@ -31,18 +31,18 @@ import 'fake_matrix_api.dart';
|
|||
|
||||
void main() {
|
||||
/// All Tests related to the MxContent
|
||||
group("Timeline", () {
|
||||
final String roomID = "!1234:example.com";
|
||||
group('Timeline', () {
|
||||
final roomID = '!1234:example.com';
|
||||
final testTimeStamp = DateTime.now().millisecondsSinceEpoch;
|
||||
int updateCount = 0;
|
||||
List<int> insertList = [];
|
||||
var updateCount = 0;
|
||||
var insertList = <int>[];
|
||||
|
||||
Client client = Client("testclient", debug: true);
|
||||
var client = Client('testclient', debug: true);
|
||||
client.httpClient = FakeMatrixApi();
|
||||
|
||||
Room room = Room(
|
||||
id: roomID, client: client, prev_batch: "1234", roomAccountData: {});
|
||||
Timeline timeline = Timeline(
|
||||
var room = Room(
|
||||
id: roomID, client: client, prev_batch: '1234', roomAccountData: {});
|
||||
var timeline = Timeline(
|
||||
room: room,
|
||||
events: [],
|
||||
onUpdate: () {
|
||||
|
@ -52,32 +52,32 @@ void main() {
|
|||
insertList.add(insertID);
|
||||
});
|
||||
|
||||
test("Create", () async {
|
||||
await client.checkServer("https://fakeServer.notExisting");
|
||||
test('Create', () async {
|
||||
await client.checkServer('https://fakeServer.notExisting');
|
||||
client.onEvent.add(EventUpdate(
|
||||
type: "timeline",
|
||||
type: 'timeline',
|
||||
roomID: roomID,
|
||||
eventType: "m.room.message",
|
||||
eventType: 'm.room.message',
|
||||
content: {
|
||||
"type": "m.room.message",
|
||||
"content": {"msgtype": "m.text", "body": "Testcase"},
|
||||
"sender": "@alice:example.com",
|
||||
"status": 2,
|
||||
"event_id": "1",
|
||||
"origin_server_ts": testTimeStamp
|
||||
'type': 'm.room.message',
|
||||
'content': {'msgtype': 'm.text', 'body': 'Testcase'},
|
||||
'sender': '@alice:example.com',
|
||||
'status': 2,
|
||||
'event_id': '1',
|
||||
'origin_server_ts': testTimeStamp
|
||||
}));
|
||||
|
||||
client.onEvent.add(EventUpdate(
|
||||
type: "timeline",
|
||||
type: 'timeline',
|
||||
roomID: roomID,
|
||||
eventType: "m.room.message",
|
||||
eventType: 'm.room.message',
|
||||
content: {
|
||||
"type": "m.room.message",
|
||||
"content": {"msgtype": "m.text", "body": "Testcase"},
|
||||
"sender": "@alice:example.com",
|
||||
"status": 2,
|
||||
"event_id": "2",
|
||||
"origin_server_ts": testTimeStamp - 1000
|
||||
'type': 'm.room.message',
|
||||
'content': {'msgtype': 'm.text', 'body': 'Testcase'},
|
||||
'sender': '@alice:example.com',
|
||||
'status': 2,
|
||||
'event_id': '2',
|
||||
'origin_server_ts': testTimeStamp - 1000
|
||||
}));
|
||||
|
||||
expect(timeline.sub != null, true);
|
||||
|
@ -88,43 +88,43 @@ void main() {
|
|||
expect(insertList, [0, 0]);
|
||||
expect(insertList.length, timeline.events.length);
|
||||
expect(timeline.events.length, 2);
|
||||
expect(timeline.events[0].eventId, "1");
|
||||
expect(timeline.events[0].sender.id, "@alice:example.com");
|
||||
expect(timeline.events[0].eventId, '1');
|
||||
expect(timeline.events[0].sender.id, '@alice:example.com');
|
||||
expect(timeline.events[0].time.millisecondsSinceEpoch, testTimeStamp);
|
||||
expect(timeline.events[0].body, "Testcase");
|
||||
expect(timeline.events[0].body, 'Testcase');
|
||||
expect(
|
||||
timeline.events[0].time.millisecondsSinceEpoch >
|
||||
timeline.events[1].time.millisecondsSinceEpoch,
|
||||
true);
|
||||
expect(timeline.events[0].receipts, []);
|
||||
|
||||
room.roomAccountData["m.receipt"] = RoomAccountData.fromJson({
|
||||
"type": "m.receipt",
|
||||
"content": {
|
||||
"@alice:example.com": {
|
||||
"event_id": "1",
|
||||
"ts": 1436451550453,
|
||||
room.roomAccountData['m.receipt'] = RoomAccountData.fromJson({
|
||||
'type': 'm.receipt',
|
||||
'content': {
|
||||
'@alice:example.com': {
|
||||
'event_id': '1',
|
||||
'ts': 1436451550453,
|
||||
}
|
||||
},
|
||||
"room_id": roomID,
|
||||
'room_id': roomID,
|
||||
}, room);
|
||||
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
|
||||
expect(timeline.events[0].receipts.length, 1);
|
||||
expect(timeline.events[0].receipts[0].user.id, "@alice:example.com");
|
||||
expect(timeline.events[0].receipts[0].user.id, '@alice:example.com');
|
||||
|
||||
client.onEvent.add(EventUpdate(
|
||||
type: "timeline",
|
||||
type: 'timeline',
|
||||
roomID: roomID,
|
||||
eventType: "m.room.redaction",
|
||||
eventType: 'm.room.redaction',
|
||||
content: {
|
||||
"type": "m.room.redaction",
|
||||
"content": {"reason": "spamming"},
|
||||
"sender": "@alice:example.com",
|
||||
"redacts": "2",
|
||||
"event_id": "3",
|
||||
"origin_server_ts": testTimeStamp + 1000
|
||||
'type': 'm.room.redaction',
|
||||
'content': {'reason': 'spamming'},
|
||||
'sender': '@alice:example.com',
|
||||
'redacts': '2',
|
||||
'event_id': '3',
|
||||
'origin_server_ts': testTimeStamp + 1000
|
||||
}));
|
||||
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
|
@ -136,29 +136,29 @@ void main() {
|
|||
expect(timeline.events[1].redacted, true);
|
||||
});
|
||||
|
||||
test("Send message", () async {
|
||||
await room.sendTextEvent("test", txid: "1234");
|
||||
test('Send message', () async {
|
||||
await room.sendTextEvent('test', txid: '1234');
|
||||
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
|
||||
expect(updateCount, 5);
|
||||
expect(insertList, [0, 0, 0]);
|
||||
expect(insertList.length, timeline.events.length);
|
||||
expect(timeline.events[0].eventId, "42");
|
||||
expect(timeline.events[0].eventId, '42');
|
||||
expect(timeline.events[0].status, 1);
|
||||
|
||||
client.onEvent.add(EventUpdate(
|
||||
type: "timeline",
|
||||
type: 'timeline',
|
||||
roomID: roomID,
|
||||
eventType: "m.room.message",
|
||||
eventType: 'm.room.message',
|
||||
content: {
|
||||
"type": "m.room.message",
|
||||
"content": {"msgtype": "m.text", "body": "test"},
|
||||
"sender": "@alice:example.com",
|
||||
"status": 2,
|
||||
"event_id": "42",
|
||||
"unsigned": {"transaction_id": "1234"},
|
||||
"origin_server_ts": DateTime.now().millisecondsSinceEpoch
|
||||
'type': 'm.room.message',
|
||||
'content': {'msgtype': 'm.text', 'body': 'test'},
|
||||
'sender': '@alice:example.com',
|
||||
'status': 2,
|
||||
'event_id': '42',
|
||||
'unsigned': {'transaction_id': '1234'},
|
||||
'origin_server_ts': DateTime.now().millisecondsSinceEpoch
|
||||
}));
|
||||
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
|
@ -166,29 +166,29 @@ void main() {
|
|||
expect(updateCount, 6);
|
||||
expect(insertList, [0, 0, 0]);
|
||||
expect(insertList.length, timeline.events.length);
|
||||
expect(timeline.events[0].eventId, "42");
|
||||
expect(timeline.events[0].eventId, '42');
|
||||
expect(timeline.events[0].status, 2);
|
||||
});
|
||||
|
||||
test("Send message with error", () async {
|
||||
test('Send message with error', () async {
|
||||
client.onEvent.add(EventUpdate(
|
||||
type: "timeline",
|
||||
type: 'timeline',
|
||||
roomID: roomID,
|
||||
eventType: "m.room.message",
|
||||
eventType: 'm.room.message',
|
||||
content: {
|
||||
"type": "m.room.message",
|
||||
"content": {"msgtype": "m.text", "body": "Testcase"},
|
||||
"sender": "@alice:example.com",
|
||||
"status": 0,
|
||||
"event_id": "abc",
|
||||
"origin_server_ts": testTimeStamp
|
||||
'type': 'm.room.message',
|
||||
'content': {'msgtype': 'm.text', 'body': 'Testcase'},
|
||||
'sender': '@alice:example.com',
|
||||
'status': 0,
|
||||
'event_id': 'abc',
|
||||
'origin_server_ts': testTimeStamp
|
||||
}));
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
await room.sendTextEvent("test", txid: "errortxid");
|
||||
await room.sendTextEvent('test', txid: 'errortxid');
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
await room.sendTextEvent("test", txid: "errortxid2");
|
||||
await room.sendTextEvent('test', txid: 'errortxid2');
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
await room.sendTextEvent("test", txid: "errortxid3");
|
||||
await room.sendTextEvent('test', txid: 'errortxid3');
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
|
||||
expect(updateCount, 13);
|
||||
|
@ -199,7 +199,7 @@ void main() {
|
|||
expect(timeline.events[2].status, -1);
|
||||
});
|
||||
|
||||
test("Remove message", () async {
|
||||
test('Remove message', () async {
|
||||
await timeline.events[0].remove();
|
||||
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
|
@ -211,8 +211,8 @@ void main() {
|
|||
expect(timeline.events[0].status, -1);
|
||||
});
|
||||
|
||||
test("Resend message", () async {
|
||||
await timeline.events[0].sendAgain(txid: "1234");
|
||||
test('Resend message', () async {
|
||||
await timeline.events[0].sendAgain(txid: '1234');
|
||||
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
|
||||
|
@ -223,17 +223,17 @@ void main() {
|
|||
expect(timeline.events[0].status, 1);
|
||||
});
|
||||
|
||||
test("Request history", () async {
|
||||
test('Request history', () async {
|
||||
await room.requestHistory();
|
||||
|
||||
await Future.delayed(Duration(milliseconds: 50));
|
||||
|
||||
expect(updateCount, 20);
|
||||
expect(timeline.events.length, 9);
|
||||
expect(timeline.events[6].eventId, "1143273582443PhrSn:example.org");
|
||||
expect(timeline.events[7].eventId, "2143273582443PhrSn:example.org");
|
||||
expect(timeline.events[8].eventId, "3143273582443PhrSn:example.org");
|
||||
expect(room.prev_batch, "t47409-4357353_219380_26003_2265");
|
||||
expect(timeline.events[6].eventId, '1143273582443PhrSn:example.org');
|
||||
expect(timeline.events[7].eventId, '2143273582443PhrSn:example.org');
|
||||
expect(timeline.events[8].eventId, '3143273582443PhrSn:example.org');
|
||||
expect(room.prev_batch, 't47409-4357353_219380_26003_2265');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
@ -27,29 +27,29 @@ import 'package:test/test.dart';
|
|||
|
||||
void main() {
|
||||
/// All Tests related to the Event
|
||||
group("User", () {
|
||||
test("Create from json", () async {
|
||||
final String id = "@alice:server.abc";
|
||||
final Membership membership = Membership.join;
|
||||
final String displayName = "Alice";
|
||||
final String avatarUrl = "";
|
||||
group('User', () {
|
||||
test('Create from json', () async {
|
||||
final id = '@alice:server.abc';
|
||||
final membership = Membership.join;
|
||||
final displayName = 'Alice';
|
||||
final avatarUrl = '';
|
||||
|
||||
final Map<String, dynamic> jsonObj = {
|
||||
"content": {
|
||||
"membership": "join",
|
||||
"avatar_url": avatarUrl,
|
||||
"displayname": displayName
|
||||
final jsonObj = {
|
||||
'content': {
|
||||
'membership': 'join',
|
||||
'avatar_url': avatarUrl,
|
||||
'displayname': displayName
|
||||
},
|
||||
"type": "m.room.member",
|
||||
"event_id": "143273582443PhrSn:example.org",
|
||||
"room_id": "!636q39766251:example.com",
|
||||
"sender": id,
|
||||
"origin_server_ts": 1432735824653,
|
||||
"unsigned": {"age": 1234},
|
||||
"state_key": id
|
||||
'type': 'm.room.member',
|
||||
'event_id': '143273582443PhrSn:example.org',
|
||||
'room_id': '!636q39766251:example.com',
|
||||
'sender': id,
|
||||
'origin_server_ts': 1432735824653,
|
||||
'unsigned': {'age': 1234},
|
||||
'state_key': id
|
||||
};
|
||||
|
||||
User user = Event.fromJson(jsonObj, null).asUser;
|
||||
var user = Event.fromJson(jsonObj, null).asUser;
|
||||
|
||||
expect(user.id, id);
|
||||
expect(user.membership, membership);
|
||||
|
@ -58,13 +58,13 @@ void main() {
|
|||
expect(user.calcDisplayname(), displayName);
|
||||
});
|
||||
|
||||
test("calcDisplayname", () async {
|
||||
final User user1 = User("@alice:example.com");
|
||||
final User user2 = User("@SuperAlice:example.com");
|
||||
final User user3 = User("@alice:example.com");
|
||||
expect(user1.calcDisplayname(), "alice");
|
||||
expect(user2.calcDisplayname(), "SuperAlice");
|
||||
expect(user3.calcDisplayname(), "alice");
|
||||
test('calcDisplayname', () async {
|
||||
final user1 = User('@alice:example.com');
|
||||
final user2 = User('@SuperAlice:example.com');
|
||||
final user3 = User('@alice:example.com');
|
||||
expect(user1.calcDisplayname(), 'alice');
|
||||
expect(user2.calcDisplayname(), 'SuperAlice');
|
||||
expect(user3.calcDisplayname(), 'alice');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
@ -3,36 +3,36 @@ import '../test/fake_store.dart';
|
|||
|
||||
void main() => test();
|
||||
|
||||
const String homeserver = "https://matrix.test.famedly.de";
|
||||
const String testUserA = "@tick:test.famedly.de";
|
||||
const String testPasswordA = "test";
|
||||
const String testUserB = "@trick:test.famedly.de";
|
||||
const String testPasswordB = "test";
|
||||
const String testMessage = "Hello world";
|
||||
const String testMessage2 = "Hello moon";
|
||||
const String testMessage3 = "Hello sun";
|
||||
const String testMessage4 = "Hello star";
|
||||
const String testMessage5 = "Hello earth";
|
||||
const String testMessage6 = "Hello mars";
|
||||
const String homeserver = 'https://matrix.test.famedly.de';
|
||||
const String testUserA = '@tick:test.famedly.de';
|
||||
const String testPasswordA = 'test';
|
||||
const String testUserB = '@trick:test.famedly.de';
|
||||
const String testPasswordB = 'test';
|
||||
const String testMessage = 'Hello world';
|
||||
const String testMessage2 = 'Hello moon';
|
||||
const String testMessage3 = 'Hello sun';
|
||||
const String testMessage4 = 'Hello star';
|
||||
const String testMessage5 = 'Hello earth';
|
||||
const String testMessage6 = 'Hello mars';
|
||||
|
||||
void test() async {
|
||||
print("++++ Login $testUserA ++++");
|
||||
Client testClientA = Client("TestClient", debug: false);
|
||||
testClientA.storeAPI = FakeStore(testClientA, Map<String, dynamic>());
|
||||
print('++++ Login $testUserA ++++');
|
||||
var testClientA = Client('TestClient', debug: false);
|
||||
testClientA.storeAPI = FakeStore(testClientA, <String, dynamic>{});
|
||||
await testClientA.checkServer(homeserver);
|
||||
await testClientA.login(testUserA, testPasswordA);
|
||||
assert(testClientA.encryptionEnabled);
|
||||
|
||||
print("++++ Login $testUserB ++++");
|
||||
Client testClientB = Client("TestClient", debug: false);
|
||||
testClientB.storeAPI = FakeStore(testClientB, Map<String, dynamic>());
|
||||
print('++++ Login $testUserB ++++');
|
||||
var testClientB = Client('TestClient', debug: false);
|
||||
testClientB.storeAPI = FakeStore(testClientB, <String, dynamic>{});
|
||||
await testClientB.checkServer(homeserver);
|
||||
await testClientB.login(testUserB, testPasswordA);
|
||||
assert(testClientB.encryptionEnabled);
|
||||
|
||||
print("++++ ($testUserA) Leave all rooms ++++");
|
||||
print('++++ ($testUserA) Leave all rooms ++++');
|
||||
while (testClientA.rooms.isNotEmpty) {
|
||||
Room room = testClientA.rooms.first;
|
||||
var room = testClientA.rooms.first;
|
||||
if (room.canonicalAlias?.isNotEmpty ?? false) {
|
||||
break;
|
||||
}
|
||||
|
@ -44,10 +44,10 @@ void test() async {
|
|||
}
|
||||
}
|
||||
|
||||
print("++++ ($testUserB) Leave all rooms ++++");
|
||||
for (int i = 0; i < 3; i++) {
|
||||
print('++++ ($testUserB) Leave all rooms ++++');
|
||||
for (var i = 0; i < 3; i++) {
|
||||
if (testClientB.rooms.isNotEmpty) {
|
||||
Room room = testClientB.rooms.first;
|
||||
var room = testClientB.rooms.first;
|
||||
try {
|
||||
await room.leave();
|
||||
await room.forget();
|
||||
|
@ -57,7 +57,7 @@ void test() async {
|
|||
}
|
||||
}
|
||||
|
||||
print("++++ Check if own olm device is verified by default ++++");
|
||||
print('++++ Check if own olm device is verified by default ++++');
|
||||
assert(testClientA.userDeviceKeys.containsKey(testUserA));
|
||||
assert(testClientA.userDeviceKeys[testUserA].deviceKeys
|
||||
.containsKey(testClientA.deviceID));
|
||||
|
@ -73,27 +73,27 @@ void test() async {
|
|||
assert(!testClientB
|
||||
.userDeviceKeys[testUserB].deviceKeys[testClientB.deviceID].blocked);
|
||||
|
||||
print("++++ ($testUserA) Create room and invite $testUserB ++++");
|
||||
print('++++ ($testUserA) Create room and invite $testUserB ++++');
|
||||
await testClientA.createRoom(invite: [User(testUserB)]);
|
||||
await Future.delayed(Duration(seconds: 1));
|
||||
Room room = testClientA.rooms.first;
|
||||
var room = testClientA.rooms.first;
|
||||
assert(room != null);
|
||||
final String roomId = room.id;
|
||||
final roomId = room.id;
|
||||
|
||||
print("++++ ($testUserB) Join room ++++");
|
||||
Room inviteRoom = testClientB.getRoomById(roomId);
|
||||
print('++++ ($testUserB) Join room ++++');
|
||||
var inviteRoom = testClientB.getRoomById(roomId);
|
||||
await inviteRoom.join();
|
||||
await Future.delayed(Duration(seconds: 1));
|
||||
assert(inviteRoom.membership == Membership.join);
|
||||
|
||||
print("++++ ($testUserA) Enable encryption ++++");
|
||||
print('++++ ($testUserA) Enable encryption ++++');
|
||||
assert(room.encrypted == false);
|
||||
await room.enableEncryption();
|
||||
await Future.delayed(Duration(seconds: 5));
|
||||
assert(room.encrypted == true);
|
||||
assert(room.outboundGroupSession == null);
|
||||
|
||||
print("++++ ($testUserA) Check known olm devices ++++");
|
||||
print('++++ ($testUserA) Check known olm devices ++++');
|
||||
assert(testClientA.userDeviceKeys.containsKey(testUserB));
|
||||
assert(testClientA.userDeviceKeys[testUserB].deviceKeys
|
||||
.containsKey(testClientB.deviceID));
|
||||
|
@ -111,7 +111,7 @@ void test() async {
|
|||
await testClientA.userDeviceKeys[testUserB].deviceKeys[testClientB.deviceID]
|
||||
.setVerified(true, testClientA);
|
||||
|
||||
print("++++ Check if own olm device is verified by default ++++");
|
||||
print('++++ Check if own olm device is verified by default ++++');
|
||||
assert(testClientA.userDeviceKeys.containsKey(testUserA));
|
||||
assert(testClientA.userDeviceKeys[testUserA].deviceKeys
|
||||
.containsKey(testClientA.deviceID));
|
||||
|
@ -127,7 +127,7 @@ void test() async {
|
|||
await room.sendTextEvent(testMessage);
|
||||
await Future.delayed(Duration(seconds: 5));
|
||||
assert(room.outboundGroupSession != null);
|
||||
String currentSessionIdA = room.outboundGroupSession.session_id();
|
||||
var currentSessionIdA = room.outboundGroupSession.session_id();
|
||||
assert(room.sessionKeys.containsKey(room.outboundGroupSession.session_id()));
|
||||
assert(testClientA.olmSessions[testClientB.identityKey].length == 1);
|
||||
assert(testClientB.olmSessions[testClientA.identityKey].length == 1);
|
||||
|
@ -172,9 +172,9 @@ void test() async {
|
|||
print(
|
||||
"++++ ($testUserA) Received decrypted message: '${room.lastMessage}' ++++");
|
||||
|
||||
print("++++ Login $testUserB in another client ++++");
|
||||
Client testClientC = Client("TestClient", debug: false);
|
||||
testClientC.storeAPI = FakeStore(testClientC, Map<String, dynamic>());
|
||||
print('++++ Login $testUserB in another client ++++');
|
||||
var testClientC = Client('TestClient', debug: false);
|
||||
testClientC.storeAPI = FakeStore(testClientC, <String, dynamic>{});
|
||||
await testClientC.checkServer(homeserver);
|
||||
await testClientC.login(testUserB, testPasswordA);
|
||||
await Future.delayed(Duration(seconds: 3));
|
||||
|
@ -200,7 +200,7 @@ void test() async {
|
|||
print(
|
||||
"++++ ($testUserB) Received decrypted message: '${inviteRoom.lastMessage}' ++++");
|
||||
|
||||
print("++++ Logout $testUserB another client ++++");
|
||||
print('++++ Logout $testUserB another client ++++');
|
||||
await testClientC.logout();
|
||||
testClientC = null;
|
||||
await Future.delayed(Duration(seconds: 5));
|
||||
|
@ -223,20 +223,20 @@ void test() async {
|
|||
print(
|
||||
"++++ ($testUserB) Received decrypted message: '${inviteRoom.lastMessage}' ++++");
|
||||
|
||||
print("++++ ($testUserA) Restore user ++++");
|
||||
print('++++ ($testUserA) Restore user ++++');
|
||||
FakeStore clientAStore = testClientA.storeAPI;
|
||||
testClientA = null;
|
||||
testClientA = Client("TestClient", debug: false);
|
||||
testClientA = Client('TestClient', debug: false);
|
||||
testClientA.storeAPI = FakeStore(testClientA, clientAStore.storeMap);
|
||||
await Future.delayed(Duration(seconds: 3));
|
||||
Room restoredRoom = testClientA.rooms.first;
|
||||
var restoredRoom = testClientA.rooms.first;
|
||||
assert(room != null);
|
||||
assert(restoredRoom.id == room.id);
|
||||
assert(restoredRoom.outboundGroupSession.session_id() ==
|
||||
room.outboundGroupSession.session_id());
|
||||
assert(restoredRoom.sessionKeys.length == 4);
|
||||
assert(restoredRoom.sessionKeys.length == room.sessionKeys.length);
|
||||
for (int i = 0; i < restoredRoom.sessionKeys.length; i++) {
|
||||
for (var i = 0; i < restoredRoom.sessionKeys.length; i++) {
|
||||
assert(restoredRoom.sessionKeys.keys.toList()[i] ==
|
||||
room.sessionKeys.keys.toList()[i]);
|
||||
}
|
||||
|
@ -261,16 +261,16 @@ void test() async {
|
|||
print(
|
||||
"++++ ($testUserB) Received decrypted message: '${inviteRoom.lastMessage}' ++++");
|
||||
|
||||
print("++++ Logout $testUserA and $testUserB ++++");
|
||||
print('++++ Logout $testUserA and $testUserB ++++');
|
||||
await room.leave();
|
||||
await room.forget();
|
||||
await inviteRoom.leave();
|
||||
await inviteRoom.forget();
|
||||
await Future.delayed(Duration(seconds: 1));
|
||||
await testClientA.jsonRequest(
|
||||
type: HTTPType.POST, action: "/client/r0/logout/all");
|
||||
type: HTTPType.POST, action: '/client/r0/logout/all');
|
||||
await testClientB.jsonRequest(
|
||||
type: HTTPType.POST, action: "/client/r0/logout/all");
|
||||
type: HTTPType.POST, action: '/client/r0/logout/all');
|
||||
testClientA = null;
|
||||
testClientB = null;
|
||||
return;
|
||||
|
|
Loading…
Reference in a new issue