Merge branch 'krille/new-logger' into 'main'

feat: Use logger package

See merge request famedly/famedlysdk!572
This commit is contained in:
Christian Pauly 2020-12-19 12:04:25 +00:00
commit efadef4f3e
35 changed files with 189 additions and 226 deletions

View File

@ -135,8 +135,9 @@ class Encryption {
try { try {
return await olmManager.decryptToDeviceEvent(event); return await olmManager.decryptToDeviceEvent(event);
} catch (e, s) { } catch (e, s) {
Logs.error( Logs().e(
'[LibOlm] Could not decrypt to device event from ${event.sender} with content: ${event.content}\n${e.toString()}', '[LibOlm] Could not decrypt to device event from ${event.sender} with content: ${event.content}',
e,
s); s);
client.onEncryptionError.add( client.onEncryptionError.add(
SdkError( SdkError(
@ -178,7 +179,7 @@ class Encryption {
var haveIndex = inboundGroupSession.indexes.containsKey(messageIndexKey); var haveIndex = inboundGroupSession.indexes.containsKey(messageIndexKey);
if (haveIndex && if (haveIndex &&
inboundGroupSession.indexes[messageIndexKey] != messageIndexValue) { inboundGroupSession.indexes[messageIndexKey] != messageIndexValue) {
Logs.error('[Decrypt] Could not decrypt due to a corrupted session.'); Logs().e('[Decrypt] Could not decrypt due to a corrupted session.');
throw (DecryptError.CHANNEL_CORRUPTED); throw (DecryptError.CHANNEL_CORRUPTED);
} }
inboundGroupSession.indexes[messageIndexKey] = messageIndexValue; inboundGroupSession.indexes[messageIndexKey] = messageIndexValue;
@ -282,7 +283,7 @@ class Encryption {
} }
return event; return event;
} catch (e, s) { } catch (e, s) {
Logs.error('[Decrypt] Could not decrpyt event: ' + e.toString(), s); Logs().e('[Decrypt] Could not decrpyt event', e, s);
return event; return event;
} }
} }

View File

@ -111,9 +111,7 @@ class KeyManager {
} }
} catch (e, s) { } catch (e, s) {
inboundGroupSession.free(); inboundGroupSession.free();
Logs.error( Logs().e('[LibOlm] Could not create new InboundGroupSession', e, s);
'[LibOlm] Could not create new InboundGroupSession: ' + e.toString(),
s);
return; return;
} }
final newSession = SessionKey( final newSession = SessionKey(
@ -356,9 +354,9 @@ class KeyManager {
devicesToReceive, 'm.room_key', rawSession); devicesToReceive, 'm.room_key', rawSession);
} }
} catch (e, s) { } catch (e, s) {
Logs.error( Logs().e(
'[LibOlm] Unable to re-send the session key at later index to new devices: ' + '[LibOlm] Unable to re-send the session key at later index to new devices',
e.toString(), e,
s); s);
} }
return false; return false;
@ -411,9 +409,7 @@ class KeyManager {
outboundGroupSession.create(); outboundGroupSession.create();
} catch (e, s) { } catch (e, s) {
outboundGroupSession.free(); outboundGroupSession.free();
Logs.error( Logs().e('[LibOlm] Unable to create new outboundGroupSession', e, s);
'[LibOlm] Unable to create new outboundGroupSession: ' + e.toString(),
s);
return null; return null;
} }
final rawSession = <String, dynamic>{ final rawSession = <String, dynamic>{
@ -437,9 +433,9 @@ class KeyManager {
await storeOutboundGroupSession(roomId, sess); await storeOutboundGroupSession(roomId, sess);
_outboundGroupSessions[roomId] = sess; _outboundGroupSessions[roomId] = sess;
} catch (e, s) { } catch (e, s) {
Logs.error( Logs().e(
'[LibOlm] Unable to send the session key to the participating devices: ' + '[LibOlm] Unable to send the session key to the participating devices',
e.toString(), e,
s); s);
sess.dispose(); sess.dispose();
return null; return null;
@ -531,8 +527,7 @@ class KeyManager {
decrypted = json.decode(decryption.decrypt(sessionData['ephemeral'], decrypted = json.decode(decryption.decrypt(sessionData['ephemeral'],
sessionData['mac'], sessionData['ciphertext'])); sessionData['mac'], sessionData['ciphertext']));
} catch (e, s) { } catch (e, s) {
Logs.error( Logs().e('[LibOlm] Error decrypting room key', e, s);
'[LibOlm] Error decrypting room key: ' + e.toString(), s);
} }
if (decrypted != null) { if (decrypted != null) {
decrypted['session_id'] = sessionId; decrypted['session_id'] = sessionId;
@ -584,12 +579,10 @@ class KeyManager {
await loadSingleKey(room.id, sessionId); await loadSingleKey(room.id, sessionId);
} catch (err, stacktrace) { } catch (err, stacktrace) {
if (err is MatrixException && err.errcode == 'M_NOT_FOUND') { if (err is MatrixException && err.errcode == 'M_NOT_FOUND') {
Logs.info( Logs().i(
'[KeyManager] Key not in online key backup, requesting it from other devices...'); '[KeyManager] Key not in online key backup, requesting it from other devices...');
} else { } else {
Logs.error( Logs().e('[KeyManager] Failed to access online key backup', err,
'[KeyManager] Failed to access online key backup: ' +
err.toString(),
stacktrace); stacktrace);
} }
} }
@ -632,10 +625,7 @@ class KeyManager {
); );
outgoingShareRequests[request.requestId] = request; outgoingShareRequests[request.requestId] = request;
} catch (e, s) { } catch (e, s) {
Logs.error( Logs().e('[Key Manager] Sending key verification request failed', e, s);
'[Key Manager] Sending key verification request failed: ' +
e.toString(),
s);
} }
} }
@ -693,7 +683,7 @@ class KeyManager {
final roomKeys = final roomKeys =
await runInBackground<RoomKeys, _GenerateUploadKeysArgs>( await runInBackground<RoomKeys, _GenerateUploadKeysArgs>(
_generateUploadKeys, args); _generateUploadKeys, args);
Logs.info('[Key Manager] Uploading ${dbSessions.length} room keys...'); Logs().i('[Key Manager] Uploading ${dbSessions.length} room keys...');
// upload the payload... // upload the payload...
await client.storeRoomKeys(info.version, roomKeys); await client.storeRoomKeys(info.version, roomKeys);
// and now finally mark all the keys as uploaded // and now finally mark all the keys as uploaded
@ -706,7 +696,7 @@ class KeyManager {
decryption.free(); decryption.free();
} }
} catch (e, s) { } catch (e, s) {
Logs.error('[Key Manager] Error uploading room keys: ' + e.toString(), s); Logs().e('[Key Manager] Error uploading room keys', e, s);
} finally { } finally {
_isUploadingKeys = false; _isUploadingKeys = false;
} }
@ -720,27 +710,27 @@ class KeyManager {
} }
if (event.content['action'] == 'request') { if (event.content['action'] == 'request') {
// we are *receiving* a request // we are *receiving* a request
Logs.info('[KeyManager] Received key sharing request...'); Logs().i('[KeyManager] Received key sharing request...');
if (!event.content.containsKey('body')) { if (!event.content.containsKey('body')) {
Logs.info('[KeyManager] No body, doing nothing'); Logs().i('[KeyManager] No body, doing nothing');
return; // no body return; // no body
} }
if (!client.userDeviceKeys.containsKey(event.sender) || if (!client.userDeviceKeys.containsKey(event.sender) ||
!client.userDeviceKeys[event.sender].deviceKeys !client.userDeviceKeys[event.sender].deviceKeys
.containsKey(event.content['requesting_device_id'])) { .containsKey(event.content['requesting_device_id'])) {
Logs.info('[KeyManager] Device not found, doing nothing'); Logs().i('[KeyManager] Device not found, doing nothing');
return; // device not found return; // device not found
} }
final device = client.userDeviceKeys[event.sender] final device = client.userDeviceKeys[event.sender]
.deviceKeys[event.content['requesting_device_id']]; .deviceKeys[event.content['requesting_device_id']];
if (device.userId == client.userID && if (device.userId == client.userID &&
device.deviceId == client.deviceID) { device.deviceId == client.deviceID) {
Logs.info('[KeyManager] Request is by ourself, ignoring'); Logs().i('[KeyManager] Request is by ourself, ignoring');
return; // ignore requests by ourself return; // ignore requests by ourself
} }
final room = client.getRoomById(event.content['body']['room_id']); final room = client.getRoomById(event.content['body']['room_id']);
if (room == null) { if (room == null) {
Logs.info('[KeyManager] Unknown room, ignoring'); Logs().i('[KeyManager] Unknown room, ignoring');
return; // unknown room return; // unknown room
} }
final sessionId = event.content['body']['session_id']; final sessionId = event.content['body']['session_id'];
@ -748,7 +738,7 @@ class KeyManager {
// okay, let's see if we have this session at all // okay, let's see if we have this session at all
if ((await loadInboundGroupSession(room.id, sessionId, senderKey)) == if ((await loadInboundGroupSession(room.id, sessionId, senderKey)) ==
null) { null) {
Logs.info('[KeyManager] Unknown session, ignoring'); Logs().i('[KeyManager] Unknown session, ignoring');
return; // we don't have this session anyways return; // we don't have this session anyways
} }
final request = KeyManagerKeyShareRequest( final request = KeyManagerKeyShareRequest(
@ -759,7 +749,7 @@ class KeyManager {
senderKey: senderKey, senderKey: senderKey,
); );
if (incomingShareRequests.containsKey(request.requestId)) { if (incomingShareRequests.containsKey(request.requestId)) {
Logs.info('[KeyManager] Already processed this request, ignoring'); Logs().i('[KeyManager] Already processed this request, ignoring');
return; // we don't want to process one and the same request multiple times return; // we don't want to process one and the same request multiple times
} }
incomingShareRequests[request.requestId] = request; incomingShareRequests[request.requestId] = request;
@ -768,12 +758,12 @@ class KeyManager {
if (device.userId == client.userID && if (device.userId == client.userID &&
device.verified && device.verified &&
!device.blocked) { !device.blocked) {
Logs.info('[KeyManager] All checks out, forwarding key...'); Logs().i('[KeyManager] All checks out, forwarding key...');
// alright, we can forward the key // alright, we can forward the key
await roomKeyRequest.forwardKey(); await roomKeyRequest.forwardKey();
} else { } else {
Logs.info( Logs()
'[KeyManager] Asking client, if the key should be forwarded'); .i('[KeyManager] Asking client, if the key should be forwarded');
client.onRoomKeyRequest client.onRoomKeyRequest
.add(roomKeyRequest); // let the client handle this .add(roomKeyRequest); // let the client handle this
} }
@ -988,7 +978,7 @@ RoomKeys _generateUploadKeys(_GenerateUploadKeysArgs args) {
} }
return roomKeys; return roomKeys;
} catch (e, s) { } catch (e, s) {
Logs.error('[Key Manager] Error generating payload ' + e.toString(), s); Logs().e('[Key Manager] Error generating payload', e, s);
rethrow; rethrow;
} finally { } finally {
enc.free(); enc.free();

View File

@ -127,7 +127,7 @@ class OlmManager {
isValid = true; isValid = true;
} catch (e, s) { } catch (e, s) {
isValid = false; isValid = false;
Logs.error('[LibOlm] Signature check failed: ' + e.toString(), s); Logs().e('[LibOlm] Signature check failed', e, s);
} finally { } finally {
olmutil.free(); olmutil.free();
} }
@ -442,10 +442,8 @@ class OlmManager {
)); ));
} catch (e, s) { } catch (e, s) {
session.free(); session.free();
Logs.error( Logs()
'[LibOlm] Could not create new outbound olm session: ' + .e('[LibOlm] Could not create new outbound olm session', e, s);
e.toString(),
s);
} }
} }
} }
@ -518,8 +516,7 @@ class OlmManager {
data[device.userId][device.deviceId] = data[device.userId][device.deviceId] =
await encryptToDeviceMessagePayload(device, type, payload); await encryptToDeviceMessagePayload(device, type, payload);
} catch (e, s) { } catch (e, s) {
Logs.error( Logs().e('[LibOlm] Error encrypting to-device event', e, s);
'[LibOlm] Error encrypting to-device event: ' + e.toString(), s);
continue; continue;
} }
} }

View File

@ -384,10 +384,10 @@ class SSSS {
Future<void> request(String type, [List<DeviceKeys> devices]) async { Future<void> request(String type, [List<DeviceKeys> devices]) async {
// only send to own, verified devices // only send to own, verified devices
Logs.info('[SSSS] Requesting type ${type}...'); Logs().i('[SSSS] Requesting type ${type}...');
if (devices == null || devices.isEmpty) { if (devices == null || devices.isEmpty) {
if (!client.userDeviceKeys.containsKey(client.userID)) { if (!client.userDeviceKeys.containsKey(client.userID)) {
Logs.warning('[SSSS] User does not have any devices'); Logs().w('[SSSS] User does not have any devices');
return; return;
} }
devices = client.userDeviceKeys[client.userID].deviceKeys.values.toList(); devices = client.userDeviceKeys[client.userID].deviceKeys.values.toList();
@ -398,7 +398,7 @@ class SSSS {
d.blocked || d.blocked ||
d.deviceId == client.deviceID); d.deviceId == client.deviceID);
if (devices.isEmpty) { if (devices.isEmpty) {
Logs.warning('[SSSS] No devices'); Logs().w('[SSSS] No devices');
return; return;
} }
final requestId = client.generateUniqueTransactionId(); final requestId = client.generateUniqueTransactionId();
@ -440,32 +440,32 @@ class SSSS {
Future<void> handleToDeviceEvent(ToDeviceEvent event) async { Future<void> handleToDeviceEvent(ToDeviceEvent event) async {
if (event.type == 'm.secret.request') { if (event.type == 'm.secret.request') {
// got a request to share a secret // got a request to share a secret
Logs.info('[SSSS] Received sharing request...'); Logs().i('[SSSS] Received sharing request...');
if (event.sender != client.userID || if (event.sender != client.userID ||
!client.userDeviceKeys.containsKey(client.userID)) { !client.userDeviceKeys.containsKey(client.userID)) {
Logs.info('[SSSS] Not sent by us'); Logs().i('[SSSS] Not sent by us');
return; // we aren't asking for it ourselves, so ignore return; // we aren't asking for it ourselves, so ignore
} }
if (event.content['action'] != 'request') { if (event.content['action'] != 'request') {
Logs.info('[SSSS] it is actually a cancelation'); Logs().i('[SSSS] it is actually a cancelation');
return; // not actually requesting, so ignore return; // not actually requesting, so ignore
} }
final device = client.userDeviceKeys[client.userID] final device = client.userDeviceKeys[client.userID]
.deviceKeys[event.content['requesting_device_id']]; .deviceKeys[event.content['requesting_device_id']];
if (device == null || !device.verified || device.blocked) { if (device == null || !device.verified || device.blocked) {
Logs.info('[SSSS] Unknown / unverified devices, ignoring'); Logs().i('[SSSS] Unknown / unverified devices, ignoring');
return; // nope....unknown or untrusted device return; // nope....unknown or untrusted device
} }
// alright, all seems fine...let's check if we actually have the secret they are asking for // alright, all seems fine...let's check if we actually have the secret they are asking for
final type = event.content['name']; final type = event.content['name'];
final secret = await getCached(type); final secret = await getCached(type);
if (secret == null) { if (secret == null) {
Logs.info( Logs().i(
'[SSSS] We don\'t have the secret for ${type} ourself, ignoring'); '[SSSS] We don\'t have the secret for ${type} ourself, ignoring');
return; // seems like we don't have this, either return; // seems like we don't have this, either
} }
// okay, all checks out...time to share this secret! // okay, all checks out...time to share this secret!
Logs.info('[SSSS] Replying with secret for ${type}'); Logs().i('[SSSS] Replying with secret for ${type}');
await client.sendToDeviceEncrypted( await client.sendToDeviceEncrypted(
[device], [device],
'm.secret.send', 'm.secret.send',
@ -475,11 +475,11 @@ class SSSS {
}); });
} else if (event.type == 'm.secret.send') { } else if (event.type == 'm.secret.send') {
// receiving a secret we asked for // receiving a secret we asked for
Logs.info('[SSSS] Received shared secret...'); Logs().i('[SSSS] Received shared secret...');
if (event.sender != client.userID || if (event.sender != client.userID ||
!pendingShareRequests.containsKey(event.content['request_id']) || !pendingShareRequests.containsKey(event.content['request_id']) ||
event.encryptedContent == null) { event.encryptedContent == null) {
Logs.info('[SSSS] Not by us or unknown request'); Logs().i('[SSSS] Not by us or unknown request');
return; // we have no idea what we just received return; // we have no idea what we just received
} }
final request = pendingShareRequests[event.content['request_id']]; final request = pendingShareRequests[event.content['request_id']];
@ -490,26 +490,26 @@ class SSSS {
d.curve25519Key == event.encryptedContent['sender_key'], d.curve25519Key == event.encryptedContent['sender_key'],
orElse: () => null); orElse: () => null);
if (device == null) { if (device == null) {
Logs.info('[SSSS] Someone else replied?'); Logs().i('[SSSS] Someone else replied?');
return; // someone replied whom we didn't send the share request to return; // someone replied whom we didn't send the share request to
} }
final secret = event.content['secret']; final secret = event.content['secret'];
if (!(event.content['secret'] is String)) { if (!(event.content['secret'] is String)) {
Logs.info('[SSSS] Secret wasn\'t a string'); Logs().i('[SSSS] Secret wasn\'t a string');
return; // the secret wasn't a string....wut? return; // the secret wasn't a string....wut?
} }
// let's validate if the secret is, well, valid // let's validate if the secret is, well, valid
if (_validators.containsKey(request.type) && if (_validators.containsKey(request.type) &&
!(await _validators[request.type](secret))) { !(await _validators[request.type](secret))) {
Logs.info('[SSSS] The received secret was invalid'); Logs().i('[SSSS] The received secret was invalid');
return; // didn't pass the validator return; // didn't pass the validator
} }
pendingShareRequests.remove(request.requestId); pendingShareRequests.remove(request.requestId);
if (request.start.add(Duration(minutes: 15)).isBefore(DateTime.now())) { if (request.start.add(Duration(minutes: 15)).isBefore(DateTime.now())) {
Logs.info('[SSSS] Request is too far in the past'); Logs().i('[SSSS] Request is too far in the past');
return; // our request is more than 15min in the past...better not trust it anymore return; // our request is more than 15min in the past...better not trust it anymore
} }
Logs.info('[SSSS] Secret for type ${request.type} is ok, storing it'); Logs().i('[SSSS] Secret for type ${request.type} is ok, storing it');
if (client.database != null) { if (client.database != null) {
final keyId = keyIdFromType(request.type); final keyId = keyIdFromType(request.type);
if (keyId != null) { if (keyId != null) {

View File

@ -236,8 +236,7 @@ class Bootstrap {
} }
} catch (e) { } catch (e) {
// very bad // very bad
Logs.error( Logs().e('[Bootstrapping] Error construction ssss key', e);
'[Bootstrapping] Error construction ssss key: ' + e.toString());
state = BootstrapState.error; state = BootstrapState.error;
return; return;
} }
@ -296,10 +295,7 @@ class Bootstrap {
await newSsssKey.maybeCacheAll(); await newSsssKey.maybeCacheAll();
} }
} catch (e, s) { } catch (e, s) {
Logs.error( Logs().e('[Bootstrapping] Error trying to migrate old secrets', e, s);
'[Bootstrapping] Error trying to migrate old secrets: ' +
e.toString(),
s);
state = BootstrapState.error; state = BootstrapState.error;
return; return;
} }
@ -494,8 +490,7 @@ class Bootstrap {
} }
await encryption.crossSigning.sign(keysToSign); await encryption.crossSigning.sign(keysToSign);
} catch (e, s) { } catch (e, s) {
Logs.error( Logs().e('[Bootstrapping] Error setting up cross signing', e, s);
'[Bootstrapping] Error setting up cross signing: ' + e.toString(), s);
state = BootstrapState.error; state = BootstrapState.error;
return; return;
} }
@ -553,9 +548,7 @@ class Bootstrap {
// and finally set all megolm keys as needing to be uploaded again // and finally set all megolm keys as needing to be uploaded again
await client.database?.markInboundGroupSessionsAsNeedingUpload(client.id); await client.database?.markInboundGroupSessionsAsNeedingUpload(client.id);
} catch (e, s) { } catch (e, s) {
Logs.error( Logs().e('[Bootstrapping] Error setting up online key backup', e, s);
'[Bootstrapping] Error setting up online key backup: ' + e.toString(),
s);
state = BootstrapState.error; state = BootstrapState.error;
encryption.client.onEncryptionError.add( encryption.client.onEncryptionError.add(
SdkError(exception: e, stackTrace: s), SdkError(exception: e, stackTrace: s),

View File

@ -20,7 +20,7 @@ extension JsonSignatureCheckExtension on Map<String, dynamic> {
isValid = true; isValid = true;
} catch (e, s) { } catch (e, s) {
isValid = false; isValid = false;
Logs.error('[LibOlm] Signature check failed: ' + e.toString(), s); Logs().e('[LibOlm] Signature check failed', e, s);
} finally { } finally {
olmutil.free(); olmutil.free();
} }

View File

@ -155,7 +155,7 @@ class KeyVerification {
} }
void dispose() { void dispose() {
Logs.info('[Key Verification] disposing object...'); Logs().i('[Key Verification] disposing object...');
method?.dispose(); method?.dispose();
} }
@ -210,8 +210,7 @@ class KeyVerification {
await Future.delayed(Duration(milliseconds: 50)); await Future.delayed(Duration(milliseconds: 50));
} }
_handlePayloadLock = true; _handlePayloadLock = true;
Logs.info( Logs().i('[Key Verification] Received type ${type}: ' + payload.toString());
'[Key Verification] Received type ${type}: ' + payload.toString());
try { try {
var thisLastStep = lastStep; var thisLastStep = lastStep;
switch (type) { switch (type) {
@ -321,7 +320,7 @@ class KeyVerification {
startPaylaod = payload; startPaylaod = payload;
setState(KeyVerificationState.askAccept); setState(KeyVerificationState.askAccept);
} else { } else {
Logs.info('handling start in method.....'); Logs().i('handling start in method.....');
await method.handlePayload(type, payload); await method.handlePayload(type, payload);
} }
break; break;
@ -346,8 +345,7 @@ class KeyVerification {
lastStep = type; lastStep = type;
} }
} catch (err, stacktrace) { } catch (err, stacktrace) {
Logs.error( Logs().e('[Key Verification] An error occured', err, stacktrace);
'[Key Verification] An error occured: ' + err.toString(), stacktrace);
await cancel('m.invalid_message'); await cancel('m.invalid_message');
} finally { } finally {
_handlePayloadLock = false; _handlePayloadLock = false;
@ -583,10 +581,9 @@ class KeyVerification {
Future<void> send(String type, Map<String, dynamic> payload) async { Future<void> send(String type, Map<String, dynamic> payload) async {
makePayload(payload); makePayload(payload);
Logs.info('[Key Verification] Sending type ${type}: ' + payload.toString()); Logs().i('[Key Verification] Sending type ${type}: ' + payload.toString());
if (room != null) { if (room != null) {
Logs.info( Logs().i('[Key Verification] Sending to ${userId} in room ${room.id}...');
'[Key Verification] Sending to ${userId} in room ${room.id}...');
if ({'m.key.verification.request'}.contains(type)) { if ({'m.key.verification.request'}.contains(type)) {
payload['msgtype'] = type; payload['msgtype'] = type;
payload['to'] = userId; payload['to'] = userId;
@ -600,13 +597,12 @@ class KeyVerification {
encryption.keyVerificationManager.addRequest(this); encryption.keyVerificationManager.addRequest(this);
} }
} else { } else {
Logs.info( Logs().i('[Key Verification] Sending to ${userId} device ${deviceId}...');
'[Key Verification] Sending to ${userId} device ${deviceId}...');
if (deviceId == '*') { if (deviceId == '*') {
if ({'m.key.verification.request'}.contains(type)) { if ({'m.key.verification.request'}.contains(type)) {
await client.sendToDevicesOfUserIds({userId}, type, payload); await client.sendToDevicesOfUserIds({userId}, type, payload);
} else { } else {
Logs.error( Logs().e(
'[Key Verification] Tried to broadcast and un-broadcastable type: ${type}'); '[Key Verification] Tried to broadcast and un-broadcastable type: ${type}');
} }
} else { } else {
@ -739,8 +735,7 @@ class _KeyVerificationMethodSas extends _KeyVerificationMethod {
break; break;
} }
} catch (err, stacktrace) { } catch (err, stacktrace) {
Logs.error('[Key Verification SAS] An error occured: ' + err.toString(), Logs().e('[Key Verification SAS] An error occured', err, stacktrace);
stacktrace);
if (request.deviceId != null) { if (request.deviceId != null) {
await request.cancel('m.invalid_message'); await request.cancel('m.invalid_message');
} }

View File

@ -49,7 +49,7 @@ class OlmSession {
DateTime.fromMillisecondsSinceEpoch(dbEntry.lastReceived ?? 0); DateTime.fromMillisecondsSinceEpoch(dbEntry.lastReceived ?? 0);
assert(sessionId == session.session_id()); assert(sessionId == session.session_id());
} catch (e, s) { } catch (e, s) {
Logs.error('[LibOlm] Could not unpickle olm session: ' + e.toString(), s); Logs().e('[LibOlm] Could not unpickle olm session', e, s);
dispose(); dispose();
} }
} }

View File

@ -51,7 +51,7 @@ class OutboundGroupSession {
} }
} catch (e) { } catch (e) {
// devices is bad (old data), so just not use this session // devices is bad (old data), so just not use this session
Logs.info( Logs().i(
'[OutboundGroupSession] Session in database is old, not using it. ' + '[OutboundGroupSession] Session in database is old, not using it. ' +
e.toString()); e.toString());
return; return;
@ -63,9 +63,7 @@ class OutboundGroupSession {
sentMessages = dbEntry.sentMessages; sentMessages = dbEntry.sentMessages;
} catch (e, s) { } catch (e, s) {
dispose(); dispose();
Logs.error( Logs().e('[LibOlm] Unable to unpickle outboundGroupSession', e, s);
'[LibOlm] Unable to unpickle outboundGroupSession: ' + e.toString(),
s);
} }
} }

View File

@ -78,9 +78,7 @@ class SessionKey {
inboundGroupSession.unpickle(key, dbEntry.pickle); inboundGroupSession.unpickle(key, dbEntry.pickle);
} catch (e, s) { } catch (e, s) {
dispose(); dispose();
Logs.error( Logs().e('[LibOlm] Unable to unpickle inboundGroupSession', e, s);
'[LibOlm] Unable to unpickle inboundGroupSession: ' + e.toString(),
s);
} }
} }

View File

@ -19,6 +19,7 @@
library matrix_api; library matrix_api;
export 'matrix_api/matrix_api.dart'; export 'matrix_api/matrix_api.dart';
export 'matrix_api/utils/logs.dart';
export 'matrix_api/model/algorithm_types.dart'; export 'matrix_api/model/algorithm_types.dart';
export 'matrix_api/model/basic_event.dart'; export 'matrix_api/model/basic_event.dart';
export 'matrix_api/model/basic_event_with_sender.dart'; export 'matrix_api/model/basic_event_with_sender.dart';

View File

@ -16,37 +16,16 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import 'package:ansicolor/ansicolor.dart'; import 'package:logger/logger.dart';
abstract class Logs { class Logs extends Logger {
static final AnsiPen _infoPen = AnsiPen()..blue(); static final Logs _singleton = Logs._internal();
static final AnsiPen _warningPen = AnsiPen()..yellow();
static final AnsiPen _successPen = AnsiPen()..green();
static final AnsiPen _errorPen = AnsiPen()..red();
static const String _prefixText = '[Famedly Matrix SDK] '; factory Logs() {
return _singleton;
}
// ignore: avoid_print set level(Level newLevel) => Logger.level = newLevel;
static void info(dynamic info) => print(
_prefixText + _infoPen(info.toString()),
);
// ignore: avoid_print Logs._internal() : super(printer: PrettyPrinter(methodCount: 0));
static void success(dynamic obj, [dynamic stackTrace]) => print(
_prefixText + _successPen(obj.toString()),
);
// ignore: avoid_print
static void warning(dynamic warning, [dynamic stackTrace]) => print(
_prefixText +
_warningPen(warning.toString()) +
(stackTrace != null ? '\n${stackTrace.toString()}' : ''),
);
// ignore: avoid_print
static void error(dynamic obj, [dynamic stackTrace]) => print(
_prefixText +
_errorPen(obj.toString()) +
(stackTrace != null ? '\n${stackTrace.toString()}' : ''),
);
} }

View File

@ -4,12 +4,12 @@ extension TryGetMapExtension on Map<String, dynamic> {
T tryGet<T>(String key, [T fallbackValue]) { T tryGet<T>(String key, [T fallbackValue]) {
final value = this[key]; final value = this[key];
if (value != null && !(value is T)) { if (value != null && !(value is T)) {
Logs.warning( Logs().w(
'Expected "${T.runtimeType}" in event content for the Key "$key" but got "${value.runtimeType}".'); 'Expected "${T.runtimeType}" in event content for the Key "$key" but got "${value.runtimeType}".');
return fallbackValue; return fallbackValue;
} }
if (value == null && fallbackValue != null) { if (value == null && fallbackValue != null) {
Logs.warning( Logs().w(
'Required field in event content for the Key "$key" is null. Set to "$fallbackValue".'); 'Required field in event content for the Key "$key" is null. Set to "$fallbackValue".');
return fallbackValue; return fallbackValue;
} }

View File

@ -163,7 +163,7 @@ class Client extends MatrixApi {
/// Warning! This endpoint is for testing only! /// Warning! This endpoint is for testing only!
set rooms(List<Room> newList) { set rooms(List<Room> newList) {
Logs.warning('Warning! This endpoint is for testing only!'); Logs().w('Warning! This endpoint is for testing only!');
_rooms = newList; _rooms = newList;
} }
@ -390,7 +390,7 @@ class Client extends MatrixApi {
try { try {
await super.logout(); await super.logout();
} catch (e, s) { } catch (e, s) {
Logs.error(e, s); Logs().e('Logout failed', e, s);
rethrow; rethrow;
} finally { } finally {
await clear(); await clear();
@ -404,7 +404,7 @@ class Client extends MatrixApi {
try { try {
await super.logoutAll(); await super.logoutAll();
} catch (e, s) { } catch (e, s) {
Logs.error(e, s); Logs().e('Logout all failed', e, s);
rethrow; rethrow;
} finally { } finally {
await clear(); await clear();
@ -690,7 +690,7 @@ class Client extends MatrixApi {
if (_initLock) throw Exception('[init()] has been called multiple times!'); if (_initLock) throw Exception('[init()] has been called multiple times!');
_initLock = true; _initLock = true;
try { try {
Logs.info('Initialize client $clientName'); Logs().i('Initialize client $clientName');
if (isLogged()) { if (isLogged()) {
throw Exception('User is already logged in! Call [logout()] first!'); throw Exception('User is already logged in! Call [logout()] first!');
} }
@ -734,7 +734,7 @@ class Client extends MatrixApi {
encryption?.dispose(); encryption?.dispose();
encryption = null; encryption = null;
onLoginStateChanged.add(LoginState.loggedOut); onLoginStateChanged.add(LoginState.loggedOut);
Logs.info('User is not logged in.'); Logs().i('User is not logged in.');
_initLock = false; _initLock = false;
return; return;
} }
@ -777,12 +777,12 @@ class Client extends MatrixApi {
} }
onLoginStateChanged.add(LoginState.logged); onLoginStateChanged.add(LoginState.logged);
Logs.success( Logs().i(
'Successfully connected as ${userID.localpart} with ${homeserver.toString()}', 'Successfully connected as ${userID.localpart} with ${homeserver.toString()}',
); );
return _sync(); return _sync();
} catch (e, s) { } catch (e, s) {
Logs.error('Initialization failed: ${e.toString()}', s); Logs().e('Initialization failed', e, s);
clear(); clear();
onLoginStateChanged.addError(e, s); onLoginStateChanged.addError(e, s);
_initLock = false; _initLock = false;
@ -880,15 +880,15 @@ class Client extends MatrixApi {
} on MatrixException catch (e, s) { } on MatrixException catch (e, s) {
onSyncError.add(SdkError(exception: e, stackTrace: s)); onSyncError.add(SdkError(exception: e, stackTrace: s));
if (e.error == MatrixError.M_UNKNOWN_TOKEN) { if (e.error == MatrixError.M_UNKNOWN_TOKEN) {
Logs.warning('The user has been logged out!'); Logs().w('The user has been logged out!');
clear(); clear();
} }
} on MatrixConnectionException catch (e, s) { } on MatrixConnectionException catch (e, s) {
Logs.warning('Synchronization connection failed: ${e.toString()}'); Logs().w('Synchronization connection failed', e);
onSyncError.add(SdkError(exception: e, stackTrace: s)); onSyncError.add(SdkError(exception: e, stackTrace: s));
} catch (e, s) { } catch (e, s) {
if (!isLogged() || _disposed) return; if (!isLogged() || _disposed) return;
Logs.error('Error during processing events: ${e.toString()}', s); Logs().e('Error during processing events', e, s);
onSyncError.add(SdkError( onSyncError.add(SdkError(
exception: e is Exception ? e : Exception(e), stackTrace: s)); exception: e is Exception ? e : Exception(e), stackTrace: s));
} }
@ -1255,7 +1255,7 @@ class Client extends MatrixApi {
Event.fromJson(eventUpdate.content, room, eventUpdate.sortOrder); Event.fromJson(eventUpdate.content, room, eventUpdate.sortOrder);
var prevState = room.getState(stateEvent.type, stateEvent.stateKey); var prevState = room.getState(stateEvent.type, stateEvent.stateKey);
if (prevState != null && prevState.sortOrder > stateEvent.sortOrder) { if (prevState != null && prevState.sortOrder > stateEvent.sortOrder) {
Logs.warning(''' Logs().w('''
A new ${eventUpdate.type} event of the type ${stateEvent.type} has arrived with a previews A new ${eventUpdate.type} event of the type ${stateEvent.type} has arrived with a previews
sort order ${stateEvent.sortOrder} than the current ${stateEvent.type} event with a sort order ${stateEvent.sortOrder} than the current ${stateEvent.type} event with a
sort order of ${prevState.sortOrder}. This should never happen...'''); sort order of ${prevState.sortOrder}. This should never happen...''');
@ -1341,7 +1341,7 @@ sort order of ${prevState.sortOrder}. This should never happen...''');
} }
} }
} catch (e, s) { } catch (e, s) {
Logs.error('[E2EE] Failed to fetch participants: ' + e.toString(), s); Logs().e('[E2EE] Failed to fetch participants', e, s);
} }
} }
} }
@ -1530,8 +1530,7 @@ sort order of ${prevState.sortOrder}. This should never happen...''');
}); });
} }
} catch (e, s) { } catch (e, s) {
Logs.error( Logs().e('[LibOlm] Unable to update user device keys', e, s);
'[LibOlm] Unable to update user device keys: ' + e.toString(), s);
} }
} }
@ -1715,11 +1714,13 @@ sort order of ${prevState.sortOrder}. This should never happen...''');
encryption = null; encryption = null;
try { try {
if (closeDatabase && database != null) { if (closeDatabase && database != null) {
await database.close().catchError((e, s) => Logs.warning(e, s)); await database
.close()
.catchError((e, s) => Logs().w('Failed to close database: ', e, s));
_database = null; _database = null;
} }
} catch (error, stacktrace) { } catch (error, stacktrace) {
Logs.warning('Failed to close database: ' + error.toString(), stacktrace); Logs().w('Failed to close database: ', error, stacktrace);
} }
return; return;
} }

View File

@ -67,7 +67,7 @@ class Database extends _$Database {
try { try {
await m.createAll(); await m.createAll();
} catch (e, s) { } catch (e, s) {
Logs.error(e, s); Logs().e('Create all failed in database migrator', e, s);
onError.add(SdkError(exception: e, stackTrace: s)); onError.add(SdkError(exception: e, stackTrace: s));
rethrow; rethrow;
} }
@ -138,7 +138,7 @@ class Database extends _$Database {
await customStatement('UPDATE clients SET prev_batch = null'); await customStatement('UPDATE clients SET prev_batch = null');
} }
} catch (e, s) { } catch (e, s) {
Logs.error(e, s); Logs().e('Database migration failed', e, s);
onError.add(SdkError(exception: e, stackTrace: s)); onError.add(SdkError(exception: e, stackTrace: s));
rethrow; rethrow;
} }
@ -148,12 +148,12 @@ class Database extends _$Database {
if (executor.dialect == SqlDialect.sqlite) { if (executor.dialect == SqlDialect.sqlite) {
final ret = await customSelect('PRAGMA journal_mode=WAL').get(); final ret = await customSelect('PRAGMA journal_mode=WAL').get();
if (ret.isNotEmpty) { if (ret.isNotEmpty) {
Logs.info('[Moor] Switched database to mode ' + Logs().i('[Moor] Switched database to mode ' +
ret.first.data['journal_mode'].toString()); ret.first.data['journal_mode'].toString());
} }
} }
} catch (e, s) { } catch (e, s) {
Logs.error(e, s); Logs().e('Database before open failed', e, s);
onError.add(SdkError(exception: e, stackTrace: s)); onError.add(SdkError(exception: e, stackTrace: s));
rethrow; rethrow;
} }
@ -202,8 +202,7 @@ class Database extends _$Database {
session.unpickle(userId, row.pickle); session.unpickle(userId, row.pickle);
res[row.identityKey].add(session); res[row.identityKey].add(session);
} catch (e, s) { } catch (e, s) {
Logs.error( Logs().e('[LibOlm] Could not unpickle olm session', e, s);
'[LibOlm] Could not unpickle olm session: ' + e.toString(), s);
} }
} }
return res; return res;

View File

@ -139,7 +139,7 @@ class Room {
try { try {
state = client.encryption.decryptRoomEventSync(id, state); state = client.encryption.decryptRoomEventSync(id, state);
} catch (e, s) { } catch (e, s) {
Logs.error('[LibOlm] Could not decrypt room state: ' + e.toString(), s); Logs().e('[LibOlm] Could not decrypt room state', e, s);
} }
} }
if (!(state.stateKey is String) && if (!(state.stateKey is String) &&
@ -794,13 +794,12 @@ class Room {
if ((DateTime.now().millisecondsSinceEpoch - if ((DateTime.now().millisecondsSinceEpoch -
sentDate.millisecondsSinceEpoch) < sentDate.millisecondsSinceEpoch) <
(1000 * client.sendMessageTimeoutSeconds)) { (1000 * client.sendMessageTimeoutSeconds)) {
Logs.warning('[Client] Problem while sending message because of "' + Logs().w('[Client] Problem while sending message because of "' +
e.toString() + e.toString() +
'". Try again in 1 seconds...'); '". Try again in 1 seconds...');
await Future.delayed(Duration(seconds: 1)); await Future.delayed(Duration(seconds: 1));
} else { } else {
Logs.warning( Logs().w('[Client] Problem while sending message', e, s);
'[Client] Problem while sending message: ' + e.toString(), s);
syncUpdate.rooms.join.values.first.timeline.events.first syncUpdate.rooms.join.values.first.timeline.events.first
.unsigned[MessageSendingStatusKey] = -1; .unsigned[MessageSendingStatusKey] = -1;
await _handleFakeSync(syncUpdate); await _handleFakeSync(syncUpdate);

View File

@ -317,7 +317,7 @@ class Timeline {
if (onUpdate != null) onUpdate(); if (onUpdate != null) onUpdate();
} }
} catch (e, s) { } catch (e, s) {
Logs.warning('Handle event update failed: ${e.toString()}', s); Logs().w('Handle event update failed', e, s);
} }
} }

View File

@ -68,7 +68,7 @@ class EventUpdate {
sortOrder: sortOrder, sortOrder: sortOrder,
); );
} catch (e, s) { } catch (e, s) {
Logs.error('[LibOlm] Could not decrypt megolm event: ' + e.toString(), s); Logs().e('[LibOlm] Could not decrypt megolm event', e, s);
return this; return this;
} }
} }

View File

@ -25,7 +25,7 @@ Future<T> runInRoot<T>(FutureOr<T> Function() fn) async {
try { try {
return await fn(); return await fn();
} catch (e, s) { } catch (e, s) {
Logs.error('Error thrown in root zone: ' + e.toString(), s); Logs().e('Error thrown in root zone', e, s);
} }
return null; return null;
}); });

View File

@ -21,8 +21,8 @@ dependencies:
password_hash: ^2.0.0 password_hash: ^2.0.0
olm: ^1.2.1 olm: ^1.2.1
matrix_file_e2ee: ^1.0.5 matrix_file_e2ee: ^1.0.5
ansicolor: ^1.1.1
isolate: ^2.0.3 isolate: ^2.0.3
logger: 0.7.0
dev_dependencies: dev_dependencies:
test: ^1.15.7 test: ^1.15.7

View File

@ -55,15 +55,16 @@ void main() {
roomUpdateListFuture = matrix.onRoomUpdate.stream.toList(); roomUpdateListFuture = matrix.onRoomUpdate.stream.toList();
eventUpdateListFuture = matrix.onEvent.stream.toList(); eventUpdateListFuture = matrix.onEvent.stream.toList();
toDeviceUpdateListFuture = matrix.onToDeviceEvent.stream.toList(); toDeviceUpdateListFuture = matrix.onToDeviceEvent.stream.toList();
var olmEnabled = true; var olmEnabled = true;
try { try {
olm.init(); olm.init();
olm.Account(); olm.Account();
} catch (_) { } catch (e) {
olmEnabled = false; olmEnabled = false;
Logs.warning('[LibOlm] Failed to load LibOlm: ' + _.toString()); Logs().w('[LibOlm] Failed to load LibOlm', e);
} }
Logs.success('[LibOlm] Enabled: $olmEnabled'); Logs().w('[LibOlm] Enabled: $olmEnabled');
test('Login', () async { test('Login', () async {
var presenceCounter = 0; var presenceCounter = 0;

View File

@ -76,11 +76,11 @@ void main() {
try { try {
olm.init(); olm.init();
olm.Account(); olm.Account();
} catch (_) { } catch (e) {
olmEnabled = false; olmEnabled = false;
Logs.error('[LibOlm] Failed to load LibOlm: ' + _.toString()); Logs().e('[LibOlm] Failed to load LibOlm', e);
} }
Logs.success('[LibOlm] Enabled: $olmEnabled'); Logs().i('[LibOlm] Enabled: $olmEnabled');
if (!olmEnabled) return; if (!olmEnabled) return;

View File

@ -33,11 +33,11 @@ void main() {
try { try {
olm.init(); olm.init();
olm.Account(); olm.Account();
} catch (_) { } catch (e) {
olmEnabled = false; olmEnabled = false;
Logs.warning('[LibOlm] Failed to load LibOlm: ' + _.toString()); Logs().e('[LibOlm] Failed to load LibOlm', e);
} }
Logs.success('[LibOlm] Enabled: $olmEnabled'); Logs().i('[LibOlm] Enabled: $olmEnabled');
if (!olmEnabled) return; if (!olmEnabled) return;

View File

@ -32,11 +32,11 @@ void main() {
try { try {
olm.init(); olm.init();
olm.Account(); olm.Account();
} catch (_) { } catch (e) {
olmEnabled = false; olmEnabled = false;
Logs.warning('[LibOlm] Failed to load LibOlm: ' + _.toString()); Logs().e('[LibOlm] Failed to load LibOlm', e);
} }
Logs.success('[LibOlm] Enabled: $olmEnabled'); Logs().i('[LibOlm] Enabled: $olmEnabled');
if (!olmEnabled) return; if (!olmEnabled) return;

View File

@ -29,11 +29,11 @@ void main() {
try { try {
olm.init(); olm.init();
olm.Account(); olm.Account();
} catch (_) { } catch (e) {
olmEnabled = false; olmEnabled = false;
Logs.warning('[LibOlm] Failed to load LibOlm: ' + _.toString()); Logs().e('[LibOlm] Failed to load LibOlm', e);
} }
Logs.success('[LibOlm] Enabled: $olmEnabled'); Logs().i('[LibOlm] Enabled: $olmEnabled');
if (!olmEnabled) return; if (!olmEnabled) return;

View File

@ -35,11 +35,11 @@ void main() {
try { try {
olm.init(); olm.init();
olm.Account(); olm.Account();
} catch (_) { } catch (e) {
olmEnabled = false; olmEnabled = false;
Logs.warning('[LibOlm] Failed to load LibOlm: ' + _.toString()); Logs().e('[LibOlm] Failed to load LibOlm', e);
} }
Logs.success('[LibOlm] Enabled: $olmEnabled'); Logs().i('[LibOlm] Enabled: $olmEnabled');
if (!olmEnabled) return; if (!olmEnabled) return;

View File

@ -31,11 +31,11 @@ void main() {
try { try {
olm.init(); olm.init();
olm.Account(); olm.Account();
} catch (_) { } catch (e) {
olmEnabled = false; olmEnabled = false;
Logs.warning('[LibOlm] Failed to load LibOlm: ' + _.toString()); Logs().e('[LibOlm] Failed to load LibOlm', e);
} }
Logs.success('[LibOlm] Enabled: $olmEnabled'); Logs().i('[LibOlm] Enabled: $olmEnabled');
if (!olmEnabled) return; if (!olmEnabled) return;

View File

@ -44,11 +44,11 @@ void main() {
try { try {
olm.init(); olm.init();
olm.Account(); olm.Account();
} catch (_) { } catch (e) {
olmEnabled = false; olmEnabled = false;
Logs.warning('[LibOlm] Failed to load LibOlm: ' + _.toString()); Logs().e('[LibOlm] Failed to load LibOlm', e);
} }
Logs.success('[LibOlm] Enabled: $olmEnabled'); Logs().i('[LibOlm] Enabled: $olmEnabled');
if (!olmEnabled) return; if (!olmEnabled) return;
@ -107,7 +107,7 @@ void main() {
'requesting_device_id': 'OTHERDEVICE', 'requesting_device_id': 'OTHERDEVICE',
}); });
await matrix.encryption.keyManager.handleToDeviceEvent(event); await matrix.encryption.keyManager.handleToDeviceEvent(event);
Logs.info(FakeMatrixApi.calledEndpoints.keys.toString()); Logs().i(FakeMatrixApi.calledEndpoints.keys.toString());
expect( expect(
FakeMatrixApi.calledEndpoints.keys.any( FakeMatrixApi.calledEndpoints.keys.any(
(k) => k.startsWith('/client/r0/sendToDevice/m.room.encrypted')), (k) => k.startsWith('/client/r0/sendToDevice/m.room.encrypted')),

View File

@ -66,11 +66,11 @@ void main() {
try { try {
olm.init(); olm.init();
olm.Account(); olm.Account();
} catch (_) { } catch (e) {
olmEnabled = false; olmEnabled = false;
Logs.warning('[LibOlm] Failed to load LibOlm: ' + _.toString()); Logs().e('[LibOlm] Failed to load LibOlm', e);
} }
Logs.success('[LibOlm] Enabled: $olmEnabled'); Logs().i('[LibOlm] Enabled: $olmEnabled');
if (!olmEnabled) return; if (!olmEnabled) return;

View File

@ -32,11 +32,11 @@ void main() {
try { try {
olm.init(); olm.init();
olm.Account(); olm.Account();
} catch (_) { } catch (e) {
olmEnabled = false; olmEnabled = false;
Logs.warning('[LibOlm] Failed to load LibOlm: ' + _.toString()); Logs().e('[LibOlm] Failed to load LibOlm', e);
} }
Logs.success('[LibOlm] Enabled: $olmEnabled'); Logs().i('[LibOlm] Enabled: $olmEnabled');
if (!olmEnabled) return; if (!olmEnabled) return;

View File

@ -33,11 +33,11 @@ void main() {
try { try {
olm.init(); olm.init();
olm.Account(); olm.Account();
} catch (_) { } catch (e) {
olmEnabled = false; olmEnabled = false;
Logs.warning('[LibOlm] Failed to load LibOlm: ' + _.toString()); Logs().e('[LibOlm] Failed to load LibOlm', e);
} }
Logs.success('[LibOlm] Enabled: $olmEnabled'); Logs().i('[LibOlm] Enabled: $olmEnabled');
if (!olmEnabled) return; if (!olmEnabled) return;

View File

@ -49,11 +49,11 @@ void main() {
try { try {
olm.init(); olm.init();
olm.Account(); olm.Account();
} catch (_) { } catch (e) {
olmEnabled = false; olmEnabled = false;
Logs.warning('[LibOlm] Failed to load LibOlm: ' + _.toString()); Logs().e('[LibOlm] Failed to load LibOlm', e);
} }
Logs.success('[LibOlm] Enabled: $olmEnabled'); Logs().i('[LibOlm] Enabled: $olmEnabled');
if (!olmEnabled) return; if (!olmEnabled) return;

View File

@ -38,11 +38,11 @@ void main() {
try { try {
olm.init(); olm.init();
olm.Account(); olm.Account();
} catch (_) { } catch (e) {
olmEnabled = false; olmEnabled = false;
Logs.warning('[LibOlm] Failed to load LibOlm: ' + _.toString()); Logs().e('[LibOlm] Failed to load LibOlm', e);
} }
Logs.success('[LibOlm] Enabled: $olmEnabled'); Logs().i('[LibOlm] Enabled: $olmEnabled');
final timestamp = DateTime.now().millisecondsSinceEpoch; final timestamp = DateTime.now().millisecondsSinceEpoch;
final id = '!4fsdfjisjf:server.abc'; final id = '!4fsdfjisjf:server.abc';

View File

@ -24,6 +24,7 @@ import 'package:famedlysdk/matrix_api/model/matrix_exception.dart';
import 'package:famedlysdk/matrix_api/model/presence_content.dart'; import 'package:famedlysdk/matrix_api/model/presence_content.dart';
import 'package:famedlysdk/matrix_api/model/push_rule_set.dart'; import 'package:famedlysdk/matrix_api/model/push_rule_set.dart';
import 'package:famedlysdk/matrix_api/model/pusher.dart'; import 'package:famedlysdk/matrix_api/model/pusher.dart';
import 'package:famedlysdk/matrix_api/utils/logs.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'fake_matrix_api.dart'; import 'fake_matrix_api.dart';
@ -34,6 +35,20 @@ void main() {
final matrixApi = MatrixApi( final matrixApi = MatrixApi(
httpClient: FakeMatrixApi(), httpClient: FakeMatrixApi(),
); );
test('Logs', () {
Logs().i('Info');
Logs().d('Debug');
Logs().v('Verbose');
Logs().w('Warning');
Logs().wtf('Critical Error');
Logs().e('Error');
try {
throw 'Exception';
} catch (e, s) {
Logs().e('Caught', e, s);
}
});
test('MatrixException test', () async { test('MatrixException test', () async {
final exception = MatrixException.fromJson({ final exception = MatrixException.fromJson({
'flows': [ 'flows': [

View File

@ -19,23 +19,23 @@ void test() async {
try { try {
await olm.init(); await olm.init();
olm.Account(); olm.Account();
Logs.success('[LibOlm] Enabled'); Logs().i('[LibOlm] Enabled');
Logs.success('++++ Login Alice at ++++'); Logs().i('++++ Login Alice at ++++');
testClientA = Client('TestClientA', databaseBuilder: getDatabase); testClientA = Client('TestClientA', databaseBuilder: getDatabase);
await testClientA.checkHomeserver(TestUser.homeserver); await testClientA.checkHomeserver(TestUser.homeserver);
await testClientA.login( await testClientA.login(
user: TestUser.username, password: TestUser.password); user: TestUser.username, password: TestUser.password);
assert(testClientA.encryptionEnabled); assert(testClientA.encryptionEnabled);
Logs.success('++++ Login Bob ++++'); Logs().i('++++ Login Bob ++++');
testClientB = Client('TestClientB', databaseBuilder: getDatabase); testClientB = Client('TestClientB', databaseBuilder: getDatabase);
await testClientB.checkHomeserver(TestUser.homeserver); await testClientB.checkHomeserver(TestUser.homeserver);
await testClientB.login( await testClientB.login(
user: TestUser.username2, password: TestUser.password); user: TestUser.username2, password: TestUser.password);
assert(testClientB.encryptionEnabled); assert(testClientB.encryptionEnabled);
Logs.success('++++ (Alice) Leave all rooms ++++'); Logs().i('++++ (Alice) Leave all rooms ++++');
while (testClientA.rooms.isNotEmpty) { while (testClientA.rooms.isNotEmpty) {
var room = testClientA.rooms.first; var room = testClientA.rooms.first;
if (room.canonicalAlias?.isNotEmpty ?? false) { if (room.canonicalAlias?.isNotEmpty ?? false) {
@ -47,7 +47,7 @@ void test() async {
} catch (_) {} } catch (_) {}
} }
Logs.success('++++ (Bob) Leave all rooms ++++'); Logs().i('++++ (Bob) Leave all rooms ++++');
for (var i = 0; i < 3; i++) { for (var i = 0; i < 3; i++) {
if (testClientB.rooms.isNotEmpty) { if (testClientB.rooms.isNotEmpty) {
var room = testClientB.rooms.first; var room = testClientB.rooms.first;
@ -58,7 +58,7 @@ void test() async {
} }
} }
Logs.success('++++ Check if own olm device is verified by default ++++'); Logs().i('++++ Check if own olm device is verified by default ++++');
assert(testClientA.userDeviceKeys.containsKey(TestUser.username)); assert(testClientA.userDeviceKeys.containsKey(TestUser.username));
assert(testClientA.userDeviceKeys[TestUser.username].deviceKeys assert(testClientA.userDeviceKeys[TestUser.username].deviceKeys
.containsKey(testClientA.deviceID)); .containsKey(testClientA.deviceID));
@ -74,20 +74,20 @@ void test() async {
assert(!testClientB.userDeviceKeys[TestUser.username2] assert(!testClientB.userDeviceKeys[TestUser.username2]
.deviceKeys[testClientB.deviceID].blocked); .deviceKeys[testClientB.deviceID].blocked);
Logs.success('++++ (Alice) Create room and invite Bob ++++'); Logs().i('++++ (Alice) Create room and invite Bob ++++');
await testClientA.createRoom(invite: [TestUser.username2]); await testClientA.createRoom(invite: [TestUser.username2]);
await Future.delayed(Duration(seconds: 1)); await Future.delayed(Duration(seconds: 1));
var room = testClientA.rooms.first; var room = testClientA.rooms.first;
assert(room != null); assert(room != null);
final roomId = room.id; final roomId = room.id;
Logs.success('++++ (Bob) Join room ++++'); Logs().i('++++ (Bob) Join room ++++');
var inviteRoom = testClientB.getRoomById(roomId); var inviteRoom = testClientB.getRoomById(roomId);
await inviteRoom.join(); await inviteRoom.join();
await Future.delayed(Duration(seconds: 1)); await Future.delayed(Duration(seconds: 1));
assert(inviteRoom.membership == Membership.join); assert(inviteRoom.membership == Membership.join);
Logs.success('++++ (Alice) Enable encryption ++++'); Logs().i('++++ (Alice) Enable encryption ++++');
assert(room.encrypted == false); assert(room.encrypted == false);
await room.enableEncryption(); await room.enableEncryption();
await Future.delayed(Duration(seconds: 5)); await Future.delayed(Duration(seconds: 5));
@ -95,7 +95,7 @@ void test() async {
assert(room.client.encryption.keyManager.getOutboundGroupSession(room.id) == assert(room.client.encryption.keyManager.getOutboundGroupSession(room.id) ==
null); null);
Logs.success('++++ (Alice) Check known olm devices ++++'); Logs().i('++++ (Alice) Check known olm devices ++++');
assert(testClientA.userDeviceKeys.containsKey(TestUser.username2)); assert(testClientA.userDeviceKeys.containsKey(TestUser.username2));
assert(testClientA.userDeviceKeys[TestUser.username2].deviceKeys assert(testClientA.userDeviceKeys[TestUser.username2].deviceKeys
.containsKey(testClientB.deviceID)); .containsKey(testClientB.deviceID));
@ -114,7 +114,7 @@ void test() async {
.userDeviceKeys[TestUser.username2].deviceKeys[testClientB.deviceID] .userDeviceKeys[TestUser.username2].deviceKeys[testClientB.deviceID]
.setVerified(true); .setVerified(true);
Logs.success('++++ Check if own olm device is verified by default ++++'); Logs().i('++++ Check if own olm device is verified by default ++++');
assert(testClientA.userDeviceKeys.containsKey(TestUser.username)); assert(testClientA.userDeviceKeys.containsKey(TestUser.username));
assert(testClientA.userDeviceKeys[TestUser.username].deviceKeys assert(testClientA.userDeviceKeys[TestUser.username].deviceKeys
.containsKey(testClientA.deviceID)); .containsKey(testClientA.deviceID));
@ -126,7 +126,7 @@ void test() async {
assert(testClientB.userDeviceKeys[TestUser.username2] assert(testClientB.userDeviceKeys[TestUser.username2]
.deviceKeys[testClientB.deviceID].verified); .deviceKeys[testClientB.deviceID].verified);
Logs.success("++++ (Alice) Send encrypted message: '$testMessage' ++++"); Logs().i("++++ (Alice) Send encrypted message: '$testMessage' ++++");
await room.sendTextEvent(testMessage); await room.sendTextEvent(testMessage);
await Future.delayed(Duration(seconds: 5)); await Future.delayed(Duration(seconds: 5));
assert(room.client.encryption.keyManager.getOutboundGroupSession(room.id) != assert(room.client.encryption.keyManager.getOutboundGroupSession(room.id) !=
@ -153,11 +153,10 @@ void test() async {
null);*/ null);*/
assert(room.lastMessage == testMessage); assert(room.lastMessage == testMessage);
assert(inviteRoom.lastMessage == testMessage); assert(inviteRoom.lastMessage == testMessage);
Logs.success( Logs().i(
"++++ (Bob) Received decrypted message: '${inviteRoom.lastMessage}' ++++"); "++++ (Bob) Received decrypted message: '${inviteRoom.lastMessage}' ++++");
Logs.success( Logs().i("++++ (Alice) Send again encrypted message: '$testMessage2' ++++");
"++++ (Alice) Send again encrypted message: '$testMessage2' ++++");
await room.sendTextEvent(testMessage2); await room.sendTextEvent(testMessage2);
await Future.delayed(Duration(seconds: 5)); await Future.delayed(Duration(seconds: 5));
assert(testClientA.encryption.olmManager assert(testClientA.encryption.olmManager
@ -181,11 +180,10 @@ void test() async {
null);*/ null);*/
assert(room.lastMessage == testMessage2); assert(room.lastMessage == testMessage2);
assert(inviteRoom.lastMessage == testMessage2); assert(inviteRoom.lastMessage == testMessage2);
Logs.success( Logs().i(
"++++ (Bob) Received decrypted message: '${inviteRoom.lastMessage}' ++++"); "++++ (Bob) Received decrypted message: '${inviteRoom.lastMessage}' ++++");
Logs.success( Logs().i("++++ (Bob) Send again encrypted message: '$testMessage3' ++++");
"++++ (Bob) Send again encrypted message: '$testMessage3' ++++");
await inviteRoom.sendTextEvent(testMessage3); await inviteRoom.sendTextEvent(testMessage3);
await Future.delayed(Duration(seconds: 5)); await Future.delayed(Duration(seconds: 5));
assert(testClientA.encryption.olmManager assert(testClientA.encryption.olmManager
@ -215,18 +213,17 @@ void test() async {
null);*/ null);*/
assert(inviteRoom.lastMessage == testMessage3); assert(inviteRoom.lastMessage == testMessage3);
assert(room.lastMessage == testMessage3); assert(room.lastMessage == testMessage3);
Logs.success( Logs().i(
"++++ (Alice) Received decrypted message: '${room.lastMessage}' ++++"); "++++ (Alice) Received decrypted message: '${room.lastMessage}' ++++");
Logs.success('++++ Login Bob in another client ++++'); Logs().i('++++ Login Bob in another client ++++');
var testClientC = Client('TestClientC', databaseBuilder: getDatabase); var testClientC = Client('TestClientC', databaseBuilder: getDatabase);
await testClientC.checkHomeserver(TestUser.homeserver); await testClientC.checkHomeserver(TestUser.homeserver);
await testClientC.login( await testClientC.login(
user: TestUser.username2, password: TestUser.password); user: TestUser.username2, password: TestUser.password);
await Future.delayed(Duration(seconds: 3)); await Future.delayed(Duration(seconds: 3));
Logs.success( Logs().i("++++ (Alice) Send again encrypted message: '$testMessage4' ++++");
"++++ (Alice) Send again encrypted message: '$testMessage4' ++++");
await room.sendTextEvent(testMessage4); await room.sendTextEvent(testMessage4);
await Future.delayed(Duration(seconds: 5)); await Future.delayed(Duration(seconds: 5));
assert(testClientA.encryption.olmManager assert(testClientA.encryption.olmManager
@ -263,17 +260,16 @@ void test() async {
null);*/ null);*/
assert(room.lastMessage == testMessage4); assert(room.lastMessage == testMessage4);
assert(inviteRoom.lastMessage == testMessage4); assert(inviteRoom.lastMessage == testMessage4);
Logs.success( Logs().i(
"++++ (Bob) Received decrypted message: '${inviteRoom.lastMessage}' ++++"); "++++ (Bob) Received decrypted message: '${inviteRoom.lastMessage}' ++++");
Logs.success('++++ Logout Bob another client ++++'); Logs().i('++++ Logout Bob another client ++++');
await testClientC.dispose(closeDatabase: false); await testClientC.dispose(closeDatabase: false);
await testClientC.logout(); await testClientC.logout();
testClientC = null; testClientC = null;
await Future.delayed(Duration(seconds: 5)); await Future.delayed(Duration(seconds: 5));
Logs.success( Logs().i("++++ (Alice) Send again encrypted message: '$testMessage6' ++++");
"++++ (Alice) Send again encrypted message: '$testMessage6' ++++");
await room.sendTextEvent(testMessage6); await room.sendTextEvent(testMessage6);
await Future.delayed(Duration(seconds: 5)); await Future.delayed(Duration(seconds: 5));
assert(testClientA.encryption.olmManager assert(testClientA.encryption.olmManager
@ -300,7 +296,7 @@ void test() async {
null);*/ null);*/
assert(room.lastMessage == testMessage6); assert(room.lastMessage == testMessage6);
assert(inviteRoom.lastMessage == testMessage6); assert(inviteRoom.lastMessage == testMessage6);
Logs.success( Logs().i(
"++++ (Bob) Received decrypted message: '${inviteRoom.lastMessage}' ++++"); "++++ (Bob) Received decrypted message: '${inviteRoom.lastMessage}' ++++");
await room.leave(); await room.leave();
@ -309,10 +305,10 @@ void test() async {
await inviteRoom.forget(); await inviteRoom.forget();
await Future.delayed(Duration(seconds: 1)); await Future.delayed(Duration(seconds: 1));
} catch (e, s) { } catch (e, s) {
Logs.error('Test failed: ${e.toString()}', s); Logs().e('Test failed', e, s);
rethrow; rethrow;
} finally { } finally {
Logs.success('++++ Logout Alice and Bob ++++'); Logs().i('++++ Logout Alice and Bob ++++');
if (testClientA?.isLogged() ?? false) await testClientA.logoutAll(); if (testClientA?.isLogged() ?? false) await testClientA.logoutAll();
if (testClientA?.isLogged() ?? false) await testClientB.logoutAll(); if (testClientA?.isLogged() ?? false) await testClientB.logoutAll();
await testClientA?.dispose(closeDatabase: false); await testClientA?.dispose(closeDatabase: false);