refactor: Added and applied require_trailing_commas linter rule

This commit is contained in:
Malin Errenst 2023-03-02 10:57:52 +01:00
commit ec7acc5385
112 changed files with 3466 additions and 2855 deletions

View file

@ -55,10 +55,12 @@ extension AccountBundlesExtension on Client {
}
ret ??= [];
if (ret.isEmpty) {
ret.add(AccountBundle(
name: userID,
priority: 0,
));
ret.add(
AccountBundle(
name: userID,
priority: 0,
),
);
}
return ret;
}

View file

@ -78,7 +78,8 @@ class BackgroundPush {
firebase?.setListeners(
onMessage: (message) => pushHelper(
PushNotification.fromJson(
Map<String, dynamic>.from(message['data'] ?? message)),
Map<String, dynamic>.from(message['data'] ?? message),
),
client: client,
l10n: l10n,
activeRoomId: router?.currentState?.pathParameters['roomid'],
@ -331,7 +332,8 @@ class BackgroundPush {
}
} catch (e) {
Logs().i(
'[Push] No self-hosted unified push gateway present: $newEndpoint');
'[Push] No self-hosted unified push gateway present: $newEndpoint',
);
}
Logs().i('[Push] UnifiedPush using endpoint $endpoint');
final oldTokens = <String?>{};
@ -366,7 +368,8 @@ class BackgroundPush {
Future<void> _onUpMessage(Uint8List message, String i) async {
upAction = true;
final data = Map<String, dynamic>.from(
json.decode(utf8.decode(message))['notification']);
json.decode(utf8.decode(message))['notification'],
);
// UP may strip the devices list
data['devices'] ??= [];
await pushHelper(
@ -382,8 +385,11 @@ class BackgroundPush {
/// IDs we map the [roomId] to a number and store this number.
late Map<String, int> idMap;
Future<void> _loadIdMap() async {
idMap = Map<String, int>.from(json.decode(
(await store.getItem(SettingKeys.notificationCurrentIds)) ?? '{}'));
idMap = Map<String, int>.from(
json.decode(
(await store.getItem(SettingKeys.notificationCurrentIds)) ?? '{}',
),
);
}
Future<int> mapRoomIdToInt(String roomId) async {
@ -441,7 +447,8 @@ class BackgroundPush {
if (syncErrored) {
try {
Logs().v(
'[Push] failed to sync for fallback push, fetching notifications endpoint...');
'[Push] failed to sync for fallback push, fetching notifications endpoint...',
);
final notifications = await client.getNotifications(limit: 20);
final notificationRooms =
notifications.notifications.map((n) => n.roomId).toSet();
@ -450,8 +457,9 @@ class BackgroundPush {
.map((r) => r.id);
} catch (e) {
Logs().v(
'[Push] failed to fetch pending notifications for clearing push, falling back...',
e);
'[Push] failed to fetch pending notifications for clearing push, falling back...',
e,
);
emptyRooms = client.rooms
.where((r) => r.notificationCount == 0)
.map((r) => r.id);
@ -474,7 +482,9 @@ class BackgroundPush {
}
if (changed) {
await store.setItem(
SettingKeys.notificationCurrentIds, json.encode(idMap));
SettingKeys.notificationCurrentIds,
json.encode(idMap),
);
}
} finally {
_clearingPushLock = false;

View file

@ -39,19 +39,25 @@ abstract class ClientManager {
}
final clients = clientNames.map(createClient).toList();
if (initialize) {
await Future.wait(clients.map((client) => client
.init(
waitForFirstSync: false,
waitUntilLoadCompletedLoaded: false,
)
.catchError(
(e, s) => Logs().e('Unable to initialize client', e, s))));
await Future.wait(
clients.map(
(client) => client
.init(
waitForFirstSync: false,
waitUntilLoadCompletedLoaded: false,
)
.catchError(
(e, s) => Logs().e('Unable to initialize client', e, s),
),
),
);
}
if (clients.length > 1 && clients.any((c) => !c.isLogged())) {
final loggedOutClients = clients.where((c) => !c.isLogged()).toList();
for (final client in loggedOutClients) {
Logs().w(
'Multi account is enabled but client ${client.userID} is not logged in. Removing...');
'Multi account is enabled but client ${client.userID} is not logged in. Removing...',
);
clientNames.remove(client.clientName);
clients.remove(client);
}

View file

@ -5,7 +5,8 @@ import 'package:matrix/matrix.dart';
import 'package:native_imaging/native_imaging.dart' as native;
Future<MatrixImageFileResizedResponse?> customImageResizer(
MatrixImageFileResizeArguments arguments) async {
MatrixImageFileResizeArguments arguments,
) async {
await native.init();
late native.Image nativeImg;
@ -21,7 +22,10 @@ Future<MatrixImageFileResizedResponse?> customImageResizer(
return null;
}
final rgba = Uint8List.view(
rgbaData.buffer, rgbaData.offsetInBytes, rgbaData.lengthInBytes);
rgbaData.buffer,
rgbaData.offsetInBytes,
rgbaData.lengthInBytes,
);
final width = dartFrame.image.width;
final height = dartFrame.image.height;

View file

@ -77,10 +77,15 @@ extension DateTimeExtension on DateTime {
}
} else if (sameYear) {
return L10n.of(context)!.dateWithoutYear(
month.toString().padLeft(2, '0'), day.toString().padLeft(2, '0'));
month.toString().padLeft(2, '0'),
day.toString().padLeft(2, '0'),
);
}
return L10n.of(context)!.dateWithYear(year.toString(),
month.toString().padLeft(2, '0'), day.toString().padLeft(2, '0'));
return L10n.of(context)!.dateWithYear(
year.toString(),
month.toString().padLeft(2, '0'),
day.toString().padLeft(2, '0'),
);
}
/// If the DateTime is today, this returns [localizedTimeOfDay()], if not it also
@ -95,7 +100,9 @@ extension DateTimeExtension on DateTime {
if (sameDay) return localizedTimeOfDay(context);
return L10n.of(context)!.dateAndTimeOfDay(
localizedTimeShort(context), localizedTimeOfDay(context));
localizedTimeShort(context),
localizedTimeOfDay(context),
);
}
static String _z(int i) => i < 10 ? '0${i.toString()}' : i.toString();

View file

@ -19,7 +19,8 @@ abstract class FluffyShare {
ClipboardData(text: text),
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(L10n.of(context)!.copiedToClipboard)));
SnackBar(content: Text(L10n.of(context)!.copiedToClipboard)),
);
return;
}
}

View file

@ -15,8 +15,10 @@ extension ClientStoriesExtension on Client {
List<User> get contacts => rooms
.where((room) => room.isDirectChat)
.map((room) =>
room.unsafeGetUserFromMemoryOrFallback(room.directChatMatrixID!))
.map(
(room) =>
room.unsafeGetUserFromMemoryOrFallback(room.directChatMatrixID!),
)
.toList();
List<Room> get storiesRooms =>
@ -78,23 +80,30 @@ extension ClientStoriesExtension on Client {
}
Future<Room?> getStoriesRoom(BuildContext context) async {
final candidates = rooms.where((room) =>
room.getState(EventTypes.RoomCreate)?.content.tryGet<String>('type') ==
storiesRoomType &&
room.ownPowerLevel >= 100);
final candidates = rooms.where(
(room) =>
room
.getState(EventTypes.RoomCreate)
?.content
.tryGet<String>('type') ==
storiesRoomType &&
room.ownPowerLevel >= 100,
);
if (candidates.isEmpty) return null;
if (candidates.length == 1) return candidates.single;
return await showModalActionSheet<Room>(
context: context,
actions: candidates
.map(
(room) => SheetAction(
label: room.getLocalizedDisplayname(
MatrixLocals(L10n.of(context)!),
),
key: room),
)
.toList());
context: context,
actions: candidates
.map(
(room) => SheetAction(
label: room.getLocalizedDisplayname(
MatrixLocals(L10n.of(context)!),
),
key: room,
),
)
.toList(),
);
}
}

View file

@ -23,7 +23,8 @@ class FlutterHiveCollectionsDatabase extends HiveCollectionsDatabase {
static const String _cipherStorageKey = 'hive_encryption_key';
static Future<FlutterHiveCollectionsDatabase> databaseBuilder(
Client client) async {
Client client,
) async {
Logs().d('Open Hive...');
HiveAesCipher? hiverCipher;
try {
@ -96,9 +97,9 @@ class FlutterHiveCollectionsDatabase extends HiveCollectionsDatabase {
}
}
// do not destroy your stable FluffyChat in debug mode
directory = Directory(directory.uri
.resolve(kDebugMode ? 'hive_debug' : 'hive')
.toFilePath());
directory = Directory(
directory.uri.resolve(kDebugMode ? 'hive_debug' : 'hive').toFilePath(),
);
directory.create(recursive: true);
path = directory.path;
}

View file

@ -8,8 +8,9 @@ extension IosBadgeClientExtension on Client {
void updateIosBadge() {
if (PlatformInfos.isIOS) {
// Workaround for iOS not clearing notifications with fcm_shared_isolate
if (!rooms.any((r) =>
r.membership == Membership.invite || (r.notificationCount > 0))) {
if (!rooms.any(
(r) => r.membership == Membership.invite || (r.notificationCount > 0),
)) {
// ignore: unawaited_futures
FlutterLocalNotificationsPlugin().cancelAll();
FlutterAppBadger.removeBadge();

View file

@ -62,7 +62,9 @@ class MatrixLocals extends MatrixLocalizations {
@override
String changedTheGuestAccessRulesTo(
String senderName, String localizedString) {
String senderName,
String localizedString,
) {
return l10n.changedTheGuestAccessRulesTo(senderName, localizedString);
}
@ -73,7 +75,9 @@ class MatrixLocals extends MatrixLocalizations {
@override
String changedTheHistoryVisibilityTo(
String senderName, String localizedString) {
String senderName,
String localizedString,
) {
return l10n.changedTheHistoryVisibilityTo(senderName, localizedString);
}

View file

@ -111,7 +111,9 @@ Future<void> _tryPushHelper(
await flutterLocalNotificationsPlugin.cancelAll();
final store = await SharedPreferences.getInstance();
await store.setString(
SettingKeys.notificationCurrentIds, json.encode({}));
SettingKeys.notificationCurrentIds,
json.encode({}),
);
}
}
return;
@ -237,7 +239,8 @@ Future<void> _tryPushHelper(
Future<int> mapRoomIdToInt(String roomId) async {
final store = await SharedPreferences.getInstance();
final idMap = Map<String, int>.from(
jsonDecode(store.getString(SettingKeys.notificationCurrentIds) ?? '{}'));
jsonDecode(store.getString(SettingKeys.notificationCurrentIds) ?? '{}'),
);
int? currentInt;
try {
currentInt = idMap[roomId];

View file

@ -54,12 +54,14 @@ extension RoomStatusExtension on Room {
}
} else if (typingUsers.length == 2) {
typingText = L10n.of(context)!.userAndUserAreTyping(
typingUsers.first.calcDisplayname(),
typingUsers[1].calcDisplayname());
typingUsers.first.calcDisplayname(),
typingUsers[1].calcDisplayname(),
);
} else if (typingUsers.length > 2) {
typingText = L10n.of(context)!.userAndOthersAreTyping(
typingUsers.first.calcDisplayname(),
(typingUsers.length - 1).toString());
typingUsers.first.calcDisplayname(),
(typingUsers.length - 1).toString(),
);
}
return typingText;
}
@ -76,8 +78,10 @@ extension RoomStatusExtension on Room {
break;
}
}
lastReceipts.removeWhere((user) =>
user.id == client.userID || user.id == timeline.events.first.senderId);
lastReceipts.removeWhere(
(user) =>
user.id == client.userID || user.id == timeline.events.first.senderId,
);
return lastReceipts.toList();
}
}

View file

@ -33,9 +33,11 @@ extension StreamExtension on Stream {
gotMessage = true;
}
};
final subscription = listen((_) => onMessage?.call(),
onDone: () => controller.close(),
onError: (e, s) => controller.addError(e, s));
final subscription = listen(
(_) => onMessage?.call(),
onDone: () => controller.close(),
onError: (e, s) => controller.addError(e, s),
);
// add proper cleanup to the subscription and the controller, to not memory leak
controller.onCancel = () {
subscription.cancel();

View file

@ -82,7 +82,8 @@ extension UiaRequestManager on MatrixState {
);
default:
final url = Uri.parse(
'${client.homeserver}/_matrix/client/r0/auth/$stage/fallback/web?session=${uiaRequest.session}');
'${client.homeserver}/_matrix/client/r0/auth/$stage/fallback/web?session=${uiaRequest.session}',
);
launchUrlString(url.toString());
if (OkCancelResult.ok ==
await showOkCancelAlertDialog(

View file

@ -20,7 +20,8 @@ class UpdateCheckerNoStore {
static const gitLabHost = 'gitlab.com';
static Uri get tagsUri => Uri.parse(
'https://$gitLabHost/projects/$gitLabProjectId/repository/tags');
'https://$gitLabHost/projects/$gitLabProjectId/repository/tags',
);
final BuildContext context;

View file

@ -33,7 +33,8 @@ class UrlLauncher {
if (uri == null) {
// we can't open this thing
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(L10n.of(context)!.cantOpenUri(url!))));
SnackBar(content: Text(L10n.of(context)!.cantOpenUri(url!))),
);
return;
}
if (!{'https', 'http'}.contains(uri.scheme)) {
@ -61,7 +62,8 @@ class UrlLauncher {
// transmute geo URIs on desktop to openstreetmap links, as those usually can't handle
// geo URIs
launchUrlString(
'https://www.openstreetmap.org/?mlat=${latlong.first}&mlon=${latlong.last}#map=16/${latlong.first}/${latlong.last}');
'https://www.openstreetmap.org/?mlat=${latlong.first}&mlon=${latlong.last}#map=16/${latlong.first}/${latlong.last}',
);
}
return;
}
@ -71,7 +73,8 @@ class UrlLauncher {
}
if (uri.host.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(L10n.of(context)!.cantOpenUri(url!))));
SnackBar(content: Text(L10n.of(context)!.cantOpenUri(url!))),
);
return;
}
// okay, we have either an http or an https URI.
@ -86,8 +89,10 @@ class UrlLauncher {
}).join('.');
// Force LaunchMode.externalApplication, otherwise url_launcher will default
// to opening links in a webview on mobile platforms.
launchUrlString(uri.replace(host: newHost).toString(),
mode: LaunchMode.externalApplication);
launchUrlString(
uri.replace(host: newHost).toString(),
mode: LaunchMode.externalApplication,
);
}
void openMatrixToUrl() async {
@ -142,8 +147,10 @@ class UrlLauncher {
}
// we have the room, so....just open it
if (event != null) {
VRouter.of(context).toSegments(['rooms', room.id],
queryParameters: {'event': event});
VRouter.of(context).toSegments(
['rooms', room.id],
queryParameters: {'event': event},
);
} else {
VRouter.of(context).toSegments(['rooms', room.id]);
}
@ -175,11 +182,14 @@ class UrlLauncher {
if (response.error != null) return;
// wait for two seconds so that it probably came down /sync
await showFutureLoadingDialog(
context: context,
future: () => Future.delayed(const Duration(seconds: 2)));
context: context,
future: () => Future.delayed(const Duration(seconds: 2)),
);
if (event != null) {
VRouter.of(context).toSegments(['rooms', response.result!],
queryParameters: {'event': event});
VRouter.of(context).toSegments(
['rooms', response.result!],
queryParameters: {'event': event},
);
} else {
VRouter.of(context).toSegments(['rooms', response.result!]);
}

View file

@ -111,14 +111,15 @@ class CallKeepManager {
Future<void> showCallkitIncoming(CallSession call) async {
if (!setupDone) {
await _callKeep.setup(
null,
<String, dynamic>{
'ios': <String, dynamic>{
'appName': appName,
},
'android': alertOptions,
null,
<String, dynamic>{
'ios': <String, dynamic>{
'appName': appName,
},
backgroundMode: true);
'android': alertOptions,
},
backgroundMode: true,
);
}
setupDone = true;
await displayIncomingCall(call);
@ -131,7 +132,8 @@ class CallKeepManager {
(event) {
if (event == CallEvent.kLocalHoldUnhold) {
Logs().i(
'Call hold event: local ${call.localHold}, remote ${call.remoteOnHold}');
'Call hold event: local ${call.localHold}, remote ${call.remoteOnHold}',
);
}
},
);
@ -169,10 +171,14 @@ class CallKeepManager {
_callKeep.on(CallKeepPerformAnswerCallAction(), answerCall);
_callKeep.on(CallKeepDidPerformDTMFAction(), didPerformDTMFAction);
_callKeep.on(
CallKeepDidReceiveStartCallAction(), didReceiveStartCallAction);
CallKeepDidReceiveStartCallAction(),
didReceiveStartCallAction,
);
_callKeep.on(CallKeepDidToggleHoldAction(), didToggleHoldCallAction);
_callKeep.on(
CallKeepDidPerformSetMutedCallAction(), didPerformSetMutedCallAction);
CallKeepDidPerformSetMutedCallAction(),
didPerformSetMutedCallAction,
);
_callKeep.on(CallKeepPerformEndCallAction(), endCall);
_callKeep.on(CallKeepPushKitToken(), onPushKitToken);
_callKeep.on(CallKeepDidDisplayIncomingCall(), didDisplayIncomingCall);
@ -209,11 +215,17 @@ class CallKeepManager {
Future<void> updateDisplay(String callUUID) async {
// Workaround because Android doesn't display well displayName, se we have to switch ...
if (isIOS) {
await _callKeep.updateDisplay(callUUID,
displayName: 'New Name', handle: callUUID);
await _callKeep.updateDisplay(
callUUID,
displayName: 'New Name',
handle: callUUID,
);
} else {
await _callKeep.updateDisplay(callUUID,
displayName: callUUID, handle: 'New Name');
await _callKeep.updateDisplay(
callUUID,
displayName: callUUID,
handle: 'New Name',
);
}
}
@ -250,7 +262,8 @@ class CallKeepManager {
const Divider(),
ListTile(
onTap: () => FlutterForegroundTask.openSystemAlertWindowSettings(
forceOpen: true),
forceOpen: true,
),
title: Text(L10n.of(context)!.appearOnTop),
subtitle: Text(L10n.of(context)!.appearOnTopDetails),
trailing: const Icon(Icons.file_upload_rounded),
@ -310,7 +323,8 @@ class CallKeepManager {
}
Future<void> didReceiveStartCallAction(
CallKeepDidReceiveStartCallAction event) async {
CallKeepDidReceiveStartCallAction event,
) async {
if (event.handle == null) {
// @TODO: sometime we receive `didReceiveStartCallAction` with handle` undefined`
return;
@ -328,7 +342,8 @@ class CallKeepManager {
}
Future<void> didPerformSetMutedCallAction(
CallKeepDidPerformSetMutedCallAction event) async {
CallKeepDidPerformSetMutedCallAction event,
) async {
final keeper = calls[event.callUUID];
if (event.muted!) {
keeper!.call.setMicrophoneMuted(true);
@ -339,7 +354,8 @@ class CallKeepManager {
}
Future<void> didToggleHoldCallAction(
CallKeepDidToggleHoldAction event) async {
CallKeepDidToggleHoldAction event,
) async {
final keeper = calls[event.callUUID];
if (event.hold!) {
keeper!.call.setRemoteOnHold(true);

View file

@ -82,14 +82,15 @@ class VoipPlugin with WidgetsBindingObserver implements WebRTCDelegate {
} else {
overlayEntry = OverlayEntry(
builder: (_) => Calling(
context: context,
client: client,
callId: callId,
call: call,
onClear: () {
overlayEntry?.remove();
overlayEntry = null;
}),
context: context,
client: client,
callId: callId,
call: call,
onClear: () {
overlayEntry?.remove();
overlayEntry = null;
},
),
);
Overlay.of(context).insert(overlayEntry!);
}
@ -103,8 +104,9 @@ class VoipPlugin with WidgetsBindingObserver implements WebRTCDelegate {
@override
Future<RTCPeerConnection> createPeerConnection(
Map<String, dynamic> configuration,
[Map<String, dynamic> constraints = const {}]) =>
Map<String, dynamic> configuration, [
Map<String, dynamic> constraints = const {},
]) =>
webrtc_impl.createPeerConnection(configuration, constraints);
@override
@ -150,7 +152,9 @@ class VoipPlugin with WidgetsBindingObserver implements WebRTCDelegate {
try {
final wasForeground = await FlutterForegroundTask.isAppOnForeground;
await Store().setItem(
'wasForeground', wasForeground == true ? 'true' : 'false');
'wasForeground',
wasForeground == true ? 'true' : 'false',
);
FlutterForegroundTask.setOnLockScreenVisibility(true);
FlutterForegroundTask.wakeUpScreen();
FlutterForegroundTask.launchApp();
@ -162,10 +166,13 @@ class VoipPlugin with WidgetsBindingObserver implements WebRTCDelegate {
try {
if (!hasCallingAccount) {
ScaffoldMessenger.of(FluffyChatApp.routerKey.currentContext!)
.showSnackBar(const SnackBar(
content: Text(
'No calling accounts found (used for native calls UI)',
)));
.showSnackBar(
const SnackBar(
content: Text(
'No calling accounts found (used for native calls UI)',
),
),
);
}
} catch (e) {
Logs().e('failed to show snackbar');