Initial commit
This commit is contained in:
105
lib/utils/account_bundles.dart
Normal file
105
lib/utils/account_bundles.dart
Normal file
@@ -0,0 +1,105 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class AccountBundles {
|
||||
String? prefix;
|
||||
List<AccountBundle>? bundles;
|
||||
|
||||
AccountBundles({this.prefix, this.bundles});
|
||||
|
||||
AccountBundles.fromJson(Map<String, dynamic> json)
|
||||
: prefix = json.tryGet<String>('prefix'),
|
||||
bundles = json['bundles'] is List
|
||||
? json['bundles']
|
||||
.map((b) {
|
||||
try {
|
||||
return AccountBundle.fromJson(b);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.whereType<AccountBundle>()
|
||||
.toList()
|
||||
: null;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
if (prefix != null) 'prefix': prefix,
|
||||
if (bundles != null) 'bundles': bundles!.map((v) => v.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
|
||||
class AccountBundle {
|
||||
String? name;
|
||||
int? priority;
|
||||
|
||||
AccountBundle({this.name, this.priority});
|
||||
|
||||
AccountBundle.fromJson(Map<String, dynamic> json)
|
||||
: name = json.tryGet<String>('name'),
|
||||
priority = json.tryGet<int>('priority');
|
||||
|
||||
Map<String, dynamic> toJson() => <String, dynamic>{
|
||||
if (name != null) 'name': name,
|
||||
if (priority != null) 'priority': priority,
|
||||
};
|
||||
}
|
||||
|
||||
const accountBundlesType = 'im.fluffychat.account_bundles';
|
||||
|
||||
extension AccountBundlesExtension on Client {
|
||||
List<AccountBundle> get accountBundles {
|
||||
List<AccountBundle>? ret;
|
||||
if (accountData.containsKey(accountBundlesType)) {
|
||||
ret = AccountBundles.fromJson(
|
||||
accountData[accountBundlesType]!.content,
|
||||
).bundles;
|
||||
}
|
||||
ret ??= [];
|
||||
if (ret.isEmpty) {
|
||||
ret.add(AccountBundle(name: userID, priority: 0));
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
Future<void> setAccountBundle(String name, [int? priority]) async {
|
||||
final data = AccountBundles.fromJson(
|
||||
accountData[accountBundlesType]?.content ?? {},
|
||||
);
|
||||
var foundBundle = false;
|
||||
final bundles = data.bundles ??= [];
|
||||
for (final bundle in bundles) {
|
||||
if (bundle.name == name) {
|
||||
bundle.priority = priority;
|
||||
foundBundle = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!foundBundle) {
|
||||
bundles.add(AccountBundle(name: name, priority: priority));
|
||||
}
|
||||
await setAccountData(userID!, accountBundlesType, data.toJson());
|
||||
}
|
||||
|
||||
Future<void> removeFromAccountBundle(String name) async {
|
||||
if (!accountData.containsKey(accountBundlesType)) {
|
||||
return; // nothing to do
|
||||
}
|
||||
final data = AccountBundles.fromJson(
|
||||
accountData[accountBundlesType]!.content,
|
||||
);
|
||||
if (data.bundles == null) return;
|
||||
data.bundles!.removeWhere((b) => b.name == name);
|
||||
await setAccountData(userID!, accountBundlesType, data.toJson());
|
||||
}
|
||||
|
||||
String get sendPrefix {
|
||||
final data = AccountBundles.fromJson(
|
||||
accountData[accountBundlesType]?.content ?? {},
|
||||
);
|
||||
return data.prefix!;
|
||||
}
|
||||
}
|
||||
68
lib/utils/account_config.dart
Normal file
68
lib/utils/account_config.dart
Normal file
@@ -0,0 +1,68 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
extension ApplicationAccountConfigExtension on Client {
|
||||
static const String accountDataKey = 'im.fluffychat.account_config';
|
||||
|
||||
ApplicationAccountConfig get applicationAccountConfig =>
|
||||
ApplicationAccountConfig.fromJson(
|
||||
accountData[accountDataKey]?.content ?? {},
|
||||
);
|
||||
|
||||
Future<void> setApplicationAccountConfig(ApplicationAccountConfig config) =>
|
||||
setAccountData(userID!, accountDataKey, config.toJson());
|
||||
|
||||
/// Only updates the specified values in ApplicationAccountConfig
|
||||
Future<void> updateApplicationAccountConfig(ApplicationAccountConfig config) {
|
||||
final currentConfig = applicationAccountConfig;
|
||||
return setAccountData(
|
||||
userID!,
|
||||
accountDataKey,
|
||||
ApplicationAccountConfig(
|
||||
wallpaperUrl: config.wallpaperUrl ?? currentConfig.wallpaperUrl,
|
||||
wallpaperOpacity:
|
||||
config.wallpaperOpacity ?? currentConfig.wallpaperOpacity,
|
||||
wallpaperBlur: config.wallpaperBlur ?? currentConfig.wallpaperBlur,
|
||||
).toJson(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ApplicationAccountConfig {
|
||||
final Uri? wallpaperUrl;
|
||||
final double? wallpaperOpacity;
|
||||
final double? wallpaperBlur;
|
||||
|
||||
const ApplicationAccountConfig({
|
||||
this.wallpaperUrl,
|
||||
this.wallpaperOpacity,
|
||||
this.wallpaperBlur,
|
||||
});
|
||||
|
||||
static double _sanitizedOpacity(double? opacity) {
|
||||
if (opacity == null) return 1;
|
||||
if (opacity > 1 || opacity < 0) return 1;
|
||||
return opacity;
|
||||
}
|
||||
|
||||
factory ApplicationAccountConfig.fromJson(Map<String, dynamic> json) =>
|
||||
ApplicationAccountConfig(
|
||||
wallpaperUrl: json['wallpaper_url'] is String
|
||||
? Uri.tryParse(json['wallpaper_url'])
|
||||
: null,
|
||||
wallpaperOpacity: _sanitizedOpacity(
|
||||
json.tryGet<double>('wallpaper_opacity'),
|
||||
),
|
||||
wallpaperBlur: json.tryGet<double>('wallpaper_blur'),
|
||||
);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'wallpaper_url': wallpaperUrl?.toString(),
|
||||
'wallpaper_opacity': wallpaperOpacity,
|
||||
'wallpaper_blur': wallpaperBlur,
|
||||
};
|
||||
}
|
||||
58
lib/utils/adaptive_bottom_sheet.dart
Normal file
58
lib/utils/adaptive_bottom_sheet.dart
Normal file
@@ -0,0 +1,58 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
Future<T?> showAdaptiveBottomSheet<T>({
|
||||
required BuildContext context,
|
||||
required Widget Function(BuildContext) builder,
|
||||
bool isDismissible = true,
|
||||
bool isScrollControlled = true,
|
||||
bool useRootNavigator = true,
|
||||
}) {
|
||||
if (FluffyThemes.isColumnMode(context)) {
|
||||
return showDialog<T>(
|
||||
context: context,
|
||||
useRootNavigator: useRootNavigator,
|
||||
barrierDismissible: isDismissible,
|
||||
useSafeArea: true,
|
||||
builder: (context) => Center(
|
||||
child: Container(
|
||||
margin: const EdgeInsets.all(16),
|
||||
constraints: const BoxConstraints(maxWidth: 480, maxHeight: 720),
|
||||
child: Material(
|
||||
elevation: Theme.of(context).dialogTheme.elevation ?? 4,
|
||||
shadowColor: Theme.of(context).dialogTheme.shadowColor,
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
color: Theme.of(context).scaffoldBackgroundColor,
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: builder(context),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return showModalBottomSheet<T>(
|
||||
context: context,
|
||||
builder: (context) => ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
maxHeight:
|
||||
MediaQuery.viewInsetsOf(context).bottom +
|
||||
min(MediaQuery.sizeOf(context).height - 32, 600),
|
||||
),
|
||||
child: builder(context),
|
||||
),
|
||||
useSafeArea: true,
|
||||
useRootNavigator: useRootNavigator,
|
||||
isDismissible: isDismissible,
|
||||
isScrollControlled: isScrollControlled,
|
||||
clipBehavior: Clip.hardEdge,
|
||||
);
|
||||
}
|
||||
464
lib/utils/background_push.dart
Normal file
464
lib/utils/background_push.dart
Normal file
@@ -0,0 +1,464 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
// Copyright (C) 2020, 2021 Famedly GmbH
|
||||
// Copyright (C) 2021 Fluffychat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:isolate';
|
||||
import 'dart:ui';
|
||||
|
||||
//<GOOGLE_SERVICES>import 'package:fcm_shared_isolate/fcm_shared_isolate.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/main.dart';
|
||||
import 'package:tatchat/utils/notification_background_handler.dart';
|
||||
import 'package:tatchat/utils/push_helper.dart';
|
||||
import 'package:tatchat/widgets/tatu_chat_app.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:unifiedpush/unifiedpush.dart';
|
||||
import 'package:unifiedpush_ui/unifiedpush_ui.dart';
|
||||
|
||||
import '../config/app_config.dart';
|
||||
import '../config/setting_keys.dart';
|
||||
import '../widgets/matrix.dart';
|
||||
import 'platform_infos.dart';
|
||||
|
||||
class BackgroundPush {
|
||||
static BackgroundPush? _instance;
|
||||
final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
|
||||
FlutterLocalNotificationsPlugin();
|
||||
|
||||
List<Client> _clients;
|
||||
|
||||
List<Client> get clients => matrix?.widget.clients ?? _clients;
|
||||
|
||||
MatrixState? matrix;
|
||||
String? _fcmToken;
|
||||
|
||||
String? get fcmToken => _fcmToken;
|
||||
void Function(String errorMsg, {Uri? link})? onFcmError;
|
||||
L10n? l10n;
|
||||
|
||||
Future<void> loadLocale() async {
|
||||
final context = matrix?.context;
|
||||
// inspired by _lookupL10n in .dart_tool/flutter_gen/gen_l10n/l10n.dart
|
||||
l10n ??=
|
||||
(context != null && context.mounted ? L10n.of(context) : null) ??
|
||||
(await L10n.delegate.load(PlatformDispatcher.instance.locale));
|
||||
}
|
||||
|
||||
final pendingTests = <String, Completer<void>>{};
|
||||
bool firebaseEnabled = false;
|
||||
|
||||
//<GOOGLE_SERVICES>final firebase = FcmSharedIsolate();
|
||||
|
||||
DateTime? lastReceivedPush;
|
||||
|
||||
bool upAction = false;
|
||||
|
||||
Future<void> _init() async {
|
||||
//<GOOGLE_SERVICES>firebaseEnabled = true;
|
||||
try {
|
||||
mainIsolateReceivePort?.listen((message) async {
|
||||
try {
|
||||
await notificationTap(
|
||||
NotificationResponseJson.fromJsonString(message),
|
||||
clients: clients,
|
||||
router: TatuChatApp.router,
|
||||
l10n: l10n,
|
||||
);
|
||||
} catch (e, s) {
|
||||
Logs().wtf('Main Notification Tap crashed', e, s);
|
||||
}
|
||||
});
|
||||
if (PlatformInfos.isAndroid) {
|
||||
final port = ReceivePort();
|
||||
IsolateNameServer.removePortNameMapping('background_tab_port');
|
||||
IsolateNameServer.registerPortWithName(
|
||||
port.sendPort,
|
||||
'background_tab_port',
|
||||
);
|
||||
port.listen((message) async {
|
||||
try {
|
||||
await notificationTap(
|
||||
NotificationResponseJson.fromJsonString(message),
|
||||
clients: clients,
|
||||
router: TatuChatApp.router,
|
||||
l10n: l10n,
|
||||
);
|
||||
} catch (e, s) {
|
||||
Logs().wtf('Main Notification Tap crashed', e, s);
|
||||
}
|
||||
});
|
||||
}
|
||||
await _flutterLocalNotificationsPlugin.initialize(
|
||||
settings: const InitializationSettings(
|
||||
android: AndroidInitializationSettings('notifications_icon'),
|
||||
iOS: DarwinInitializationSettings(),
|
||||
),
|
||||
onDidReceiveNotificationResponse: (response) => notificationTap(
|
||||
response,
|
||||
clients: clients,
|
||||
router: TatuChatApp.router,
|
||||
l10n: l10n,
|
||||
),
|
||||
onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
|
||||
);
|
||||
Logs().v('Flutter Local Notifications initialized');
|
||||
//<GOOGLE_SERVICES>firebase.setListeners(
|
||||
//<GOOGLE_SERVICES> onMessage: (message) => pushHelper(
|
||||
//<GOOGLE_SERVICES> PushNotification.fromJson(
|
||||
//<GOOGLE_SERVICES> message.tryGetMap<String, Object>('data') ?? message,
|
||||
//<GOOGLE_SERVICES> ),
|
||||
//<GOOGLE_SERVICES> clients: clients,
|
||||
//<GOOGLE_SERVICES> l10n: l10n,
|
||||
//<GOOGLE_SERVICES> activeRoomId: matrix?.activeRoomId,
|
||||
//<GOOGLE_SERVICES> flutterLocalNotificationsPlugin: _flutterLocalNotificationsPlugin,
|
||||
//<GOOGLE_SERVICES> ),
|
||||
//<GOOGLE_SERVICES>);
|
||||
if (Platform.isAndroid) {
|
||||
await UnifiedPush.initialize(
|
||||
onNewEndpoint: _newUpEndpoint,
|
||||
onRegistrationFailed: (_, i) => _upUnregistered(i),
|
||||
onUnregistered: _upUnregistered,
|
||||
onMessage: _onUpMessage,
|
||||
);
|
||||
}
|
||||
} catch (e, s) {
|
||||
Logs().e('Unable to initialize Flutter local notifications', e, s);
|
||||
}
|
||||
}
|
||||
|
||||
BackgroundPush._(this._clients) {
|
||||
_init();
|
||||
}
|
||||
|
||||
factory BackgroundPush.clientOnly(List<Client> clients) {
|
||||
return _instance ??= BackgroundPush._(clients);
|
||||
}
|
||||
|
||||
factory BackgroundPush(
|
||||
MatrixState matrix, {
|
||||
void Function(String errorMsg, {Uri? link})? onFcmError,
|
||||
}) {
|
||||
final instance = BackgroundPush.clientOnly(matrix.widget.clients);
|
||||
instance.matrix = matrix;
|
||||
// ignore: prefer_initializing_formals
|
||||
instance.onFcmError = onFcmError;
|
||||
return instance;
|
||||
}
|
||||
|
||||
/// Makes sure that there is exactly ONE pusher with these settings for this
|
||||
/// client and deletes all other pushers if not.
|
||||
Future<void> setupPusher({
|
||||
required Client client,
|
||||
String? gatewayUrl,
|
||||
String? token,
|
||||
}) async {
|
||||
if (PlatformInfos.isIOS) {
|
||||
//<GOOGLE_SERVICES>await firebase.requestPermission();
|
||||
}
|
||||
if (PlatformInfos.isAndroid && !isIntegrationTest) {
|
||||
_flutterLocalNotificationsPlugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
AndroidFlutterLocalNotificationsPlugin
|
||||
>()
|
||||
?.requestNotificationsPermission();
|
||||
}
|
||||
final appDisplayName = PlatformInfos.appDisplayName;
|
||||
|
||||
final pushers =
|
||||
await (client.getPushers().catchError((e) {
|
||||
Logs().w('[Push] Unable to request pushers', e);
|
||||
return <Pusher>[];
|
||||
})) ??
|
||||
[];
|
||||
|
||||
// we need the deviceAppId to remove potential legacy pusher
|
||||
var deviceAppId = '${AppConfig.pushNotificationsAppId}.${client.deviceID}';
|
||||
// appId may only be up to 64 chars as per spec
|
||||
if (deviceAppId.length > 64) {
|
||||
deviceAppId = deviceAppId.substring(0, 64);
|
||||
}
|
||||
final thisAppId = deviceAppId;
|
||||
if (gatewayUrl == null || token == null) {
|
||||
Logs().w('[Push] Missing required push credentials');
|
||||
return;
|
||||
}
|
||||
|
||||
if (pushers.any(
|
||||
(currentPusher) =>
|
||||
currentPusher.pushkey == token &&
|
||||
currentPusher.data.additionalProperties['client_name'] ==
|
||||
client.clientName &&
|
||||
currentPusher.kind == 'http' &&
|
||||
currentPusher.appId == thisAppId &&
|
||||
currentPusher.appDisplayName == appDisplayName &&
|
||||
currentPusher.deviceDisplayName == client.deviceName &&
|
||||
currentPusher.lang == 'en' &&
|
||||
currentPusher.data.url.toString() == gatewayUrl &&
|
||||
currentPusher.data.format ==
|
||||
AppSettings.pushNotificationsPusherFormat.value &&
|
||||
currentPusher.data.additionalProperties['data_message'] ==
|
||||
pusherDataMessageFormat,
|
||||
)) {
|
||||
Logs().i('[Push] Pusher already set for ${client.deviceID}');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!client.isLogged()) return;
|
||||
|
||||
final legacyPushers = pushers.where(
|
||||
(pusher) =>
|
||||
pusher.appId == thisAppId || // To migrate older app-id format:
|
||||
((pusher.appId == 'chat.fluffy.fluffychat.data_message' ||
|
||||
pusher.appId == 'chat.fluffy.fluffychat') &&
|
||||
pusher.pushkey == token),
|
||||
);
|
||||
for (final pusher in legacyPushers) {
|
||||
try {
|
||||
await client.deletePusher(pusher);
|
||||
Logs().i('[Push] Removed legacy pusher for ${client.deviceID}');
|
||||
} catch (err) {
|
||||
Logs().w(
|
||||
'[Push] Failed to remove old pusher for ${client.deviceID}',
|
||||
err,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Logs().i('Need to set new pusher for ${client.clientName}');
|
||||
try {
|
||||
await client.postPusher(
|
||||
Pusher(
|
||||
pushkey: token,
|
||||
appId: thisAppId,
|
||||
appDisplayName: appDisplayName,
|
||||
deviceDisplayName: PlatformInfos.appDisplayName,
|
||||
lang: 'en',
|
||||
data: PusherData(
|
||||
url: Uri.parse(gatewayUrl),
|
||||
format: AppSettings.pushNotificationsPusherFormat.value,
|
||||
additionalProperties: {
|
||||
'client_name': client.clientName,
|
||||
'data_message': pusherDataMessageFormat,
|
||||
},
|
||||
),
|
||||
kind: 'http',
|
||||
),
|
||||
append: true,
|
||||
);
|
||||
} catch (e, s) {
|
||||
Logs().e('[Push] Unable to set pushers', e, s);
|
||||
}
|
||||
}
|
||||
|
||||
final pusherDataMessageFormat = Platform.isAndroid;
|
||||
|
||||
static bool _wentToRoomOnStartup = false;
|
||||
|
||||
Future<void> setupPush(BuildContext context) async {
|
||||
if (PlatformInfos.isAndroid &&
|
||||
(await UnifiedPush.getDistributors()).isNotEmpty &&
|
||||
context.mounted) {
|
||||
await UnifiedPushUi(
|
||||
context: context,
|
||||
instances: ['default'],
|
||||
unifiedPushFunctions: UPFunctions(),
|
||||
showNoDistribDialog: false,
|
||||
onNoDistribDialogDismissed: () {}, // TODO: Implement me
|
||||
).registerAppWithDialog();
|
||||
} else {
|
||||
for (final client in clients) {
|
||||
Logs().d('SetupPush for Client ${client.clientName}');
|
||||
if (client.onLoginStateChanged.value != LoginState.loggedIn ||
|
||||
!PlatformInfos.isMobile ||
|
||||
matrix == null) {
|
||||
return;
|
||||
}
|
||||
// Do not setup unifiedpush if this has been initialized by
|
||||
// an unifiedpush action
|
||||
if (upAction) {
|
||||
return;
|
||||
}
|
||||
await setupFirebase(client);
|
||||
}
|
||||
}
|
||||
|
||||
// ignore: unawaited_futures
|
||||
_flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails().then((
|
||||
details,
|
||||
) {
|
||||
if (details == null ||
|
||||
!details.didNotificationLaunchApp ||
|
||||
_wentToRoomOnStartup) {
|
||||
return;
|
||||
}
|
||||
_wentToRoomOnStartup = true;
|
||||
final response = details.notificationResponse;
|
||||
if (response != null) {
|
||||
notificationTap(
|
||||
response,
|
||||
clients: clients,
|
||||
router: TatuChatApp.router,
|
||||
l10n: l10n,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _noFcmWarning() async {
|
||||
if (matrix == null) {
|
||||
return;
|
||||
}
|
||||
if (AppSettings.showNoGoogle.value) {
|
||||
return;
|
||||
}
|
||||
await loadLocale();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (PlatformInfos.isAndroid) {
|
||||
onFcmError?.call(
|
||||
l10n!.noGoogleServicesWarning,
|
||||
link: Uri.parse(AppConfig.enablePushTutorial),
|
||||
);
|
||||
return;
|
||||
}
|
||||
onFcmError?.call(l10n!.oopsPushError);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> setupFirebase(Client client) async {
|
||||
Logs().v('Setup firebase');
|
||||
if (!firebaseEnabled) {
|
||||
await _noFcmWarning();
|
||||
return;
|
||||
}
|
||||
if (_fcmToken?.isEmpty ?? true) {
|
||||
if (PlatformInfos.isIOS) {
|
||||
//<GOOGLE_SERVICES>await firebase.requestPermission();
|
||||
}
|
||||
const max = 5;
|
||||
for (var i = 0; i < max; i++) {
|
||||
try {
|
||||
await Future.delayed(const Duration(seconds: 1));
|
||||
//<GOOGLE_SERVICES>_fcmToken = await firebase.getToken();
|
||||
if (_fcmToken != null) break;
|
||||
} catch (e, s) {
|
||||
Logs().w(
|
||||
'[Push] cannot get token - try ($i/$max)',
|
||||
e,
|
||||
e is String ? null : s,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (_fcmToken == null) {
|
||||
await _noFcmWarning();
|
||||
return;
|
||||
}
|
||||
}
|
||||
await setupPusher(
|
||||
client: client,
|
||||
gatewayUrl: AppSettings.pushNotificationsGatewayUrl.value,
|
||||
token: _fcmToken,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _newUpEndpoint(PushEndpoint newPushEndpoint, String i) async {
|
||||
final newEndpoint = newPushEndpoint.url;
|
||||
upAction = true;
|
||||
if (newEndpoint.isEmpty) {
|
||||
await _upUnregistered(i);
|
||||
return;
|
||||
}
|
||||
var endpoint =
|
||||
'https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify';
|
||||
try {
|
||||
final url = Uri.parse(newEndpoint)
|
||||
.replace(path: '/_matrix/push/v1/notify', query: '')
|
||||
.toString()
|
||||
.split('?')
|
||||
.first;
|
||||
final res = json.decode(
|
||||
utf8.decode((await http.get(Uri.parse(url))).bodyBytes),
|
||||
);
|
||||
if (res['gateway'] == 'matrix' ||
|
||||
(res['unifiedpush'] is Map &&
|
||||
res['unifiedpush']['gateway'] == 'matrix')) {
|
||||
endpoint = url;
|
||||
}
|
||||
} catch (e) {
|
||||
Logs().i(
|
||||
'[Push] No self-hosted unified push gateway present: $newEndpoint',
|
||||
);
|
||||
}
|
||||
Logs().i('[Push] UnifiedPush using endpoint $endpoint');
|
||||
|
||||
for (final client in clients) {
|
||||
await setupPusher(
|
||||
client: client,
|
||||
gatewayUrl: endpoint,
|
||||
token: newEndpoint,
|
||||
);
|
||||
}
|
||||
await AppSettings.unifiedPushEndpoint.setItem(newEndpoint);
|
||||
await AppSettings.unifiedPushRegistered.setItem(true);
|
||||
}
|
||||
|
||||
Future<void> _upUnregistered(String i) async {
|
||||
upAction = true;
|
||||
Logs().i('[Push] Removing UnifiedPush endpoint...');
|
||||
await AppSettings.unifiedPushEndpoint.setItem(
|
||||
AppSettings.unifiedPushEndpoint.defaultValue,
|
||||
);
|
||||
await AppSettings.unifiedPushRegistered.setItem(false);
|
||||
}
|
||||
|
||||
Future<void> _onUpMessage(PushMessage pushMessage, String i) async {
|
||||
final message = pushMessage.content;
|
||||
upAction = true;
|
||||
final data = Map<String, dynamic>.from(
|
||||
json.decode(utf8.decode(message))['notification'],
|
||||
);
|
||||
// UP may strip the devices list
|
||||
data['devices'] ??= [];
|
||||
await pushHelper(
|
||||
PushNotification.fromJson(data),
|
||||
clients: clients,
|
||||
l10n: l10n,
|
||||
activeRoomId: matrix?.activeRoomId,
|
||||
flutterLocalNotificationsPlugin: _flutterLocalNotificationsPlugin,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class UPFunctions extends UnifiedPushFunctions {
|
||||
final List<String> features = [
|
||||
/*list of features*/
|
||||
];
|
||||
|
||||
@override
|
||||
Future<String?> getDistributor() async {
|
||||
return await UnifiedPush.getDistributor();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<String>> getDistributors() async {
|
||||
return await UnifiedPush.getDistributors(features);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> registerApp(String instance) async {
|
||||
await UnifiedPush.register(instance: instance, features: features);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> saveDistributor(String distributor) async {
|
||||
await UnifiedPush.saveDistributor(distributor);
|
||||
}
|
||||
}
|
||||
31
lib/utils/beautify_string_extension.dart
Normal file
31
lib/utils/beautify_string_extension.dart
Normal file
@@ -0,0 +1,31 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
extension BeautifyStringExtension on String {
|
||||
String get beautifiedOneLine {
|
||||
var beautifiedStr = '';
|
||||
for (var i = 0; i < length; i++) {
|
||||
beautifiedStr += substring(i, i + 1);
|
||||
if (i % 4 == 3) {
|
||||
beautifiedStr += ' ';
|
||||
}
|
||||
}
|
||||
return beautifiedStr;
|
||||
}
|
||||
|
||||
String get beautified {
|
||||
var beautifiedStr = '';
|
||||
for (var i = 0; i < length; i++) {
|
||||
beautifiedStr += substring(i, i + 1);
|
||||
if (i % 4 == 3) {
|
||||
beautifiedStr += ' ';
|
||||
}
|
||||
if (i % 16 == 15) {
|
||||
beautifiedStr += '\n';
|
||||
}
|
||||
}
|
||||
return beautifiedStr;
|
||||
}
|
||||
}
|
||||
89
lib/utils/call_kit_params.dart
Normal file
89
lib/utils/call_kit_params.dart
Normal file
@@ -0,0 +1,89 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/matrix_live_kit_call.dart';
|
||||
import 'package:tatchat/utils/notification_avatar_extension.dart';
|
||||
import 'package:flutter_callkit_incoming/entities/entities.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
Future<CallKitParams> buildFluffyChatCallKitParams(
|
||||
Room room, {
|
||||
L10n? l10n,
|
||||
MatrixRtcCallIntent intent = .video,
|
||||
Duration timeout = RtcNotificationContent.defaultLifetime,
|
||||
}) async {
|
||||
l10n ??= await lookupL10n(PlatformDispatcher.instance.locale);
|
||||
final avatarUrl = await room.avatar?.getThumbnailUri(
|
||||
room.client,
|
||||
width: notificationAvatarDimension,
|
||||
height: notificationAvatarDimension,
|
||||
method: ThumbnailMethod.crop,
|
||||
);
|
||||
|
||||
return CallKitParams(
|
||||
id: Uuid().v4(),
|
||||
extra: {
|
||||
'roomId': room.id,
|
||||
'clientName': room.client.clientName,
|
||||
'intent': intent.name,
|
||||
},
|
||||
appName: AppSettings.applicationName.value,
|
||||
nameCaller: room.getLocalizedDisplayname(),
|
||||
avatar: avatarUrl?.toString(),
|
||||
handle: switch (intent) {
|
||||
MatrixRtcCallIntent.voice => l10n.voiceCall,
|
||||
MatrixRtcCallIntent.video => l10n.videoCall,
|
||||
},
|
||||
type: intent.callKitType,
|
||||
duration: timeout.inMilliseconds,
|
||||
headers: avatarUrl == null
|
||||
? null
|
||||
: {'authorization': 'Bearer ${room.client.accessToken}'},
|
||||
missedCallNotification: NotificationParams(
|
||||
showNotification: true,
|
||||
isShowCallback: true,
|
||||
subtitle: l10n.missedCall,
|
||||
callbackText: l10n.callBack,
|
||||
),
|
||||
callingNotification: NotificationParams(
|
||||
showNotification: true,
|
||||
isShowCallback: true,
|
||||
subtitle: l10n.waitingForParticipant,
|
||||
callbackText: l10n.hangUp,
|
||||
),
|
||||
android: AndroidParams(
|
||||
textAccept: l10n.accept,
|
||||
textDecline: l10n.decline,
|
||||
ringtonePath: 'system_ringtone_default',
|
||||
incomingCallNotificationChannelName: l10n.incomingCall,
|
||||
missedCallNotificationChannelName: l10n.missedCall,
|
||||
),
|
||||
ios: IOSParams(
|
||||
iconName: 'LaunchImage',
|
||||
handleType: 'generic',
|
||||
supportsVideo: intent == .video,
|
||||
maximumCallGroups: 1,
|
||||
maximumCallsPerCallGroup: 1,
|
||||
supportsDTMF: false,
|
||||
supportsHolding: false,
|
||||
supportsGrouping: false,
|
||||
supportsUngrouping: false,
|
||||
includesCallsInRecents: true,
|
||||
ringtonePath: 'system_ringtone_default',
|
||||
audioSessionMode: switch (intent) {
|
||||
.video => 'videoChat',
|
||||
.voice => 'voiceChat',
|
||||
},
|
||||
audioSessionActive: true,
|
||||
audioSessionPreferredSampleRate: 44100.0,
|
||||
audioSessionPreferredIOBufferDuration: 0.005,
|
||||
),
|
||||
);
|
||||
}
|
||||
109
lib/utils/client_download_content_extension.dart
Normal file
109
lib/utils/client_download_content_extension.dart
Normal file
@@ -0,0 +1,109 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:math' show min;
|
||||
import 'dart:typed_data';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
extension ClientDownloadContentExtension on Client {
|
||||
Future<Uint8List> downloadMxcCached(
|
||||
Uri mxc, {
|
||||
num? width,
|
||||
num? height,
|
||||
bool isThumbnail = false,
|
||||
bool? animated,
|
||||
ThumbnailMethod? thumbnailMethod,
|
||||
bool rounded = false,
|
||||
}) async {
|
||||
// To stay compatible with previous storeKeys:
|
||||
final cacheKey = isThumbnail
|
||||
// ignore: deprecated_member_use
|
||||
? mxc.getThumbnail(
|
||||
this,
|
||||
width: width,
|
||||
height: height,
|
||||
animated: animated,
|
||||
method: thumbnailMethod,
|
||||
)
|
||||
: mxc;
|
||||
|
||||
final cachedData = await database.getFile(cacheKey);
|
||||
if (cachedData != null) return cachedData;
|
||||
|
||||
final httpUri = isThumbnail
|
||||
? await mxc.getThumbnailUri(
|
||||
this,
|
||||
width: width,
|
||||
height: height,
|
||||
animated: animated,
|
||||
method: thumbnailMethod,
|
||||
)
|
||||
: await mxc.getDownloadUri(this);
|
||||
|
||||
final response = await httpClient.get(
|
||||
httpUri,
|
||||
headers: accessToken == null
|
||||
? null
|
||||
: {'authorization': 'Bearer $accessToken'},
|
||||
);
|
||||
if (response.statusCode != 200) {
|
||||
unexpectedResponse(response, response.bodyBytes);
|
||||
}
|
||||
var imageData = response.bodyBytes;
|
||||
|
||||
if (rounded) {
|
||||
imageData = await _convertToCircularImage(
|
||||
imageData,
|
||||
min(width ?? 64, height ?? 64).round(),
|
||||
);
|
||||
}
|
||||
|
||||
await database.storeFile(cacheKey, imageData, 0);
|
||||
|
||||
return imageData;
|
||||
}
|
||||
}
|
||||
|
||||
Future<Uint8List> _convertToCircularImage(
|
||||
Uint8List imageBytes,
|
||||
int size,
|
||||
) async {
|
||||
final codec = await instantiateImageCodec(imageBytes);
|
||||
final frame = await codec.getNextFrame();
|
||||
final originalImage = frame.image;
|
||||
|
||||
final recorder = PictureRecorder();
|
||||
final canvas = Canvas(recorder);
|
||||
|
||||
final paint = Paint();
|
||||
final rect = Rect.fromLTWH(0, 0, size.toDouble(), size.toDouble());
|
||||
|
||||
final clipPath = Path()
|
||||
..addOval(
|
||||
Rect.fromCircle(center: Offset(size / 2, size / 2), radius: size / 2),
|
||||
);
|
||||
|
||||
canvas.clipPath(clipPath);
|
||||
|
||||
canvas.drawImageRect(
|
||||
originalImage,
|
||||
Rect.fromLTWH(
|
||||
0,
|
||||
0,
|
||||
originalImage.width.toDouble(),
|
||||
originalImage.height.toDouble(),
|
||||
),
|
||||
rect,
|
||||
paint,
|
||||
);
|
||||
|
||||
final picture = recorder.endRecording();
|
||||
final circularImage = await picture.toImage(size, size);
|
||||
|
||||
final byteData = await circularImage.toByteData(format: ImageByteFormat.png);
|
||||
return byteData!.buffer.asUint8List();
|
||||
}
|
||||
188
lib/utils/client_manager.dart
Normal file
188
lib/utils/client_manager.dart
Normal file
@@ -0,0 +1,188 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/custom_http_client.dart';
|
||||
import 'package:tatchat/utils/custom_image_resizer.dart';
|
||||
import 'package:tatchat/utils/init_with_restore.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/matrix_live_kit_call_member.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:flutter_vodozemac/flutter_vodozemac.dart' as vod;
|
||||
import 'package:matrix/encryption/utils/key_verification.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:universal_html/html.dart' as html;
|
||||
|
||||
import 'matrix_sdk_extensions/flutter_matrix_dart_sdk_database/builder.dart';
|
||||
|
||||
abstract class ClientManager {
|
||||
static const String clientNamespace = 'im.fluffychat.store.clients';
|
||||
|
||||
static Future<List<Client>> getClients({
|
||||
bool initialize = true,
|
||||
required SharedPreferences store,
|
||||
}) async {
|
||||
final clientNames = <String>{};
|
||||
try {
|
||||
final clientNamesList = store.getStringList(clientNamespace) ?? [];
|
||||
clientNames.addAll(clientNamesList);
|
||||
} catch (e, s) {
|
||||
Logs().w('Client names in store are corrupted', e, s);
|
||||
await store.remove(clientNamespace);
|
||||
}
|
||||
if (clientNames.isEmpty) {
|
||||
clientNames.add(PlatformInfos.appDisplayName);
|
||||
await store.setStringList(clientNamespace, clientNames.toList());
|
||||
}
|
||||
final clients = await Future.wait(
|
||||
clientNames.map((name) => createClient(name, store)),
|
||||
);
|
||||
if (initialize) {
|
||||
await Future.wait(
|
||||
clients.map(
|
||||
(client) => client
|
||||
.initWithRestore(
|
||||
onMigration: () async {
|
||||
final l10n = await lookupL10n(
|
||||
PlatformDispatcher.instance.locale,
|
||||
);
|
||||
sendInitNotification(
|
||||
l10n.databaseMigrationTitle,
|
||||
l10n.databaseMigrationBody,
|
||||
);
|
||||
},
|
||||
)
|
||||
.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...',
|
||||
);
|
||||
clientNames.remove(client.clientName);
|
||||
clients.remove(client);
|
||||
}
|
||||
await store.setStringList(clientNamespace, clientNames.toList());
|
||||
}
|
||||
return clients;
|
||||
}
|
||||
|
||||
static Future<void> addClientNameToStore(
|
||||
String clientName,
|
||||
SharedPreferences store,
|
||||
) async {
|
||||
final clientNamesList = store.getStringList(clientNamespace) ?? [];
|
||||
clientNamesList.add(clientName);
|
||||
await store.setStringList(clientNamespace, clientNamesList);
|
||||
}
|
||||
|
||||
static Future<void> removeClientNameFromStore(
|
||||
String clientName,
|
||||
SharedPreferences store,
|
||||
) async {
|
||||
final clientNamesList = store.getStringList(clientNamespace) ?? [];
|
||||
clientNamesList.remove(clientName);
|
||||
await store.setStringList(clientNamespace, clientNamesList);
|
||||
}
|
||||
|
||||
static NativeImplementations get nativeImplementations => kIsWeb
|
||||
? NativeImplementationsWebWorker(
|
||||
Uri.parse('native_executor.js'),
|
||||
timeout: const Duration(minutes: 1),
|
||||
)
|
||||
: NativeImplementationsIsolate(
|
||||
compute,
|
||||
vodozemacInit: () => vod.init(
|
||||
wasmPath:
|
||||
'./assets/assets/vodozemac/${AppConfig.vodozemacVersion}/',
|
||||
),
|
||||
);
|
||||
|
||||
static Future<Client> createClient(
|
||||
String clientName,
|
||||
SharedPreferences store,
|
||||
) async {
|
||||
final shareKeysWith = AppSettings.shareKeysWith.value;
|
||||
final enableSoftLogout = AppSettings.enableSoftLogout.value;
|
||||
|
||||
return Client(
|
||||
clientName,
|
||||
httpClient: CustomHttpClient.createHTTPClient(),
|
||||
verificationMethods: {
|
||||
KeyVerificationMethod.numbers,
|
||||
if (kIsWeb || PlatformInfos.isMobile || PlatformInfos.isLinux)
|
||||
KeyVerificationMethod.emoji,
|
||||
},
|
||||
importantStateEvents: <String>{
|
||||
// To make room emotes work
|
||||
'im.ponies.room_emotes',
|
||||
// To display call state in chat list
|
||||
MatrixRtcCallMember.eventType,
|
||||
},
|
||||
customImageResizer: PlatformInfos.supportsCustomImageResizer
|
||||
? customImageResizer
|
||||
: null,
|
||||
logLevel: Level.verbose,
|
||||
database: await flutterMatrixSdkDatabaseBuilder(clientName),
|
||||
supportedLoginTypes: {
|
||||
AuthenticationTypes.password,
|
||||
AuthenticationTypes.sso,
|
||||
},
|
||||
nativeImplementations: nativeImplementations,
|
||||
defaultNetworkRequestTimeout: const Duration(minutes: 30),
|
||||
enableDehydratedDevices: true,
|
||||
shareKeysWith:
|
||||
ShareKeysWith.values.singleWhereOrNull(
|
||||
(share) => share.name == shareKeysWith,
|
||||
) ??
|
||||
ShareKeysWith.all,
|
||||
onSoftLogout: enableSoftLogout ? (c) => c.refreshAccessToken() : null,
|
||||
sendTimelineEventTimeout: Duration(
|
||||
seconds: AppSettings.sendTimelineEventTimeout.value,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
static Future<void> sendInitNotification(String title, String body) async {
|
||||
if (kIsWeb) {
|
||||
html.Notification(title, body: body);
|
||||
return;
|
||||
}
|
||||
|
||||
final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
|
||||
|
||||
await flutterLocalNotificationsPlugin.initialize(
|
||||
settings: const InitializationSettings(
|
||||
android: AndroidInitializationSettings('notifications_icon'),
|
||||
iOS: DarwinInitializationSettings(),
|
||||
),
|
||||
);
|
||||
|
||||
await flutterLocalNotificationsPlugin.show(
|
||||
id: 0,
|
||||
title: title,
|
||||
body: body,
|
||||
notificationDetails: const NotificationDetails(
|
||||
android: AndroidNotificationDetails(
|
||||
'error_message',
|
||||
'Error Messages',
|
||||
importance: Importance.high,
|
||||
priority: Priority.max,
|
||||
),
|
||||
iOS: DarwinNotificationDetails(sound: 'notification.caf'),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
45
lib/utils/code_highlight_theme.dart
Normal file
45
lib/utils/code_highlight_theme.dart
Normal file
@@ -0,0 +1,45 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
const hightlightTextColor = Color(0xffabb2bf);
|
||||
const atomOneBackgroundColor = Color(0xff282c34);
|
||||
const atomOneDarkTheme = {
|
||||
'root': TextStyle(color: hightlightTextColor),
|
||||
'comment': TextStyle(color: Color(0xff5c6370), fontStyle: FontStyle.italic),
|
||||
'quote': TextStyle(color: Color(0xff5c6370), fontStyle: FontStyle.italic),
|
||||
'doctag': TextStyle(color: Color(0xffc678dd)),
|
||||
'keyword': TextStyle(color: Color(0xffc678dd)),
|
||||
'formula': TextStyle(color: Color(0xffc678dd)),
|
||||
'section': TextStyle(color: Color(0xffe06c75)),
|
||||
'name': TextStyle(color: Color(0xffe06c75)),
|
||||
'selector-tag': TextStyle(color: Color(0xffe06c75)),
|
||||
'deletion': TextStyle(color: Color(0xffe06c75)),
|
||||
'subst': TextStyle(color: Color(0xffe06c75)),
|
||||
'literal': TextStyle(color: Color(0xff56b6c2)),
|
||||
'string': TextStyle(color: Color(0xff98c379)),
|
||||
'regexp': TextStyle(color: Color(0xff98c379)),
|
||||
'addition': TextStyle(color: Color(0xff98c379)),
|
||||
'attribute': TextStyle(color: Color(0xff98c379)),
|
||||
'meta-string': TextStyle(color: Color(0xff98c379)),
|
||||
'built_in': TextStyle(color: Color(0xffe6c07b)),
|
||||
'attr': TextStyle(color: Color(0xffd19a66)),
|
||||
'variable': TextStyle(color: Color(0xffd19a66)),
|
||||
'template-variable': TextStyle(color: Color(0xffd19a66)),
|
||||
'type': TextStyle(color: Color(0xffd19a66)),
|
||||
'selector-class': TextStyle(color: Color(0xffd19a66)),
|
||||
'selector-attr': TextStyle(color: Color(0xffd19a66)),
|
||||
'selector-pseudo': TextStyle(color: Color(0xffd19a66)),
|
||||
'number': TextStyle(color: Color(0xffd19a66)),
|
||||
'symbol': TextStyle(color: Color(0xff61aeee)),
|
||||
'bullet': TextStyle(color: Color(0xff61aeee)),
|
||||
'link': TextStyle(color: Color(0xff61aeee)),
|
||||
'meta': TextStyle(color: Color(0xff61aeee)),
|
||||
'selector-id': TextStyle(color: Color(0xff61aeee)),
|
||||
'title': TextStyle(color: Color(0xff61aeee)),
|
||||
'emphasis': TextStyle(fontStyle: FontStyle.italic),
|
||||
'strong': TextStyle(fontWeight: FontWeight.bold),
|
||||
};
|
||||
19
lib/utils/color_value.dart
Normal file
19
lib/utils/color_value.dart
Normal file
@@ -0,0 +1,19 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
extension ColorValue on Color {
|
||||
int get hexValue {
|
||||
return _floatToInt8(a) << 24 |
|
||||
_floatToInt8(r) << 16 |
|
||||
_floatToInt8(g) << 8 |
|
||||
_floatToInt8(b) << 0;
|
||||
}
|
||||
|
||||
static int _floatToInt8(double x) {
|
||||
return (x * 255.0).round() & 0xff;
|
||||
}
|
||||
}
|
||||
41
lib/utils/custom_http_client.dart
Normal file
41
lib/utils/custom_http_client.dart
Normal file
@@ -0,0 +1,41 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:tatchat/config/isrg_x1.dart';
|
||||
import 'package:tatchat/config/isrg_x2.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/io_client.dart';
|
||||
import 'package:http/retry.dart' as retry;
|
||||
|
||||
/// Custom HTTP client that adds the ISRG Root certificates used by Let's
|
||||
/// Encrypt. Older Android versions may not include these roots in their
|
||||
/// trust store, so we ship them ourselves to ensure TLS connections to
|
||||
/// Let's Encrypt–signed servers continue to work.
|
||||
class CustomHttpClient {
|
||||
static HttpClient customHttpClient() {
|
||||
final context = SecurityContext.defaultContext;
|
||||
|
||||
try {
|
||||
context.setTrustedCertificatesBytes(utf8.encode(ISRG_X1));
|
||||
context.setTrustedCertificatesBytes(utf8.encode(ISRG_X2));
|
||||
} on TlsException catch (e) {
|
||||
if (e.osError != null &&
|
||||
e.osError!.message.contains('CERT_ALREADY_IN_HASH_TABLE')) {
|
||||
} else {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
return HttpClient(context: context);
|
||||
}
|
||||
|
||||
static http.Client createHTTPClient() => retry.RetryClient(
|
||||
PlatformInfos.isAndroid ? IOClient(customHttpClient()) : http.Client(),
|
||||
);
|
||||
}
|
||||
109
lib/utils/custom_image_resizer.dart
Normal file
109
lib/utils/custom_image_resizer.dart
Normal file
@@ -0,0 +1,109 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/painting.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:native_imaging/native_imaging.dart' as native;
|
||||
|
||||
(int, int) _scaleToBox(int width, int height, {required int boxSize}) {
|
||||
final fit = applyBoxFit(
|
||||
BoxFit.scaleDown,
|
||||
Size(width.toDouble(), height.toDouble()),
|
||||
Size(boxSize.toDouble(), boxSize.toDouble()),
|
||||
).destination;
|
||||
return (fit.width.round(), fit.height.round());
|
||||
}
|
||||
|
||||
Future<MatrixImageFileResizedResponse?> customImageResizer(
|
||||
MatrixImageFileResizeArguments arguments,
|
||||
) async {
|
||||
await native.init();
|
||||
|
||||
var imageBytes = arguments.bytes;
|
||||
String? blurhash;
|
||||
|
||||
var originalWidth = 0;
|
||||
var originalHeight = 0;
|
||||
var width = 0;
|
||||
var height = 0;
|
||||
String? mimeType;
|
||||
|
||||
try {
|
||||
// for the other platforms
|
||||
final dartCodec = await instantiateImageCodec(arguments.bytes);
|
||||
final frameCount = dartCodec.frameCount;
|
||||
final dartFrame = await dartCodec.getNextFrame();
|
||||
final rgbaData = await dartFrame.image.toByteData();
|
||||
if (rgbaData == null) {
|
||||
return null;
|
||||
}
|
||||
final rgba = Uint8List.view(
|
||||
rgbaData.buffer,
|
||||
rgbaData.offsetInBytes,
|
||||
rgbaData.lengthInBytes,
|
||||
);
|
||||
|
||||
width = originalWidth = dartFrame.image.width;
|
||||
height = originalHeight = dartFrame.image.height;
|
||||
|
||||
var nativeImg = native.Image.fromRGBA(width, height, rgba);
|
||||
|
||||
dartFrame.image.dispose();
|
||||
dartCodec.dispose();
|
||||
|
||||
if (arguments.calcBlurhash) {
|
||||
// scale down image for blurhashing to speed it up
|
||||
final (blurW, blurH) = _scaleToBox(width, height, boxSize: 100);
|
||||
final blurhashImg = nativeImg.resample(
|
||||
blurW,
|
||||
blurH,
|
||||
// nearest is unsupported...
|
||||
native.Transform.bilinear,
|
||||
);
|
||||
|
||||
blurhash = blurhashImg.toBlurhash(3, 3);
|
||||
|
||||
blurhashImg.free();
|
||||
}
|
||||
|
||||
if (frameCount > 1) {
|
||||
// Don't scale down animated images, since those would lose frames.
|
||||
nativeImg.free();
|
||||
} else {
|
||||
final max = arguments.maxDimension;
|
||||
if (width > max || height > max) {
|
||||
(width, height) = _scaleToBox(width, height, boxSize: max);
|
||||
|
||||
final scaledImg = nativeImg.resample(
|
||||
width,
|
||||
height,
|
||||
native.Transform.lanczos,
|
||||
);
|
||||
nativeImg.free();
|
||||
nativeImg = scaledImg;
|
||||
}
|
||||
|
||||
imageBytes = await nativeImg.toJpeg(75);
|
||||
mimeType = 'image/jpeg';
|
||||
nativeImg.free();
|
||||
}
|
||||
} catch (e, s) {
|
||||
Logs().e('Could not generate preview', e, s);
|
||||
mimeType = null;
|
||||
}
|
||||
|
||||
return MatrixImageFileResizedResponse(
|
||||
bytes: imageBytes,
|
||||
width: width,
|
||||
height: height,
|
||||
originalWidth: originalWidth,
|
||||
originalHeight: originalHeight,
|
||||
blurhash: blurhash,
|
||||
mimeType: mimeType,
|
||||
);
|
||||
}
|
||||
15
lib/utils/custom_scroll_behaviour.dart
Normal file
15
lib/utils/custom_scroll_behaviour.dart
Normal file
@@ -0,0 +1,15 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
class CustomScrollBehavior extends MaterialScrollBehavior {
|
||||
@override
|
||||
Set<PointerDeviceKind> get dragDevices => {
|
||||
PointerDeviceKind.touch,
|
||||
PointerDeviceKind.trackpad,
|
||||
};
|
||||
}
|
||||
191
lib/utils/date_time_extension.dart
Normal file
191
lib/utils/date_time_extension.dart
Normal file
@@ -0,0 +1,191 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
/// Provides extra functionality for formatting the time.
|
||||
extension DateTimeExtension on DateTime {
|
||||
bool operator <(DateTime other) {
|
||||
return millisecondsSinceEpoch < other.millisecondsSinceEpoch;
|
||||
}
|
||||
|
||||
bool operator >(DateTime other) {
|
||||
return millisecondsSinceEpoch > other.millisecondsSinceEpoch;
|
||||
}
|
||||
|
||||
bool operator >=(DateTime other) {
|
||||
return millisecondsSinceEpoch >= other.millisecondsSinceEpoch;
|
||||
}
|
||||
|
||||
bool operator <=(DateTime other) {
|
||||
return millisecondsSinceEpoch <= other.millisecondsSinceEpoch;
|
||||
}
|
||||
|
||||
/// Checks if two DateTimes are close enough to belong to the same
|
||||
/// environment.
|
||||
bool sameEnvironment(DateTime prevTime) =>
|
||||
difference(prevTime).abs() < const Duration(minutes: 5) &&
|
||||
sameDay(prevTime);
|
||||
|
||||
bool sameDay(DateTime prevTime) =>
|
||||
prevTime.year == year && prevTime.month == month && prevTime.day == day;
|
||||
|
||||
/// Returns a simple time String.
|
||||
String localizedTimeOfDay(BuildContext context) => use24HourFormat(context)
|
||||
? DateFormat(
|
||||
'HH:mm',
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(this)
|
||||
: DateFormat(
|
||||
'h:mm a',
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(this);
|
||||
|
||||
/// Returns [localizedTimeOfDay()] if the ChatTime is today, the name of the week
|
||||
/// day if the ChatTime is this week and a date string else.
|
||||
String localizedTimeShort(BuildContext context) {
|
||||
final now = DateTime.now();
|
||||
|
||||
final sameYear = now.year == year;
|
||||
|
||||
final sameDay = sameYear && now.month == month && now.day == day;
|
||||
|
||||
final sameWeek =
|
||||
sameYear &&
|
||||
!sameDay &&
|
||||
now.millisecondsSinceEpoch - millisecondsSinceEpoch <
|
||||
1000 * 60 * 60 * 24 * 7;
|
||||
|
||||
if (sameDay) {
|
||||
return localizedTimeOfDay(context);
|
||||
} else if (sameWeek) {
|
||||
return DateFormat.E(
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(this);
|
||||
} else if (sameYear) {
|
||||
return DateFormat.MMMd(
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(this);
|
||||
}
|
||||
return DateFormat.yMMMd(
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(this);
|
||||
}
|
||||
|
||||
DateTime get dateOnly => DateTime(year, month, day);
|
||||
|
||||
String localizedDate(BuildContext context) {
|
||||
final date = dateOnly;
|
||||
final now = DateTime.now().dateOnly;
|
||||
|
||||
final sameYear = now.year == date.year;
|
||||
|
||||
final sameDay = now == date;
|
||||
|
||||
final sameWeek =
|
||||
sameYear &&
|
||||
!sameDay &&
|
||||
now.millisecondsSinceEpoch - millisecondsSinceEpoch <
|
||||
1000 * 60 * 60 * 24 * 7;
|
||||
|
||||
if (sameDay) {
|
||||
return L10n.of(context).today;
|
||||
} else if (now.difference(date).inDays == 1) {
|
||||
return L10n.of(context).yesterday;
|
||||
} else if (sameWeek) {
|
||||
return DateFormat.EEEE(
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(date);
|
||||
} else if (sameYear) {
|
||||
return DateFormat.MMMMd(
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(date);
|
||||
}
|
||||
return DateFormat.yMMMMd(
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(date);
|
||||
}
|
||||
|
||||
/// If the DateTime is today, this returns [localizedTimeOfDay()], if not it also
|
||||
/// shows the date.
|
||||
/// TODO: Add localization
|
||||
String localizedTime(BuildContext context) {
|
||||
final now = DateTime.now();
|
||||
|
||||
final sameYear = now.year == year;
|
||||
|
||||
final sameDay = sameYear && now.month == month && now.day == day;
|
||||
|
||||
if (sameDay) return localizedTimeOfDay(context);
|
||||
return L10n.of(context).dateAndTimeOfDay(
|
||||
localizedTimeShort(context),
|
||||
localizedTimeOfDay(context),
|
||||
);
|
||||
}
|
||||
|
||||
String localizedDetailedTime(BuildContext context) =>
|
||||
L10n.of(context).dateAndTimeOfDay(
|
||||
DateFormat.yMMMd(
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(this),
|
||||
use24HourFormat(context)
|
||||
? DateFormat(
|
||||
'HH:mm:ss',
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(this)
|
||||
: DateFormat(
|
||||
'h:mm:ss a',
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(this),
|
||||
);
|
||||
|
||||
/// Check if time needs to be in 24h format
|
||||
bool use24HourFormat(BuildContext context) {
|
||||
final mediaQuery24h = MediaQuery.alwaysUse24HourFormatOf(context);
|
||||
|
||||
// For Android this should always work.
|
||||
if (PlatformInfos.isAndroid) return mediaQuery24h;
|
||||
|
||||
final locale = Localizations.localeOf(context).languageCode;
|
||||
// Note: I don't like maintaining my own list but I haven't found a way to
|
||||
// check this completely in Flutter side, as `alwaysUse24HourFormatOf()`
|
||||
// doesn't seem to work on web or desktop.
|
||||
const languages24Hour = {
|
||||
'de',
|
||||
'fr',
|
||||
'es',
|
||||
'it',
|
||||
'nl',
|
||||
'pt',
|
||||
'ru',
|
||||
'zh',
|
||||
'ja',
|
||||
'ko',
|
||||
'ar',
|
||||
'pl',
|
||||
'cs',
|
||||
'hu',
|
||||
'sv',
|
||||
'no',
|
||||
'da',
|
||||
'fi',
|
||||
'el',
|
||||
'he',
|
||||
'tr',
|
||||
'lt',
|
||||
};
|
||||
final l10n24h = languages24Hour.contains(locale);
|
||||
|
||||
// https://github.com/krille-chan/fluffychat/pull/1457#discussion_r1836817914
|
||||
if (PlatformInfos.isIOS) {
|
||||
return mediaQuery24h || l10n24h;
|
||||
}
|
||||
|
||||
return l10n24h;
|
||||
}
|
||||
}
|
||||
164
lib/utils/error_reporter.dart
Normal file
164
lib/utils/error_reporter.dart
Normal file
@@ -0,0 +1,164 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/adaptive_dialog_action.dart';
|
||||
import 'package:tatchat/widgets/tatu_chat_app.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:universal_html/universal_html.dart' as html;
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
class ErrorReporter {
|
||||
final BuildContext? context;
|
||||
final String? message;
|
||||
|
||||
const ErrorReporter(this.context, [this.message]);
|
||||
|
||||
static const Set<String> ingoredTypes = {
|
||||
'IOException',
|
||||
'ClientException',
|
||||
'SocketException',
|
||||
'TlsException',
|
||||
'HandshakeException',
|
||||
};
|
||||
|
||||
static void onFlutterError(Object error, [StackTrace? stackTrace]) {
|
||||
if (AppSettings.autoSendErrorReports.value != true) {
|
||||
debugPrint('Exception caught but auto send crash reports is disabled.');
|
||||
debugPrint(error.toString());
|
||||
debugPrintStack(stackTrace: stackTrace);
|
||||
return;
|
||||
}
|
||||
final hash = (stackTrace ?? error).hashCode.toString();
|
||||
if (AppSettings.knownErrorHashes.value.contains(hash)) return;
|
||||
AppSettings.knownErrorHashes.setItem([
|
||||
...AppSettings.knownErrorHashes.value,
|
||||
hash,
|
||||
]);
|
||||
ErrorReporter(null, 'Flutter error').onErrorCallback(error, stackTrace);
|
||||
}
|
||||
|
||||
Future<void> onErrorCallback(Object error, [StackTrace? stackTrace]) async {
|
||||
if (ingoredTypes.contains(error.runtimeType.toString())) return;
|
||||
Logs().e(message ?? 'Error caught', error, stackTrace);
|
||||
WidgetsBinding.instance.addPostFrameCallback(
|
||||
(_) => _onErrorCallback(error, stackTrace),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _onErrorCallback(Object error, [StackTrace? stackTrace]) async {
|
||||
final context =
|
||||
this.context ??
|
||||
TatuChatApp.router.routerDelegate.navigatorKey.currentContext;
|
||||
final text = '$error\n${stackTrace ?? ''}';
|
||||
|
||||
if (context == null || !context.mounted) {
|
||||
debugPrint(
|
||||
'Exception caught but we have no mounted BuildContext to display a dialog to the user!\n$text',
|
||||
);
|
||||
return;
|
||||
}
|
||||
showAdaptiveDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog.adaptive(
|
||||
title: Text(L10n.of(context).reportErrorDescription),
|
||||
content: SizedBox(
|
||||
height: 256,
|
||||
width: 256,
|
||||
child: SingleChildScrollView(
|
||||
child: Text(
|
||||
text,
|
||||
style: const TextStyle(fontSize: 14, fontFamily: 'RobotoMono'),
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
AdaptiveDialogAction(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(L10n.of(context).close),
|
||||
),
|
||||
AdaptiveDialogAction(
|
||||
onPressed: () => Clipboard.setData(ClipboardData(text: text)),
|
||||
child: Text(L10n.of(context).copy),
|
||||
),
|
||||
AdaptiveDialogAction(
|
||||
onPressed: () async {
|
||||
final existingIssueUrl = stackTrace == null
|
||||
? null
|
||||
: await _searchIssue(
|
||||
(error.toString() + stackTrace.toString()).hashCode
|
||||
.toString(),
|
||||
);
|
||||
if (existingIssueUrl != null) {
|
||||
launchUrl(existingIssueUrl);
|
||||
return;
|
||||
}
|
||||
launchUrl(
|
||||
AppConfig.newIssueUrl.resolveUri(
|
||||
Uri(
|
||||
queryParameters: {
|
||||
'template': 'bug_report.yml',
|
||||
'title':
|
||||
'[Error ${stackTrace.hashCode}] ${message ?? error}',
|
||||
'bug-description': error.toString(),
|
||||
'stacktrace': stackTrace?.toString(),
|
||||
'app-version': await PlatformInfos.getVersion(),
|
||||
'platform-info': kIsWeb
|
||||
? html.window.navigator.userAgent
|
||||
: switch (defaultTargetPlatform) {
|
||||
TargetPlatform.android => 'Android',
|
||||
TargetPlatform.fuchsia => 'Other',
|
||||
TargetPlatform.iOS => 'iOS',
|
||||
TargetPlatform.linux => 'Linux',
|
||||
TargetPlatform.macOS => 'macOS (Self-compiled)',
|
||||
TargetPlatform.windows =>
|
||||
'Windows (Self-compiled)',
|
||||
},
|
||||
},
|
||||
),
|
||||
),
|
||||
mode: LaunchMode.externalApplication,
|
||||
);
|
||||
},
|
||||
child: Text(L10n.of(context).report),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<Uri?> _searchIssue(String hash) async {
|
||||
final result = await http.get(
|
||||
Uri(
|
||||
scheme: 'https',
|
||||
host: 'api.github.com',
|
||||
path: '/search/issues',
|
||||
query: 'q=repo:krille-chan/fluffychat+is:issue+$hash',
|
||||
),
|
||||
);
|
||||
try {
|
||||
final jsonResult =
|
||||
jsonDecode(utf8.decode(result.bodyBytes)) as Map<String, Object?>;
|
||||
final uriString = jsonResult
|
||||
.tryGetList<Map<String, Object?>>('items')
|
||||
?.firstOrNull
|
||||
?.tryGet<String>('html_url');
|
||||
if (uriString == null) return null;
|
||||
return Uri.tryParse(uriString);
|
||||
} catch (e, s) {
|
||||
Logs().w('Unable to search for existing issues on GitHub', e, s);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
31
lib/utils/event_checkbox_extension.dart
Normal file
31
lib/utils/event_checkbox_extension.dart
Normal file
@@ -0,0 +1,31 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
extension EventCheckboxRoomExtension on Room {
|
||||
static const String relationshipType = 'im.fluffychat.checkboxes';
|
||||
Future<String?> checkCheckbox(
|
||||
String eventId,
|
||||
int checkboxId, {
|
||||
String? txid,
|
||||
}) => sendEvent(
|
||||
{
|
||||
'm.relates_to': {
|
||||
'rel_type': relationshipType,
|
||||
'event_id': eventId,
|
||||
'checkbox_id': checkboxId,
|
||||
},
|
||||
},
|
||||
type: EventTypes.Reaction,
|
||||
txid: txid,
|
||||
);
|
||||
}
|
||||
|
||||
extension EventCheckboxExtension on Event {
|
||||
int? get checkedCheckboxId => content
|
||||
.tryGetMap<String, Object?>('m.relates_to')
|
||||
?.tryGet<int>('checkbox_id');
|
||||
}
|
||||
29
lib/utils/file_description.dart
Normal file
29
lib/utils/file_description.dart
Normal file
@@ -0,0 +1,29 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
extension FileDescriptionExtension on Event {
|
||||
String? get fileDescription {
|
||||
if (!{
|
||||
MessageTypes.File,
|
||||
MessageTypes.Image,
|
||||
MessageTypes.Sticker,
|
||||
MessageTypes.Video,
|
||||
MessageTypes.Audio,
|
||||
}.contains(messageType)) {
|
||||
return null;
|
||||
}
|
||||
final filename = content.tryGet<String>('filename');
|
||||
final body = calcUnlocalizedBody(hideReply: true, plaintextBody: true);
|
||||
|
||||
if (filename != body &&
|
||||
filename != null &&
|
||||
content.tryGet<String>('body')?.isNotEmpty == true) {
|
||||
return body;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
38
lib/utils/file_selector.dart
Normal file
38
lib/utils/file_selector.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:file_selector/file_selector.dart';
|
||||
import 'package:tatchat/widgets/app_lock.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
Future<List<XFile>> selectFiles(
|
||||
BuildContext context, {
|
||||
String? title,
|
||||
FileType type = FileType.any,
|
||||
bool allowMultiple = false,
|
||||
}) async {
|
||||
final result = await AppLock.of(context).pauseWhile(
|
||||
showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () async {
|
||||
if (allowMultiple) {
|
||||
final result = await FilePicker.pickFiles(
|
||||
type: type,
|
||||
dialogTitle: title,
|
||||
);
|
||||
return result.map((file) => file.xFile).toList();
|
||||
}
|
||||
final result = await FilePicker.pickFile(
|
||||
type: type,
|
||||
dialogTitle: title,
|
||||
);
|
||||
return [?result?.xFile];
|
||||
},
|
||||
),
|
||||
);
|
||||
return result.result ?? [];
|
||||
}
|
||||
154
lib/utils/init_with_restore.dart
Normal file
154
lib/utils/init_with_restore.dart
Normal file
@@ -0,0 +1,154 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/client_manager.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class SessionBackup {
|
||||
final String? olmAccount;
|
||||
final String accessToken;
|
||||
final String userId;
|
||||
final String homeserver;
|
||||
final String? deviceId;
|
||||
final String? deviceName;
|
||||
|
||||
const SessionBackup({
|
||||
required this.olmAccount,
|
||||
required this.accessToken,
|
||||
required this.userId,
|
||||
required this.homeserver,
|
||||
required this.deviceId,
|
||||
this.deviceName,
|
||||
});
|
||||
|
||||
factory SessionBackup.fromJsonString(String json) =>
|
||||
SessionBackup.fromJson(jsonDecode(json));
|
||||
|
||||
factory SessionBackup.fromJson(Map<String, dynamic> json) => SessionBackup(
|
||||
olmAccount: json['olm_account'],
|
||||
accessToken: json['access_token'],
|
||||
userId: json['user_id'],
|
||||
homeserver: json['homeserver'],
|
||||
deviceId: json['device_id'],
|
||||
deviceName: json['device_name'],
|
||||
);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'olm_account': olmAccount,
|
||||
'access_token': accessToken,
|
||||
'user_id': userId,
|
||||
'homeserver': homeserver,
|
||||
'device_id': deviceId,
|
||||
if (deviceName != null) 'device_name': deviceName,
|
||||
};
|
||||
|
||||
@override
|
||||
String toString() => jsonEncode(toJson());
|
||||
}
|
||||
|
||||
extension InitWithRestoreExtension on Client {
|
||||
static Future<void> deleteSessionBackup(String clientName) async {
|
||||
final storage = PlatformInfos.isMobile || PlatformInfos.isLinux
|
||||
? const FlutterSecureStorage()
|
||||
: null;
|
||||
await storage?.delete(
|
||||
key: '${AppSettings.applicationName.value}_session_backup_$clientName',
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> initWithRestore({void Function()? onMigration}) async {
|
||||
final storageKey =
|
||||
'${AppSettings.applicationName.value}_session_backup_$clientName';
|
||||
final storage = PlatformInfos.isMobile || PlatformInfos.isLinux
|
||||
? const FlutterSecureStorage()
|
||||
: null;
|
||||
|
||||
try {
|
||||
await init(
|
||||
onInitStateChanged: (state) {
|
||||
if (state == InitState.migratingDatabase) onMigration?.call();
|
||||
},
|
||||
waitForFirstSync: false,
|
||||
waitUntilLoadCompletedLoaded: false,
|
||||
);
|
||||
if (isLogged()) {
|
||||
final accessToken = this.accessToken;
|
||||
final homeserver = this.homeserver?.toString();
|
||||
final deviceId = deviceID;
|
||||
final userId = userID;
|
||||
final hasBackup =
|
||||
accessToken != null &&
|
||||
homeserver != null &&
|
||||
deviceId != null &&
|
||||
userId != null;
|
||||
assert(hasBackup);
|
||||
if (hasBackup) {
|
||||
Logs().v('Store session in backup');
|
||||
storage?.write(
|
||||
key: storageKey,
|
||||
value: SessionBackup(
|
||||
olmAccount: encryption?.pickledOlmAccount,
|
||||
accessToken: accessToken,
|
||||
deviceId: deviceId,
|
||||
homeserver: homeserver,
|
||||
deviceName: deviceName,
|
||||
userId: userId,
|
||||
).toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e, s) {
|
||||
Logs().wtf('Client init failed!', e, s);
|
||||
final l10n = await lookupL10n(PlatformDispatcher.instance.locale);
|
||||
final sessionBackupString = await storage?.read(key: storageKey);
|
||||
if (sessionBackupString == null) {
|
||||
ClientManager.sendInitNotification(
|
||||
l10n.initAppError,
|
||||
l10n.sessionLostBody(AppConfig.newIssueUrl.toString(), e.toString()),
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
|
||||
try {
|
||||
final sessionBackup = SessionBackup.fromJsonString(sessionBackupString);
|
||||
await init(
|
||||
newToken: sessionBackup.accessToken,
|
||||
newOlmAccount: sessionBackup.olmAccount,
|
||||
newDeviceID: sessionBackup.deviceId,
|
||||
newDeviceName: sessionBackup.deviceName,
|
||||
newHomeserver: Uri.tryParse(sessionBackup.homeserver),
|
||||
newUserID: sessionBackup.userId,
|
||||
waitForFirstSync: false,
|
||||
waitUntilLoadCompletedLoaded: false,
|
||||
onInitStateChanged: (state) {
|
||||
if (state == InitState.migratingDatabase) onMigration?.call();
|
||||
},
|
||||
);
|
||||
ClientManager.sendInitNotification(
|
||||
l10n.initAppError,
|
||||
l10n.restoreSessionBody(
|
||||
AppConfig.newIssueUrl.toString(),
|
||||
e.toString(),
|
||||
),
|
||||
);
|
||||
} catch (e, s) {
|
||||
Logs().wtf('Restore client failed!', e, s);
|
||||
ClientManager.sendInitNotification(
|
||||
l10n.initAppError,
|
||||
l10n.sessionLostBody(AppConfig.newIssueUrl.toString(), e.toString()),
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
121
lib/utils/localized_exception_extension.dart
Normal file
121
lib/utils/localized_exception_extension.dart
Normal file
@@ -0,0 +1,121 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/other_party_can_receive.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:http/http.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/encryption.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import 'uia_request_manager.dart';
|
||||
|
||||
extension LocalizedExceptionExtension on Object {
|
||||
static String _formatFileSize(int size) {
|
||||
if (size < 1000) return '$size B';
|
||||
final i = (log(size) / log(1000)).floor();
|
||||
final num = (size / pow(1000, i));
|
||||
final round = num.round();
|
||||
final numString = round < 10
|
||||
? num.toStringAsFixed(2)
|
||||
: round < 100
|
||||
? num.toStringAsFixed(1)
|
||||
: round.toString();
|
||||
return '$numString ${'kMGTPEZY'[i - 1]}B';
|
||||
}
|
||||
|
||||
String toLocalizedString(
|
||||
BuildContext context, [
|
||||
ExceptionContext? exceptionContext,
|
||||
]) {
|
||||
if (this is FileTooBigMatrixException) {
|
||||
final exception = this as FileTooBigMatrixException;
|
||||
return L10n.of(
|
||||
context,
|
||||
).fileIsTooBigForServer(_formatFileSize(exception.maxFileSize));
|
||||
}
|
||||
if (this is OtherPartyCanNotReceiveMessages) {
|
||||
return L10n.of(context).otherPartyNotLoggedIn;
|
||||
}
|
||||
if (this is MatrixException) {
|
||||
switch ((this as MatrixException).error) {
|
||||
case MatrixError.M_FORBIDDEN:
|
||||
if (exceptionContext == ExceptionContext.changePassword) {
|
||||
return L10n.of(context).passwordIsWrong;
|
||||
}
|
||||
return L10n.of(context).noPermission;
|
||||
case MatrixError.M_LIMIT_EXCEEDED:
|
||||
return L10n.of(context).tooManyRequestsWarning;
|
||||
default:
|
||||
if (exceptionContext == ExceptionContext.joinRoom) {
|
||||
return L10n.of(context).unableToJoinChat;
|
||||
}
|
||||
return L10n.of(
|
||||
context,
|
||||
).serverRespondedWithError((this as MatrixException).errorMessage);
|
||||
}
|
||||
}
|
||||
if (this is InvalidPassphraseException) {
|
||||
return L10n.of(context).wrongRecoveryKey;
|
||||
}
|
||||
if (this is PlatformException) {
|
||||
if ((this as PlatformException).code == 'CANCELED') {
|
||||
return L10n.of(context).theProcessWasCanceled;
|
||||
}
|
||||
final message = (this as PlatformException).message;
|
||||
if (message != null) {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
if (this is BadServerLoginTypesException) {
|
||||
final serverVersions = (this as BadServerLoginTypesException)
|
||||
.serverLoginTypes
|
||||
.toString()
|
||||
.replaceAll('{', '"')
|
||||
.replaceAll('}', '"');
|
||||
final supportedVersions = (this as BadServerLoginTypesException)
|
||||
.supportedLoginTypes
|
||||
.toString()
|
||||
.replaceAll('{', '"')
|
||||
.replaceAll('}', '"');
|
||||
return L10n.of(
|
||||
context,
|
||||
).badServerLoginTypesException(serverVersions, supportedVersions);
|
||||
}
|
||||
if (this is IOException ||
|
||||
this is SocketException ||
|
||||
this is SyncConnectionException ||
|
||||
this is ClientException) {
|
||||
return L10n.of(context).noConnectionToTheServer;
|
||||
}
|
||||
if (this is FormatException &&
|
||||
exceptionContext == ExceptionContext.checkHomeserver) {
|
||||
return L10n.of(context).doesNotSeemToBeAValidHomeserver;
|
||||
}
|
||||
if (this is FormatException &&
|
||||
exceptionContext == ExceptionContext.checkServerSupportInfo) {
|
||||
return L10n.of(context).noContactInformationProvided;
|
||||
}
|
||||
if (this is String) return toString();
|
||||
if (this is UiaException) return toString();
|
||||
|
||||
if (exceptionContext == ExceptionContext.joinRoom) {
|
||||
return L10n.of(context).unableToJoinChat;
|
||||
}
|
||||
|
||||
return L10n.of(context).unexpectedErrorOccurded(toString());
|
||||
}
|
||||
}
|
||||
|
||||
enum ExceptionContext {
|
||||
changePassword,
|
||||
checkHomeserver,
|
||||
checkServerSupportInfo,
|
||||
joinRoom,
|
||||
}
|
||||
142
lib/utils/markdown_context_builder.dart
Normal file
142
lib/utils/markdown_context_builder.dart
Normal file
@@ -0,0 +1,142 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_text_input_dialog.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
class MarkdownContextBuilder extends StatelessWidget {
|
||||
final EditableTextState editableTextState;
|
||||
final TextEditingController controller;
|
||||
|
||||
const MarkdownContextBuilder({
|
||||
required this.editableTextState,
|
||||
required this.controller,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final value = editableTextState.textEditingValue;
|
||||
final selectedText = value.selection.textInside(value.text);
|
||||
final buttonItems = editableTextState.contextMenuButtonItems;
|
||||
final l10n = L10n.of(context);
|
||||
|
||||
return AdaptiveTextSelectionToolbar.buttonItems(
|
||||
anchors: editableTextState.contextMenuAnchors,
|
||||
buttonItems: [
|
||||
...buttonItems,
|
||||
if (selectedText.isNotEmpty) ...[
|
||||
ContextMenuButtonItem(
|
||||
label: l10n.link,
|
||||
onPressed: () async {
|
||||
final input = await showTextInputDialog(
|
||||
context: context,
|
||||
title: l10n.addLink,
|
||||
okLabel: l10n.ok,
|
||||
cancelLabel: l10n.cancel,
|
||||
validator: (text) {
|
||||
if (text.isEmpty) {
|
||||
return l10n.pleaseFillOut;
|
||||
}
|
||||
try {
|
||||
text.startsWith('http') ? Uri.parse(text) : Uri.https(text);
|
||||
} catch (_) {
|
||||
return l10n.invalidUrl;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
hintText: 'www...',
|
||||
keyboardType: TextInputType.url,
|
||||
);
|
||||
final urlString = input;
|
||||
if (urlString == null) return;
|
||||
final url = urlString.startsWith('http')
|
||||
? Uri.parse(urlString)
|
||||
: Uri.https(urlString);
|
||||
final selection = controller.selection;
|
||||
controller.text = controller.text.replaceRange(
|
||||
selection.start,
|
||||
selection.end,
|
||||
'[$selectedText]($url)',
|
||||
);
|
||||
ContextMenuController.removeAny();
|
||||
},
|
||||
),
|
||||
ContextMenuButtonItem(
|
||||
label: l10n.checkList,
|
||||
onPressed: () {
|
||||
final text = controller.text;
|
||||
final selection = controller.selection;
|
||||
|
||||
var start = selection.textBefore(text).lastIndexOf('\n');
|
||||
if (start == -1) start = 0;
|
||||
final end = selection.end;
|
||||
|
||||
final fullLineSelection = TextSelection(
|
||||
baseOffset: start,
|
||||
extentOffset: end,
|
||||
);
|
||||
|
||||
const checkBox = '- [ ]';
|
||||
|
||||
final replacedRange = fullLineSelection
|
||||
.textInside(text)
|
||||
.split('\n')
|
||||
.map(
|
||||
(line) => line.startsWith(checkBox) || line.isEmpty
|
||||
? line
|
||||
: '$checkBox $line',
|
||||
)
|
||||
.join('\n');
|
||||
controller.text = controller.text.replaceRange(
|
||||
start,
|
||||
end,
|
||||
replacedRange,
|
||||
);
|
||||
ContextMenuController.removeAny();
|
||||
},
|
||||
),
|
||||
ContextMenuButtonItem(
|
||||
label: l10n.boldText,
|
||||
onPressed: () {
|
||||
final selection = controller.selection;
|
||||
controller.text = controller.text.replaceRange(
|
||||
selection.start,
|
||||
selection.end,
|
||||
'**$selectedText**',
|
||||
);
|
||||
ContextMenuController.removeAny();
|
||||
},
|
||||
),
|
||||
ContextMenuButtonItem(
|
||||
label: l10n.italicText,
|
||||
onPressed: () {
|
||||
final selection = controller.selection;
|
||||
controller.text = controller.text.replaceRange(
|
||||
selection.start,
|
||||
selection.end,
|
||||
'*$selectedText*',
|
||||
);
|
||||
ContextMenuController.removeAny();
|
||||
},
|
||||
),
|
||||
ContextMenuButtonItem(
|
||||
label: l10n.strikeThrough,
|
||||
onPressed: () {
|
||||
final selection = controller.selection;
|
||||
controller.text = controller.text.replaceRange(
|
||||
selection.start,
|
||||
selection.end,
|
||||
'~~$selectedText~~',
|
||||
);
|
||||
ContextMenuController.removeAny();
|
||||
},
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
125
lib/utils/matrix_live_kit_calls/call_keys_event_content.dart
Normal file
125
lib/utils/matrix_live_kit_calls/call_keys_event_content.dart
Normal file
@@ -0,0 +1,125 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class CallKeysEvent extends ToDeviceEvent {
|
||||
CallKeysEvent._({
|
||||
required super.sender,
|
||||
required super.type,
|
||||
required super.content,
|
||||
});
|
||||
|
||||
factory CallKeysEvent.fromToDeviceEvent(ToDeviceEvent event) =>
|
||||
CallKeysEvent._(
|
||||
content: event.content,
|
||||
sender: event.sender,
|
||||
type: event.type,
|
||||
);
|
||||
|
||||
CallKeysEventContent get callKeysContent =>
|
||||
CallKeysEventContent.fromJson(super.content);
|
||||
|
||||
String get key =>
|
||||
String.fromCharCodes(base64Decode(callKeysContent.keys.key));
|
||||
}
|
||||
|
||||
/// To-device event content for encryption key exchange (EncryptionKeysToDeviceEventContent).
|
||||
class CallKeysEventContent {
|
||||
static const String eventType = 'io.element.call.encryption_keys';
|
||||
|
||||
final CallKeysEntry keys;
|
||||
final CallKeysMember member;
|
||||
final String roomId;
|
||||
final CallKeysSession session;
|
||||
final int? sentTs;
|
||||
|
||||
const CallKeysEventContent({
|
||||
required this.keys,
|
||||
required this.member,
|
||||
required this.roomId,
|
||||
required this.session,
|
||||
this.sentTs,
|
||||
});
|
||||
|
||||
factory CallKeysEventContent.fromJson(Map<String, Object?> json) =>
|
||||
CallKeysEventContent(
|
||||
keys: CallKeysEntry.fromJson(
|
||||
Map<String, Object?>.from(json['keys'] as Map),
|
||||
),
|
||||
member: CallKeysMember.fromJson(
|
||||
Map<String, Object?>.from(json['member'] as Map),
|
||||
),
|
||||
roomId: json['room_id'] as String,
|
||||
session: CallKeysSession.fromJson(
|
||||
Map<String, Object?>.from(json['session'] as Map),
|
||||
),
|
||||
sentTs: json['sent_ts'] as int?,
|
||||
);
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
'keys': keys.toJson(),
|
||||
'member': member.toJson(),
|
||||
'room_id': roomId,
|
||||
'session': session.toJson(),
|
||||
if (sentTs != null) 'sent_ts': sentTs,
|
||||
};
|
||||
}
|
||||
|
||||
class CallKeysEntry {
|
||||
final int index;
|
||||
final String key;
|
||||
|
||||
const CallKeysEntry({required this.index, required this.key});
|
||||
|
||||
factory CallKeysEntry.fromJson(Map<String, Object?> json) =>
|
||||
CallKeysEntry(index: json['index'] as int, key: json['key'] as String);
|
||||
|
||||
Map<String, Object?> toJson() => {'index': index, 'key': key};
|
||||
}
|
||||
|
||||
class CallKeysMember {
|
||||
final String id;
|
||||
final String claimedDeviceId;
|
||||
|
||||
const CallKeysMember({required this.id, required this.claimedDeviceId});
|
||||
|
||||
factory CallKeysMember.fromJson(Map<String, Object?> json) => CallKeysMember(
|
||||
id: json['id'] as String,
|
||||
claimedDeviceId: json['claimed_device_id'] as String,
|
||||
);
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
'id': id,
|
||||
'claimed_device_id': claimedDeviceId,
|
||||
};
|
||||
}
|
||||
|
||||
class CallKeysSession {
|
||||
final String application;
|
||||
final String callId;
|
||||
final String scope;
|
||||
|
||||
const CallKeysSession({
|
||||
required this.application,
|
||||
required this.callId,
|
||||
required this.scope,
|
||||
});
|
||||
|
||||
factory CallKeysSession.fromJson(Map<String, Object?> json) =>
|
||||
CallKeysSession(
|
||||
application: json['application'] as String,
|
||||
callId: json['call_id'] as String,
|
||||
scope: json['scope'] as String,
|
||||
);
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
'application': application,
|
||||
'call_id': callId,
|
||||
'scope': scope,
|
||||
};
|
||||
}
|
||||
352
lib/utils/matrix_live_kit_calls/matrix_live_kit_call.dart
Normal file
352
lib/utils/matrix_live_kit_calls/matrix_live_kit_call.dart
Normal file
@@ -0,0 +1,352 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/call_keys_event_content.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/matrix_live_kit_call_member.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
extension MatrixRtcClientExtension on Client {
|
||||
Future<List<String>> getLiveKitServiceUrls() async {
|
||||
if (AppSettings.customLiveKitInstance.value.isNotEmpty) {
|
||||
return [AppSettings.customLiveKitInstance.value];
|
||||
}
|
||||
final wellKnown = await getWellknown();
|
||||
final rtcFociMap = wellKnown.additionalProperties
|
||||
.tryGetMap<String, Object?>(
|
||||
'org.matrix.msc4143.rtc_foci',
|
||||
TryGet.silent,
|
||||
); // Famedly style
|
||||
if (rtcFociMap != null) {
|
||||
return [?rtcFociMap.tryGet<String>('livekit_service_url')];
|
||||
}
|
||||
|
||||
// TODO: Also query /_matrix/client/unstable/org.matrix.msc4143/rtc/transports
|
||||
|
||||
return wellKnown.additionalProperties
|
||||
.tryGetList<Map<String, Object?>>('org.matrix.msc4143.rtc_foci')
|
||||
?.map((foci) => foci.tryGet<String>('livekit_service_url'))
|
||||
.whereType<String>()
|
||||
.toList() ??
|
||||
[];
|
||||
}
|
||||
|
||||
Stream<CallKeysEvent> get onCallEncryptionKeys => onToDeviceEvent.stream
|
||||
.where((event) => event.type == CallKeysEventContent.eventType)
|
||||
.map(CallKeysEvent.fromToDeviceEvent);
|
||||
}
|
||||
|
||||
extension MatrixRtcRoomExtension on Room {
|
||||
bool get hasActiveMatrixRtcCall => getActiveMatrixRtcMembers().isNotEmpty;
|
||||
|
||||
MatrixRtcCallIntent? get activeMatrixRtcCallIntent {
|
||||
final members = getActiveMatrixRtcMembers();
|
||||
if (members.isEmpty) return null;
|
||||
if (members.any((member) => member.callIntent == .video)) return .video;
|
||||
return .voice;
|
||||
}
|
||||
|
||||
bool get hasPermissionForMatrixRtcCall =>
|
||||
canChangeStateEvent(MatrixRtcCallMember.eventType);
|
||||
|
||||
List<MatrixRtcCallMember> getActiveMatrixRtcMembers() {
|
||||
final states = this.states[MatrixRtcCallMember.eventType];
|
||||
if (states == null) return [];
|
||||
// Empty content {} means the member has left — filter those out
|
||||
final activeMemberStates = states.values.where((event) {
|
||||
if (event.content.isEmpty) return false;
|
||||
if (event is! Event) return false;
|
||||
try {
|
||||
final validContent = MatrixRtcCallMember.fromJson(
|
||||
event.content,
|
||||
senderId: event.senderId,
|
||||
);
|
||||
if (validContent.focusActive?.type != 'livekit') return false;
|
||||
final expiresAt = (validContent.createdAt ?? event.originServerTs).add(
|
||||
validContent.expires,
|
||||
);
|
||||
if (expiresAt.isBefore(DateTime.now())) return false;
|
||||
return true;
|
||||
} catch (e, s) {
|
||||
Logs().d('Invalid "org.matrix.msc3401.call.member" event!', e, s);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return activeMemberStates
|
||||
.map(
|
||||
(state) => MatrixRtcCallMember.fromJson(
|
||||
state.content,
|
||||
senderId: state.senderId,
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
|
||||
String get _ownMatrixRtcMembershipStateKey =>
|
||||
'_${client.userID}_${client.deviceID}_m.call';
|
||||
|
||||
MatrixRtcCallMember? get ownMatrixRtcMembership {
|
||||
final state = getState(
|
||||
MatrixRtcCallMember.eventType,
|
||||
_ownMatrixRtcMembershipStateKey,
|
||||
);
|
||||
if (state == null || state.content.isEmpty) return null;
|
||||
try {
|
||||
return MatrixRtcCallMember.fromJson(
|
||||
state.content,
|
||||
senderId: state.senderId,
|
||||
);
|
||||
} catch (e, s) {
|
||||
Logs().d(
|
||||
'Unknown format for ${MatrixRtcCallMember.eventType} event',
|
||||
e,
|
||||
s,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setMatrixRtcMembershipState(
|
||||
List<MatrixRtcFocusPreferred> fociPreferred, {
|
||||
MatrixRtcCallIntent intent = MatrixRtcCallIntent.video,
|
||||
}) => client.setRoomStateWithKey(
|
||||
id,
|
||||
MatrixRtcCallMember.eventType,
|
||||
_ownMatrixRtcMembershipStateKey,
|
||||
MatrixRtcCallMember(
|
||||
application: 'm.call',
|
||||
callId: '',
|
||||
deviceId: client.deviceID,
|
||||
expires: Duration(hours: 4),
|
||||
createdAt: DateTime.now(),
|
||||
fociPreferred: fociPreferred,
|
||||
focusActive: MatrixRtcFocusActive(
|
||||
focusSelection: 'oldest_membership',
|
||||
type: 'livekit',
|
||||
),
|
||||
callIntent: intent,
|
||||
membershipId: '${client.userID}:${client.deviceID}',
|
||||
scope: 'm.room',
|
||||
senderId: null,
|
||||
).toJson(),
|
||||
);
|
||||
|
||||
bool participantRaisedHandInMatrixRtcCall(
|
||||
String matrixId,
|
||||
Timeline timeline,
|
||||
) {
|
||||
final stateEvent =
|
||||
states[MatrixRtcCallMember.eventType]?[_ownMatrixRtcMembershipStateKey]
|
||||
as Event?;
|
||||
if (stateEvent == null) return false;
|
||||
final aggregatedEvents = timeline
|
||||
.aggregatedEvents[stateEvent.eventId]?['m.annotation']
|
||||
?.where(
|
||||
(event) =>
|
||||
event.senderId == matrixId &&
|
||||
event.content
|
||||
.tryGetMap<String, Object?>('m.relates_to')
|
||||
?.tryGet<String>('key') ==
|
||||
'🖐️',
|
||||
);
|
||||
if (aggregatedEvents == null || aggregatedEvents.isEmpty) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<String?> raiseHandInMatrixRtcCall() async {
|
||||
final ownMemberStateEvent =
|
||||
states[MatrixRtcCallMember.eventType]?[_ownMatrixRtcMembershipStateKey]
|
||||
as Event?;
|
||||
if (ownMemberStateEvent == null) return null;
|
||||
return await sendReaction(ownMemberStateEvent.eventId, '🖐️');
|
||||
}
|
||||
|
||||
Future<String?> lowerHandInMatrixRtcCall(Timeline timeline) async {
|
||||
final ownMemberStateEvent =
|
||||
states[MatrixRtcCallMember.eventType]?[_ownMatrixRtcMembershipStateKey]
|
||||
as Event?;
|
||||
if (ownMemberStateEvent == null) return null;
|
||||
final reaction = timeline.events.firstWhereOrNull(
|
||||
(event) =>
|
||||
event.type == EventTypes.Reaction &&
|
||||
event.relationshipEventId == ownMemberStateEvent.eventId &&
|
||||
event.senderId == client.userID &&
|
||||
event.status.isSent &&
|
||||
event.content
|
||||
.tryGetMap<String, Object?>('m.relates_to')
|
||||
?.tryGet<String>('key') ==
|
||||
'🖐️',
|
||||
);
|
||||
if (reaction == null) {
|
||||
throw Exception('Hand raise reaction event not found!');
|
||||
}
|
||||
return await reaction.redactEvent();
|
||||
}
|
||||
|
||||
Future<void> shareMatrixRtcCallKey({
|
||||
required Uint8List key,
|
||||
required int index,
|
||||
required String memberId,
|
||||
required List<DeviceKeys> deviceKeys,
|
||||
}) async {
|
||||
if (deviceKeys.isEmpty) {
|
||||
Logs().d('No devices to share call keys with');
|
||||
return;
|
||||
}
|
||||
Logs().d(
|
||||
'Share call keys with',
|
||||
deviceKeys.map((key) => '${key.userId}:${key.deviceId}'),
|
||||
);
|
||||
|
||||
final doNotEncryptTo = deviceKeys.where((d) => !d.encryptToDevice);
|
||||
if (doNotEncryptTo.isNotEmpty) {
|
||||
Logs().w(
|
||||
'Not sharing keys with ${doNotEncryptTo.length} device(s) because of key sharing restrictions!',
|
||||
);
|
||||
deviceKeys.removeWhere((d) => !d.encryptToDevice);
|
||||
}
|
||||
|
||||
await client.sendToDeviceEncrypted(
|
||||
deviceKeys,
|
||||
CallKeysEventContent.eventType,
|
||||
CallKeysEventContent(
|
||||
keys: CallKeysEntry(index: index, key: base64Encode(key)),
|
||||
member: CallKeysMember(id: memberId, claimedDeviceId: client.deviceID!),
|
||||
roomId: id,
|
||||
sentTs: DateTime.now().millisecondsSinceEpoch,
|
||||
session: CallKeysSession(
|
||||
application: 'm.call',
|
||||
callId: '',
|
||||
scope: 'm.room',
|
||||
),
|
||||
).toJson(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<MatrixRtcCredentials> joinMatrixRtcCall({
|
||||
MatrixRtcCallIntent intent = MatrixRtcCallIntent.video,
|
||||
}) async {
|
||||
await postLoad();
|
||||
if (ownMatrixRtcMembership != null) {
|
||||
Logs().w(
|
||||
'User has already an active rtc membership state in this room. Resetting it now...',
|
||||
);
|
||||
}
|
||||
Logs().d('[Join MatrixRtc Call] (1/5) Get LiveKit Backend Urls...');
|
||||
|
||||
final hasActiveMatrixRtcCall = this.hasActiveMatrixRtcCall;
|
||||
|
||||
final urls = getActiveMatrixRtcMembers()
|
||||
.map(
|
||||
(state) =>
|
||||
state.fociPreferred.map((focus) => focus.livekitServiceUrl),
|
||||
)
|
||||
.fold<List<String>>([], (urls, foci) => [...urls, ...foci]);
|
||||
|
||||
if (urls.isEmpty) {
|
||||
urls.addAll(await client.getLiveKitServiceUrls());
|
||||
}
|
||||
|
||||
Logs().v('Available SFUs', urls);
|
||||
if (urls.isEmpty) {
|
||||
throw Exception('This server does not support livekit calls!');
|
||||
}
|
||||
|
||||
Logs().d(
|
||||
'[Join MatrixRtc Call] (2/5) Set "${MatrixRtcCallMember.eventType}" State event...',
|
||||
);
|
||||
await setMatrixRtcMembershipState(
|
||||
urls
|
||||
.map(
|
||||
(url) => MatrixRtcFocusPreferred(
|
||||
type: 'livekit',
|
||||
livekitServiceUrl: url,
|
||||
livekitAlias: id,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
intent: intent,
|
||||
);
|
||||
|
||||
if (!hasActiveMatrixRtcCall) {
|
||||
final dmUserId = directChatMatrixID;
|
||||
if (dmUserId != null) {
|
||||
await sendRtcNotification(type: .ring, userIds: [dmUserId]);
|
||||
} else {
|
||||
await sendRtcNotification(type: .notification, mentionRoom: true);
|
||||
}
|
||||
}
|
||||
|
||||
Logs().v('[Join MatrixRtc Call] (3/5) Request OpenId Token...');
|
||||
final openIdCredentials = await client.requestOpenIdToken(
|
||||
client.userID!,
|
||||
{},
|
||||
);
|
||||
|
||||
for (final url in urls) {
|
||||
try {
|
||||
Logs().d(
|
||||
'[Join MatrixRtc Call] (4/5) Try authenticate to LiveKit instance $url...',
|
||||
);
|
||||
final response = await client.httpClient.post(
|
||||
Uri.parse('${url.replaceAll(RegExp(r'/+$'), '')}/sfu/get'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({
|
||||
'room': id,
|
||||
'openid_token': openIdCredentials.toJson(),
|
||||
'device_id': client.deviceID,
|
||||
}),
|
||||
);
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception(response.reasonPhrase ?? response.body);
|
||||
}
|
||||
final json =
|
||||
jsonDecode(utf8.decode(response.bodyBytes)) as Map<String, Object?>;
|
||||
Logs().d('Use SFU', url);
|
||||
return MatrixRtcCredentials.fromJson(json);
|
||||
} catch (e) {
|
||||
Logs().v(
|
||||
'[Join MatrixRtc Call] (4/4) Unable to authenticate to $url',
|
||||
e,
|
||||
);
|
||||
}
|
||||
}
|
||||
throw Exception(
|
||||
'Unable to authenticate to any of the visible LiveKit instances!',
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> leaveMatrixRtcCall() async {
|
||||
await client.setRoomStateWithKey(
|
||||
id,
|
||||
MatrixRtcCallMember.eventType,
|
||||
_ownMatrixRtcMembershipStateKey,
|
||||
{},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MatrixRtcCredentials {
|
||||
final String url, jwt;
|
||||
const MatrixRtcCredentials({required this.url, required this.jwt});
|
||||
factory MatrixRtcCredentials.fromJson(Map<String, Object?> json) =>
|
||||
MatrixRtcCredentials(
|
||||
url: json['url'] as String,
|
||||
jwt: json['jwt'] as String,
|
||||
);
|
||||
}
|
||||
|
||||
enum MatrixRtcCallIntent {
|
||||
voice(callKitType: 0),
|
||||
video(callKitType: 1);
|
||||
|
||||
final int callKitType;
|
||||
const MatrixRtcCallIntent({required this.callKitType});
|
||||
}
|
||||
135
lib/utils/matrix_live_kit_calls/matrix_live_kit_call_member.dart
Normal file
135
lib/utils/matrix_live_kit_calls/matrix_live_kit_call_member.dart
Normal file
@@ -0,0 +1,135 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/matrix_live_kit_call.dart';
|
||||
import 'package:matrix/matrix_api_lite/utils/try_get_map_extension.dart';
|
||||
|
||||
class MatrixRtcCallMember {
|
||||
static const String eventType = 'org.matrix.msc3401.call.member';
|
||||
|
||||
final String application;
|
||||
final String callId;
|
||||
final String? deviceId;
|
||||
final DateTime? createdAt;
|
||||
final Duration expires;
|
||||
final List<MatrixRtcFocusPreferred> fociPreferred;
|
||||
final MatrixRtcFocusActive? focusActive;
|
||||
final MatrixRtcCallIntent callIntent;
|
||||
final String? membershipId;
|
||||
final String scope;
|
||||
|
||||
/// Not part of JSON content but for convenience
|
||||
final String? senderId;
|
||||
|
||||
const MatrixRtcCallMember({
|
||||
required this.application,
|
||||
required this.callId,
|
||||
required this.deviceId,
|
||||
required this.expires,
|
||||
required this.fociPreferred,
|
||||
required this.focusActive,
|
||||
required this.callIntent,
|
||||
required this.membershipId,
|
||||
required this.scope,
|
||||
required this.createdAt,
|
||||
required this.senderId,
|
||||
});
|
||||
|
||||
factory MatrixRtcCallMember.fromJson(
|
||||
Map<String, Object?> json, {
|
||||
required String? senderId,
|
||||
}) => MatrixRtcCallMember(
|
||||
application: json.tryGet<String>('application') ?? '',
|
||||
callId: json.tryGet<String>('call_id') ?? '',
|
||||
deviceId: json.tryGet<String>('device_id'),
|
||||
createdAt: json.tryGet<int>('created_at') == null
|
||||
? null
|
||||
: DateTime.fromMillisecondsSinceEpoch(json.tryGet<int>('created_at')!),
|
||||
expires: Duration(milliseconds: json.tryGet<int>('expires') ?? 0),
|
||||
fociPreferred:
|
||||
(json['foci_preferred'] as List?)
|
||||
?.whereType<Map>()
|
||||
.map(
|
||||
(e) => MatrixRtcFocusPreferred.fromJson(
|
||||
Map<String, Object?>.from(e),
|
||||
),
|
||||
)
|
||||
.toList() ??
|
||||
[],
|
||||
focusActive: json['focus_active'] is Map
|
||||
? MatrixRtcFocusActive.fromJson(
|
||||
Map<String, Object?>.from(json['focus_active'] as Map),
|
||||
)
|
||||
: null,
|
||||
callIntent:
|
||||
MatrixRtcCallIntent.values.singleWhereOrNull(
|
||||
(intent) => intent.name == json.tryGet<String>('m.call.intent'),
|
||||
) ??
|
||||
MatrixRtcCallIntent.video,
|
||||
membershipId: json.tryGet<String>('membershipID'),
|
||||
scope: json.tryGet<String>('scope') ?? 'm.room',
|
||||
senderId: senderId,
|
||||
);
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
'application': application,
|
||||
'call_id': callId,
|
||||
if (deviceId != null) 'device_id': deviceId,
|
||||
'expires': expires.inMilliseconds,
|
||||
'foci_preferred': fociPreferred.map((f) => f.toJson()).toList(),
|
||||
if (focusActive != null) 'focus_active': focusActive!.toJson(),
|
||||
'm.call.intent': callIntent.name,
|
||||
if (membershipId != null) 'membershipID': membershipId,
|
||||
'scope': scope,
|
||||
'created_at': ?createdAt?.millisecondsSinceEpoch,
|
||||
};
|
||||
}
|
||||
|
||||
class MatrixRtcFocusPreferred {
|
||||
final String type;
|
||||
final String livekitServiceUrl;
|
||||
final String livekitAlias;
|
||||
|
||||
const MatrixRtcFocusPreferred({
|
||||
required this.type,
|
||||
required this.livekitServiceUrl,
|
||||
required this.livekitAlias,
|
||||
});
|
||||
|
||||
factory MatrixRtcFocusPreferred.fromJson(Map<String, Object?> json) =>
|
||||
MatrixRtcFocusPreferred(
|
||||
type: json.tryGet<String>('type') ?? '',
|
||||
livekitServiceUrl: json.tryGet<String>('livekit_service_url') ?? '',
|
||||
livekitAlias: json.tryGet<String>('livekit_alias') ?? '',
|
||||
);
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
'type': type,
|
||||
'livekit_service_url': livekitServiceUrl,
|
||||
'livekit_alias': livekitAlias,
|
||||
};
|
||||
}
|
||||
|
||||
class MatrixRtcFocusActive {
|
||||
final String type;
|
||||
final String focusSelection;
|
||||
|
||||
const MatrixRtcFocusActive({
|
||||
required this.type,
|
||||
required this.focusSelection,
|
||||
});
|
||||
|
||||
factory MatrixRtcFocusActive.fromJson(Map<String, Object?> json) =>
|
||||
MatrixRtcFocusActive(
|
||||
type: json.tryGet<String>('type') ?? '',
|
||||
focusSelection: json.tryGet<String>('focus_selection') ?? '',
|
||||
);
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
'type': type,
|
||||
'focus_selection': focusSelection,
|
||||
};
|
||||
}
|
||||
49
lib/utils/matrix_sdk_extensions/device_extension.dart
Normal file
49
lib/utils/matrix_sdk_extensions/device_extension.dart
Normal file
@@ -0,0 +1,49 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
IconData _getIconFromName(String displayname) {
|
||||
final name = displayname.toLowerCase();
|
||||
if ({'android'}.any(name.contains)) {
|
||||
return Icons.phone_android_outlined;
|
||||
}
|
||||
if ({'ios', 'ipad', 'iphone', 'ipod'}.any(name.contains)) {
|
||||
return Icons.phone_iphone_outlined;
|
||||
}
|
||||
if ({
|
||||
'web',
|
||||
'http://',
|
||||
'https://',
|
||||
'firefox',
|
||||
'chrome',
|
||||
'/_matrix',
|
||||
'safari',
|
||||
'opera',
|
||||
}.any(name.contains)) {
|
||||
return Icons.web_outlined;
|
||||
}
|
||||
if ({'desktop', 'windows', 'macos', 'linux', 'ubuntu'}.any(name.contains)) {
|
||||
return Icons.desktop_mac_outlined;
|
||||
}
|
||||
return Icons.device_unknown_outlined;
|
||||
}
|
||||
|
||||
extension DeviceExtension on Device {
|
||||
String get displayname =>
|
||||
(displayName?.isNotEmpty ?? false) ? displayName! : 'Unknown device';
|
||||
|
||||
IconData get icon => _getIconFromName(displayname);
|
||||
}
|
||||
|
||||
extension DeviceKeysExtension on DeviceKeys {
|
||||
String get displayname => (deviceDisplayName?.isNotEmpty ?? false)
|
||||
? deviceDisplayName!
|
||||
: 'Unknown device';
|
||||
|
||||
IconData get icon => _getIconFromName(displayname);
|
||||
}
|
||||
68
lib/utils/matrix_sdk_extensions/event_extension.dart
Normal file
68
lib/utils/matrix_sdk_extensions/event_extension.dart
Normal file
@@ -0,0 +1,68 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:async/async.dart' as async;
|
||||
import 'package:tatchat/utils/size_string.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import 'matrix_file_extension.dart';
|
||||
|
||||
extension LocalizedBody on Event {
|
||||
Future<async.Result<MatrixFile?>> _getFile(BuildContext context) =>
|
||||
showFutureLoadingDialog(
|
||||
context: context,
|
||||
futureWithProgress: (onProgress) {
|
||||
final fileSize = infoMap['size'] is int
|
||||
? infoMap['size'] as int
|
||||
: null;
|
||||
return downloadAndDecryptAttachment(
|
||||
onDownloadProgress: fileSize == null
|
||||
? null
|
||||
: (bytes) => onProgress(bytes / fileSize),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
Future<void> saveFile(BuildContext context) async {
|
||||
final matrixFile = await _getFile(context);
|
||||
if (!context.mounted) return;
|
||||
|
||||
matrixFile.result?.save(context);
|
||||
}
|
||||
|
||||
Future<void> shareFile(BuildContext context) async {
|
||||
final matrixFile = await _getFile(context);
|
||||
if (!context.mounted) return;
|
||||
|
||||
matrixFile.result?.share(context);
|
||||
}
|
||||
|
||||
bool get isAttachmentSmallEnough =>
|
||||
infoMap['size'] is int &&
|
||||
(infoMap['size'] as int) < room.client.database.maxFileSize;
|
||||
|
||||
bool get isThumbnailSmallEnough =>
|
||||
thumbnailInfoMap['size'] is int &&
|
||||
(thumbnailInfoMap['size'] as int) < room.client.database.maxFileSize;
|
||||
|
||||
bool get showThumbnail =>
|
||||
[
|
||||
MessageTypes.Image,
|
||||
MessageTypes.Sticker,
|
||||
MessageTypes.Video,
|
||||
].contains(messageType) &&
|
||||
(kIsWeb ||
|
||||
isAttachmentSmallEnough ||
|
||||
isThumbnailSmallEnough ||
|
||||
(content['url'] is String));
|
||||
|
||||
String? get sizeString => content
|
||||
.tryGetMap<String, Object?>('info')
|
||||
?.tryGet<int>('size')
|
||||
?.sizeString;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
extension VisibleInGuiExtension on List<Event> {
|
||||
List<Event> filterByVisibleInGui({
|
||||
String? exceptionEventId,
|
||||
String? threadId,
|
||||
}) => where((event) {
|
||||
if (threadId != null &&
|
||||
event.relationshipType != RelationshipTypes.reaction) {
|
||||
if ((event.relationshipType != RelationshipTypes.thread ||
|
||||
event.relationshipEventId != threadId) &&
|
||||
event.eventId != threadId) {
|
||||
return false;
|
||||
}
|
||||
} else if (event.relationshipType == RelationshipTypes.thread) {
|
||||
return false;
|
||||
}
|
||||
return event.isVisibleInGui || event.eventId == exceptionEventId;
|
||||
}).toList();
|
||||
}
|
||||
|
||||
extension IsStateExtension on Event {
|
||||
bool get isVisibleInGui =>
|
||||
// always filter out edit and reaction relationships
|
||||
!{
|
||||
RelationshipTypes.edit,
|
||||
RelationshipTypes.reaction,
|
||||
}.contains(relationshipType) &&
|
||||
// always filter out m.key.* and other known but unimportant events
|
||||
!isKnownHiddenStates &&
|
||||
// event types to hide: redaction and reaction events
|
||||
// if a reaction has been redacted we also want it to be hidden in the timeline
|
||||
!{EventTypes.Reaction, EventTypes.Redaction}.contains(type) &&
|
||||
// if we enabled to hide all redacted events, don't show those
|
||||
(!AppSettings.hideRedactedEvents.value || !redacted) &&
|
||||
// if we enabled to hide all unknown events, don't show those
|
||||
(!AppSettings.hideUnknownEvents.value || isEventTypeKnown);
|
||||
|
||||
bool get isState => !{EventTypes.Message, EventTypes.Sticker}.contains(type);
|
||||
|
||||
bool get isCollapsedState => !{
|
||||
EventTypes.Message,
|
||||
EventTypes.Sticker,
|
||||
EventTypes.RoomCreate,
|
||||
EventTypes.RoomTombstone,
|
||||
}.contains(type);
|
||||
|
||||
bool get isKnownHiddenStates =>
|
||||
{PollEventContent.responseType}.contains(type) ||
|
||||
type.startsWith('m.key.verification.');
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/client_manager.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:path/path.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:path_provider_foundation/path_provider_foundation.dart';
|
||||
import 'package:sqflite_common/utils/utils.dart' as sqflite_utils;
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
import 'package:universal_html/html.dart' as html;
|
||||
|
||||
import 'cipher.dart';
|
||||
|
||||
Future<DatabaseApi> flutterMatrixSdkDatabaseBuilder(String clientName) async {
|
||||
try {
|
||||
return await _constructDatabase(clientName);
|
||||
} catch (e, s) {
|
||||
Logs().wtf('Unable to construct database!', e, s);
|
||||
|
||||
try {
|
||||
// Send error notification:
|
||||
final l10n = await lookupL10n(PlatformDispatcher.instance.locale);
|
||||
// We expect that the database cannot be open on iOS 2.8.0 due to that
|
||||
// the team ID has changed and te app can no longer access the database
|
||||
// key in the iOS keychain. This should be removed from 2.9.0 on.
|
||||
if (!PlatformInfos.isIOS) {
|
||||
ClientManager.sendInitNotification(l10n.initAppError, e.toString());
|
||||
}
|
||||
} catch (e, s) {
|
||||
Logs().e('Unable to send error notification', e, s);
|
||||
}
|
||||
|
||||
// Delete database file:
|
||||
if (!kIsWeb) {
|
||||
final dbFile = File(await _getDatabasePath(clientName));
|
||||
if (await dbFile.exists()) await dbFile.delete();
|
||||
}
|
||||
|
||||
// Try again
|
||||
return await _constructDatabase(clientName);
|
||||
}
|
||||
}
|
||||
|
||||
Future<Directory?> getFileStorageLocation() async {
|
||||
try {
|
||||
late final Directory temporaryDirectory;
|
||||
if (PlatformInfos.isIOS) {
|
||||
final containerPath = await PathProviderFoundation().getContainerPath(
|
||||
appGroupIdentifier: 'group.im.fluffychat.app',
|
||||
);
|
||||
temporaryDirectory = Directory(containerPath!);
|
||||
} else if (PlatformInfos.isLinux) {
|
||||
temporaryDirectory = await getApplicationCacheDirectory();
|
||||
} else {
|
||||
temporaryDirectory = await getTemporaryDirectory();
|
||||
}
|
||||
return await Directory(
|
||||
join(temporaryDirectory.path, 'fluffychat_download_cache'),
|
||||
).create(recursive: true);
|
||||
} on MissingPlatformDirectoryException catch (_) {
|
||||
Logs().w(
|
||||
'No temporary directory for file cache available on this platform.',
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<MatrixSdkDatabase> _constructDatabase(String clientName) async {
|
||||
if (kIsWeb) {
|
||||
html.window.navigator.storage?.persist();
|
||||
return await MatrixSdkDatabase.init(clientName);
|
||||
}
|
||||
|
||||
final cipher = await getDatabaseCipher();
|
||||
|
||||
final fileStorageLocation = await getFileStorageLocation();
|
||||
|
||||
final path = await _getDatabasePath(clientName);
|
||||
|
||||
// import the SQLite / SQLCipher shared objects / dynamic libraries
|
||||
final factory = createDatabaseFactoryFfi();
|
||||
|
||||
// required for [getDatabasesPath]
|
||||
databaseFactory = factory;
|
||||
|
||||
// migrate from potential previous SQLite database path to current one
|
||||
await _migrateLegacyLocation(path, clientName);
|
||||
|
||||
// in case we got a cipher, we use the encryption helper
|
||||
// to manage SQLite encryption
|
||||
final helper = cipher == null
|
||||
? null
|
||||
: SQfLiteEncryptionHelper(factory: factory, path: path, cipher: cipher);
|
||||
|
||||
// check whether the DB is already encrypted and otherwise do so
|
||||
await helper?.ensureDatabaseFileEncrypted();
|
||||
|
||||
final database = await factory.openDatabase(
|
||||
path,
|
||||
options: OpenDatabaseOptions(
|
||||
version: 1,
|
||||
// most important : apply encryption when opening the DB
|
||||
onConfigure: helper?.applyPragmaKey,
|
||||
),
|
||||
);
|
||||
|
||||
Logs().i('Database file size', await File(database.path).length());
|
||||
|
||||
final pageCount = sqflite_utils.firstIntValue(
|
||||
await database.rawQuery('PRAGMA page_count'),
|
||||
);
|
||||
final freePages = sqflite_utils.firstIntValue(
|
||||
await database.rawQuery('PRAGMA freelist_count'),
|
||||
);
|
||||
final pageSize = sqflite_utils.firstIntValue(
|
||||
await database.rawQuery('PRAGMA page_size'),
|
||||
);
|
||||
Logs().i(
|
||||
'DB pages: $pageCount total, $freePages free (~${(freePages ?? 0) * (pageSize ?? 0)} bytes wasted)',
|
||||
);
|
||||
|
||||
final tables = await database.rawQuery(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",
|
||||
);
|
||||
for (final t in tables) {
|
||||
final name = t['name'] as String;
|
||||
final c = sqflite_utils.firstIntValue(
|
||||
await database.rawQuery('SELECT COUNT(*) FROM "$name"'),
|
||||
);
|
||||
Logs().i('Table $name: $c rows');
|
||||
}
|
||||
|
||||
await _ensureIncrementalAutoVacuum(database);
|
||||
|
||||
return await MatrixSdkDatabase.init(
|
||||
clientName,
|
||||
database: database,
|
||||
maxFileSize: 1000 * 1000 * 10,
|
||||
fileStorageLocation: fileStorageLocation?.uri,
|
||||
deleteFilesAfterDuration: const Duration(days: 30),
|
||||
);
|
||||
}
|
||||
|
||||
/// Without auto vacuum the database can never really shrink
|
||||
Future<void> _ensureIncrementalAutoVacuum(Database database) async {
|
||||
const incrementalAutoVacuum = 2;
|
||||
|
||||
final currentMode = sqflite_utils.firstIntValue(
|
||||
await database.rawQuery('PRAGMA auto_vacuum'),
|
||||
);
|
||||
|
||||
if (currentMode != incrementalAutoVacuum) {
|
||||
Logs().i('Switching database to incremental auto_vacuum...');
|
||||
await database.execute('PRAGMA auto_vacuum = $incrementalAutoVacuum');
|
||||
await database.execute('VACUUM');
|
||||
return;
|
||||
}
|
||||
|
||||
await database.execute('PRAGMA incremental_vacuum');
|
||||
}
|
||||
|
||||
Future<String> _getDatabaseDirectory() async {
|
||||
if (PlatformInfos.isIOS) {
|
||||
final containerPath = await PathProviderFoundation().getContainerPath(
|
||||
appGroupIdentifier: 'group.im.fluffychat.app',
|
||||
);
|
||||
if (containerPath == null) {
|
||||
Logs().w('No container path found for iOS app!');
|
||||
return (await getLibraryDirectory()).path;
|
||||
}
|
||||
return containerPath;
|
||||
}
|
||||
if (PlatformInfos.isMacOS) {
|
||||
return (await getLibraryDirectory()).path;
|
||||
}
|
||||
return (await getApplicationSupportDirectory()).path;
|
||||
}
|
||||
|
||||
Future<String> _getDatabasePath(String clientName) async {
|
||||
final databaseDirectory = await _getDatabaseDirectory();
|
||||
|
||||
return join(databaseDirectory, '$clientName.sqlite');
|
||||
}
|
||||
|
||||
Future<void> _migrateLegacyLocation(
|
||||
String sqlFilePath,
|
||||
String clientName,
|
||||
) async {
|
||||
final oldPath = PlatformInfos.isDesktop
|
||||
? (await getApplicationSupportDirectory()).path
|
||||
: PlatformInfos.isIOS
|
||||
? (await getLibraryDirectory()).path
|
||||
: await getDatabasesPath();
|
||||
|
||||
final oldFilePath = join(oldPath, '$clientName.sqlite');
|
||||
if (oldFilePath == sqlFilePath) return;
|
||||
|
||||
final maybeOldFile = File(oldFilePath);
|
||||
if (await maybeOldFile.exists()) {
|
||||
Logs().i(
|
||||
'Migrate legacy location for database from "$oldFilePath" to "$sqlFilePath"',
|
||||
);
|
||||
await maybeOldFile.copy(sqlFilePath);
|
||||
await maybeOldFile.delete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/client_manager.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
const _passwordStorageKey = 'database_password';
|
||||
|
||||
Future<String?> getDatabaseCipher() async {
|
||||
String? password;
|
||||
|
||||
const iosOptions = IOSOptions(groupId: 'group.im.fluffychat.app');
|
||||
|
||||
try {
|
||||
password = await FlutterSecureStorage(
|
||||
iOptions: iosOptions,
|
||||
).read(key: _passwordStorageKey, iOptions: iosOptions);
|
||||
if (password != null) return password;
|
||||
|
||||
if (PlatformInfos.isIOS) {
|
||||
final legacyPassword = await FlutterSecureStorage().read(
|
||||
key: _passwordStorageKey,
|
||||
);
|
||||
if (legacyPassword != null) {
|
||||
Logs().i('Migrate database key location on iOS...');
|
||||
await FlutterSecureStorage().delete(key: _passwordStorageKey);
|
||||
await FlutterSecureStorage(iOptions: iosOptions).write(
|
||||
key: _passwordStorageKey,
|
||||
value: legacyPassword,
|
||||
iOptions: iosOptions,
|
||||
);
|
||||
return legacyPassword;
|
||||
}
|
||||
}
|
||||
|
||||
final rng = Random.secure();
|
||||
final list = Uint8List(32);
|
||||
list.setAll(0, Iterable.generate(list.length, (i) => rng.nextInt(256)));
|
||||
final newPassword = base64UrlEncode(list);
|
||||
await FlutterSecureStorage(
|
||||
iOptions: iosOptions,
|
||||
).write(key: _passwordStorageKey, value: newPassword, iOptions: iosOptions);
|
||||
// workaround for if we just wrote to the key and it still doesn't exist
|
||||
password = await FlutterSecureStorage(
|
||||
iOptions: iosOptions,
|
||||
).read(key: _passwordStorageKey, iOptions: iosOptions);
|
||||
if (password == null) throw MissingPluginException();
|
||||
return password;
|
||||
} on MissingPluginException catch (e) {
|
||||
FlutterSecureStorage(
|
||||
iOptions: iosOptions,
|
||||
).delete(key: _passwordStorageKey, iOptions: iosOptions).catchError((_) {});
|
||||
Logs().w('Database encryption is not supported on this platform', e);
|
||||
_sendNoEncryptionWarning(e);
|
||||
} catch (e, s) {
|
||||
FlutterSecureStorage(
|
||||
iOptions: iosOptions,
|
||||
).delete(key: _passwordStorageKey, iOptions: iosOptions).catchError((_) {});
|
||||
Logs().w('Unable to init database encryption', e, s);
|
||||
_sendNoEncryptionWarning(e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<void> _sendNoEncryptionWarning(Object exception) async {
|
||||
final isStored = AppSettings.noEncryptionWarningShown.value;
|
||||
|
||||
if (isStored == true) return;
|
||||
|
||||
final l10n = await lookupL10n(PlatformDispatcher.instance.locale);
|
||||
ClientManager.sendInitNotification(
|
||||
l10n.noDatabaseEncryption,
|
||||
exception.toString(),
|
||||
);
|
||||
|
||||
await AppSettings.noEncryptionWarningShown.setItem(true);
|
||||
}
|
||||
70
lib/utils/matrix_sdk_extensions/matrix_file_extension.dart
Normal file
70
lib/utils/matrix_sdk_extensions/matrix_file_extension.dart
Normal file
@@ -0,0 +1,70 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/size_string.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:share_plus/share_plus.dart';
|
||||
|
||||
extension MatrixFileExtension on MatrixFile {
|
||||
Future<void> save(BuildContext context) async {
|
||||
final scaffoldMessenger = ScaffoldMessenger.of(context);
|
||||
final l10n = L10n.of(context);
|
||||
final downloadPath = await FilePicker.saveFile(
|
||||
dialogTitle: l10n.saveFile,
|
||||
fileName: name,
|
||||
type: filePickerFileType,
|
||||
bytes: bytes,
|
||||
);
|
||||
if (downloadPath == null) return;
|
||||
|
||||
scaffoldMessenger.showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(l10n.fileHasBeenSavedAt(downloadPath.toString())),
|
||||
showCloseIcon: true,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
FileType get filePickerFileType {
|
||||
if (this is MatrixImageFile) return FileType.image;
|
||||
if (this is MatrixAudioFile) return FileType.audio;
|
||||
if (this is MatrixVideoFile) return FileType.video;
|
||||
return FileType.any;
|
||||
}
|
||||
|
||||
Future<void> share(BuildContext context) async {
|
||||
// Workaround for iPad from
|
||||
// https://github.com/fluttercommunity/plus_plugins/tree/main/packages/share_plus/share_plus#ipad
|
||||
final box = context.findRenderObject() as RenderBox?;
|
||||
|
||||
await SharePlus.instance.share(
|
||||
ShareParams(
|
||||
files: [XFile.fromData(bytes, name: name, mimeType: mimeType)],
|
||||
sharePositionOrigin: box == null
|
||||
? null
|
||||
: box.localToGlobal(Offset.zero) & box.size,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
MatrixFile get detectFileType {
|
||||
if (msgType == MessageTypes.Image) {
|
||||
return MatrixImageFile(bytes: bytes, name: name);
|
||||
}
|
||||
if (msgType == MessageTypes.Video) {
|
||||
return MatrixVideoFile(bytes: bytes, name: name);
|
||||
}
|
||||
if (msgType == MessageTypes.Audio) {
|
||||
return MatrixAudioFile(bytes: bytes, name: name);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
String get sizeString => size.sizeString;
|
||||
}
|
||||
382
lib/utils/matrix_sdk_extensions/matrix_locals.dart
Normal file
382
lib/utils/matrix_sdk_extensions/matrix_locals.dart
Normal file
@@ -0,0 +1,382 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
/// This is a temporary helper class until there is a proper solution to this with the new system
|
||||
class MatrixLocals extends MatrixLocalizations {
|
||||
final L10n l10n;
|
||||
|
||||
MatrixLocals(this.l10n);
|
||||
|
||||
@override
|
||||
String acceptedTheInvitation(String targetName) {
|
||||
return l10n.acceptedTheInvitation(targetName);
|
||||
}
|
||||
|
||||
@override
|
||||
String activatedEndToEndEncryption(String senderName) {
|
||||
return l10n.activatedEndToEndEncryption(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String answeredTheCall(String senderName) {
|
||||
return l10n.answeredTheCall(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String get anyoneCanJoin => l10n.anyoneCanJoin;
|
||||
|
||||
@override
|
||||
String bannedUser(String senderName, String targetName) {
|
||||
return l10n.bannedUser(senderName, targetName);
|
||||
}
|
||||
|
||||
@override
|
||||
String changedTheChatAvatar(String senderName) {
|
||||
return l10n.changedTheChatAvatar(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String changedTheChatDescriptionTo(String senderName, _) {
|
||||
return l10n.changedTheChatDescription(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String changedTheChatNameTo(String senderName, _) {
|
||||
return l10n.changedTheChatName(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String changedTheChatPermissions(String senderName) {
|
||||
return l10n.changedTheChatPermissions(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String changedTheDisplaynameTo(String targetName, String newDisplayname) {
|
||||
return l10n.changedTheDisplaynameTo(targetName, newDisplayname);
|
||||
}
|
||||
|
||||
@override
|
||||
String changedTheGuestAccessRules(String senderName) {
|
||||
return l10n.changedTheGuestAccessRules(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String changedTheGuestAccessRulesTo(
|
||||
String senderName,
|
||||
String localizedString,
|
||||
) {
|
||||
return l10n.changedTheGuestAccessRulesTo(senderName, localizedString);
|
||||
}
|
||||
|
||||
@override
|
||||
String changedTheHistoryVisibility(String senderName) {
|
||||
return l10n.changedTheHistoryVisibility(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String changedTheHistoryVisibilityTo(
|
||||
String senderName,
|
||||
String localizedString,
|
||||
) {
|
||||
return l10n.changedTheHistoryVisibilityTo(senderName, localizedString);
|
||||
}
|
||||
|
||||
@override
|
||||
String changedTheJoinRules(String senderName) {
|
||||
return l10n.changedTheJoinRules(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String changedTheJoinRulesTo(String senderName, String localizedString) {
|
||||
return l10n.changedTheJoinRulesTo(senderName, localizedString);
|
||||
}
|
||||
|
||||
@override
|
||||
String changedTheProfileAvatar(String targetName) {
|
||||
return l10n.changedTheProfileAvatar(targetName);
|
||||
}
|
||||
|
||||
@override
|
||||
String changedTheRoomAliases(String senderName) {
|
||||
return l10n.changedTheRoomAliases(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String changedTheRoomInvitationLink(String senderName) {
|
||||
return l10n.changedTheRoomInvitationLink(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String get channelCorruptedDecryptError => l10n.channelCorruptedDecryptError;
|
||||
|
||||
@override
|
||||
String couldNotDecryptMessage(String errorText) {
|
||||
return l10n.couldNotDecryptMessage(errorText);
|
||||
}
|
||||
|
||||
@override
|
||||
String createdTheChat(String senderName) {
|
||||
return l10n.createdTheChat(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String get emptyChat => l10n.emptyChat;
|
||||
|
||||
@override
|
||||
String get encryptionNotEnabled => l10n.encryptionNotEnabled;
|
||||
|
||||
@override
|
||||
String endedTheCall(String senderName) {
|
||||
return l10n.endedTheCall(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String get fromJoining => l10n.fromJoining;
|
||||
|
||||
@override
|
||||
String get fromTheInvitation => l10n.fromTheInvitation;
|
||||
|
||||
@override
|
||||
String groupWith(String displayname) {
|
||||
return l10n.groupWith(displayname);
|
||||
}
|
||||
|
||||
@override
|
||||
String get guestsAreForbidden => l10n.guestsAreForbidden;
|
||||
|
||||
@override
|
||||
String get guestsCanJoin => l10n.guestsCanJoin;
|
||||
|
||||
@override
|
||||
String hasWithdrawnTheInvitationFor(String senderName, String targetName) {
|
||||
return l10n.hasWithdrawnTheInvitationFor(senderName, targetName);
|
||||
}
|
||||
|
||||
@override
|
||||
String invitedUser(String senderName, String targetName) {
|
||||
return l10n.invitedUser(senderName, targetName);
|
||||
}
|
||||
|
||||
@override
|
||||
String get invitedUsersOnly => l10n.invitedUsersOnly;
|
||||
|
||||
@override
|
||||
String joinedTheChat(String targetName) {
|
||||
return l10n.joinedTheChat(targetName);
|
||||
}
|
||||
|
||||
@override
|
||||
String kicked(String senderName, String targetName) {
|
||||
return l10n.kicked(senderName, targetName);
|
||||
}
|
||||
|
||||
@override
|
||||
String kickedAndBanned(String senderName, String targetName) {
|
||||
return l10n.kickedAndBanned(senderName, targetName);
|
||||
}
|
||||
|
||||
@override
|
||||
String get needPantalaimonWarning => l10n.oopsSomethingWentWrong;
|
||||
|
||||
@override
|
||||
String get noPermission => l10n.noKeyForThisMessage;
|
||||
|
||||
@override
|
||||
String redactedAnEvent(Event redactedEvent) {
|
||||
return l10n.redactedAnEvent(
|
||||
redactedEvent.redactedBecause?.senderFromMemoryOrFallback
|
||||
.calcDisplayname() ??
|
||||
l10n.user,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String rejectedTheInvitation(String targetName) {
|
||||
return l10n.rejectedTheInvitation(targetName);
|
||||
}
|
||||
|
||||
@override
|
||||
String removedBy(Event redactedEvent) {
|
||||
return l10n.redactedBy(
|
||||
redactedEvent.senderFromMemoryOrFallback.calcDisplayname(),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String get roomHasBeenUpgraded => l10n.roomHasBeenUpgraded;
|
||||
|
||||
@override
|
||||
String sentAFile(String senderName) {
|
||||
return l10n.sentAFile(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String sentAPicture(String senderName) {
|
||||
return l10n.sentAPicture(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String sentASticker(String senderName) {
|
||||
return l10n.sentASticker(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String sentAVideo(String senderName) {
|
||||
return l10n.sentAVideo(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String sentAnAudio(String senderName) {
|
||||
return l10n.sentAnAudio(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String sentCallInformations(String senderName) {
|
||||
return l10n.sentCallInformations(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String sharedTheLocation(String senderName) {
|
||||
return l10n.sharedTheLocation(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String startedACall(String senderName) {
|
||||
return l10n.startedACall(senderName);
|
||||
}
|
||||
|
||||
@override
|
||||
String unbannedUser(String senderName, String targetName) {
|
||||
return l10n.unbannedUser(senderName, targetName);
|
||||
}
|
||||
|
||||
@override
|
||||
String get unknownEncryptionAlgorithm => l10n.unknownEncryptionAlgorithm;
|
||||
|
||||
@override
|
||||
String unknownEvent(String typeKey) {
|
||||
return l10n.userSentUnknownEvent('User', typeKey);
|
||||
}
|
||||
|
||||
@override
|
||||
String userLeftTheChat(String targetName) {
|
||||
return l10n.userLeftTheChat(targetName);
|
||||
}
|
||||
|
||||
@override
|
||||
String get visibleForAllParticipants => l10n.visibleForAllParticipants;
|
||||
|
||||
@override
|
||||
String get visibleForEveryone => l10n.visibleForEveryone;
|
||||
|
||||
@override
|
||||
String get you => l10n.you;
|
||||
|
||||
@override
|
||||
String sentReaction(String senderName, String reactionKey) =>
|
||||
l10n.reactedWith(senderName, reactionKey);
|
||||
|
||||
@override
|
||||
// TODO: implement youAcceptedTheInvitation
|
||||
String get youAcceptedTheInvitation => l10n.youAcceptedTheInvitation;
|
||||
|
||||
@override
|
||||
String youBannedUser(String targetName) => l10n.youBannedUser(targetName);
|
||||
|
||||
@override
|
||||
String youHaveWithdrawnTheInvitationFor(String targetName) =>
|
||||
l10n.youHaveWithdrawnTheInvitationFor(targetName);
|
||||
|
||||
@override
|
||||
String youInvitedBy(String senderName) => l10n.youInvitedBy(senderName);
|
||||
|
||||
@override
|
||||
String youInvitedUser(String targetName) => l10n.youInvitedUser(targetName);
|
||||
|
||||
@override
|
||||
// TODO: implement youJoinedTheChat
|
||||
String get youJoinedTheChat => l10n.youJoinedTheChat;
|
||||
|
||||
@override
|
||||
String youKicked(String targetName) => l10n.youKicked(targetName);
|
||||
|
||||
@override
|
||||
String youKickedAndBanned(String targetName) =>
|
||||
l10n.youKickedAndBanned(targetName);
|
||||
|
||||
@override
|
||||
// TODO: implement youRejectedTheInvitation
|
||||
String get youRejectedTheInvitation => l10n.youRejectedTheInvitation;
|
||||
|
||||
@override
|
||||
String youUnbannedUser(String targetName) => l10n.youUnbannedUser(targetName);
|
||||
|
||||
@override
|
||||
String wasDirectChatDisplayName(String oldDisplayName) =>
|
||||
l10n.wasDirectChatDisplayName(oldDisplayName);
|
||||
|
||||
@override
|
||||
String get unknownUser => l10n.user;
|
||||
|
||||
@override
|
||||
String hasKnocked(String targetName) => l10n.hasKnocked(targetName);
|
||||
|
||||
@override
|
||||
String acceptedKeyVerification(String senderName) =>
|
||||
l10n.acceptedKeyVerification(senderName);
|
||||
|
||||
@override
|
||||
String canceledKeyVerification(String senderName) =>
|
||||
l10n.canceledKeyVerification(senderName);
|
||||
|
||||
@override
|
||||
String completedKeyVerification(String senderName) =>
|
||||
l10n.completedKeyVerification(senderName);
|
||||
|
||||
@override
|
||||
String isReadyForKeyVerification(String senderName) =>
|
||||
l10n.isReadyForKeyVerification(senderName);
|
||||
|
||||
@override
|
||||
String requestedKeyVerification(String senderName) =>
|
||||
l10n.requestedKeyVerification(senderName);
|
||||
|
||||
@override
|
||||
String startedKeyVerification(String senderName) =>
|
||||
l10n.startedKeyVerification(senderName);
|
||||
|
||||
@override
|
||||
String invitedBy(String senderName) => senderName;
|
||||
|
||||
@override
|
||||
String get cancelledSend => l10n.sendCanceled;
|
||||
|
||||
@override
|
||||
String voiceMessage(
|
||||
String senderName,
|
||||
Duration? duration,
|
||||
) => l10n.sentVoiceMessage(
|
||||
senderName,
|
||||
duration == null
|
||||
? ''
|
||||
: '${duration.inMinutes.toString().padLeft(2, '0')}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}',
|
||||
);
|
||||
|
||||
@override
|
||||
String get refreshingLastEvent => l10n.loadingPleaseWait;
|
||||
|
||||
@override
|
||||
String startedAPoll(String senderName) => '$senderName started a poll';
|
||||
|
||||
@override
|
||||
String get pollHasBeenEnded => l10n.pollHasBeenEnded;
|
||||
|
||||
@override
|
||||
String incomingCallFrom(String senderName) =>
|
||||
l10n.incomingCallFrom(senderName);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
extension OidcSessionJsonExtension on OidcLoginSession {
|
||||
static const String storeKey = 'oidc_session';
|
||||
static const String homeserverStoreKey = 'oidc_stored_homeserver';
|
||||
Map<String, Object?> toJson() => {
|
||||
'oidc_client_data': oidcClientData.toJson(),
|
||||
'authentication_uri': authenticationUri.toString(),
|
||||
'redirect_uri': redirectUri.toString(),
|
||||
'code_verifier': codeVerifier,
|
||||
'state': state,
|
||||
};
|
||||
|
||||
static OidcLoginSession fromJson(Map<String, Object?> json) =>
|
||||
OidcLoginSession(
|
||||
oidcClientData: OidcClientData.fromJson(
|
||||
json['oidc_client_data'] as Map<String, Object?>,
|
||||
),
|
||||
authenticationUri: Uri.parse(json['authentication_uri'] as String),
|
||||
redirectUri: Uri.parse(json['redirect_uri'] as String),
|
||||
codeVerifier: json['code_verifier'] as String,
|
||||
state: json['state'] as String,
|
||||
);
|
||||
}
|
||||
58
lib/utils/notification_avatar_extension.dart
Normal file
58
lib/utils/notification_avatar_extension.dart
Normal file
@@ -0,0 +1,58 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:tatchat/utils/client_download_content_extension.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
|
||||
import 'matrix_sdk_extensions/flutter_matrix_dart_sdk_database/builder.dart';
|
||||
|
||||
const notificationAvatarDimension = 128;
|
||||
|
||||
extension NotificationAvatarExtension on Client {
|
||||
Future<Uint8List?> tryDownloadNotificationAvatar(Uri? avatar) async {
|
||||
if (avatar == null) return null;
|
||||
try {
|
||||
return await downloadMxcCached(
|
||||
avatar,
|
||||
thumbnailMethod: ThumbnailMethod.crop,
|
||||
width: notificationAvatarDimension,
|
||||
height: notificationAvatarDimension,
|
||||
animated: false,
|
||||
isThumbnail: true,
|
||||
rounded: true,
|
||||
).timeout(const Duration(seconds: 3));
|
||||
} catch (e, s) {
|
||||
Logs().e('Unable to get avatar picture', e, s);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep in sync with `createAttachment()` in iOS Notification Extension
|
||||
/// This loads the avatar for a room and also stores it in a temporary
|
||||
/// directory so the Notification Service Extension can access it later.
|
||||
Future<String?> getIosNotificationAvatar(Uri? roomAvatar) async {
|
||||
if (roomAvatar == null) return null;
|
||||
|
||||
final directory = await getFileStorageLocation();
|
||||
if (directory == null) return null;
|
||||
|
||||
final host = roomAvatar.host.replaceAll('.', '_');
|
||||
final rawPath = roomAvatar.pathSegments.join('_');
|
||||
final fileName = 'notification_${host}_$rawPath.jpg';
|
||||
final cachedFile = File(path.join(directory.path, fileName));
|
||||
|
||||
if (!await cachedFile.exists()) {
|
||||
final bytes = await tryDownloadNotificationAvatar(roomAvatar);
|
||||
if (bytes == null) return null;
|
||||
await cachedFile.writeAsBytes(bytes);
|
||||
}
|
||||
|
||||
return cachedFile.path;
|
||||
}
|
||||
}
|
||||
214
lib/utils/notification_background_handler.dart
Normal file
214
lib/utils/notification_background_handler.dart
Normal file
@@ -0,0 +1,214 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:isolate';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/client_manager.dart';
|
||||
import 'package:tatchat/utils/push_helper.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:flutter_vodozemac/flutter_vodozemac.dart' as vod;
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../config/app_config.dart';
|
||||
import '../config/setting_keys.dart';
|
||||
|
||||
bool _vodInitialized = false;
|
||||
|
||||
extension NotificationResponseJson on NotificationResponse {
|
||||
String toJsonString() => jsonEncode({
|
||||
'type': notificationResponseType.name,
|
||||
'id': id,
|
||||
'actionId': actionId,
|
||||
'input': input,
|
||||
'payload': payload,
|
||||
'data': data,
|
||||
});
|
||||
|
||||
static NotificationResponse fromJsonString(String jsonString) {
|
||||
final json = jsonDecode(jsonString) as Map<String, Object?>;
|
||||
return NotificationResponse(
|
||||
notificationResponseType: NotificationResponseType.values.singleWhere(
|
||||
(t) => t.name == json['type'],
|
||||
),
|
||||
id: json['id'] as int?,
|
||||
actionId: json['actionId'] as String?,
|
||||
input: json['input'] as String?,
|
||||
payload: json['payload'] as String?,
|
||||
data: json['data'] as Map<String, dynamic>,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> waitForPushIsolateDone() async {
|
||||
if (IsolateNameServer.lookupPortByName(AppConfig.pushIsolatePortName) !=
|
||||
null) {
|
||||
Logs().i('Wait for Push Isolate to be done...');
|
||||
await Future.delayed(const Duration(milliseconds: 300));
|
||||
}
|
||||
}
|
||||
|
||||
@pragma('vm:entry-point')
|
||||
Future<void> notificationTapBackground(
|
||||
NotificationResponse notificationResponse,
|
||||
) async {
|
||||
final sendPort = IsolateNameServer.lookupPortByName(
|
||||
AppConfig.mainIsolatePortName,
|
||||
);
|
||||
if (sendPort != null) {
|
||||
sendPort.send(notificationResponse.toJsonString());
|
||||
Logs().i('Notification tap sent to main isolate!');
|
||||
return;
|
||||
}
|
||||
Logs().i(
|
||||
'Main isolate no up - Create temporary client for notification tap intend!',
|
||||
);
|
||||
|
||||
final pushIsolateReceivePort = ReceivePort();
|
||||
IsolateNameServer.registerPortWithName(
|
||||
pushIsolateReceivePort.sendPort,
|
||||
AppConfig.pushIsolatePortName,
|
||||
);
|
||||
|
||||
if (!_vodInitialized) {
|
||||
await vod.init();
|
||||
_vodInitialized = true;
|
||||
}
|
||||
final store = await AppSettings.init();
|
||||
|
||||
final payload = FluffyChatPushPayload.fromString(
|
||||
notificationResponse.payload ?? '',
|
||||
);
|
||||
final clientName = payload.clientName;
|
||||
final client = clientName == null
|
||||
? (await ClientManager.getClients(store: store, initialize: false)).first
|
||||
: (await ClientManager.createClient(clientName, store));
|
||||
await client.abortSync();
|
||||
await client.init(
|
||||
waitForFirstSync: false,
|
||||
waitUntilLoadCompletedLoaded: false,
|
||||
);
|
||||
|
||||
if (!client.isLogged()) {
|
||||
throw Exception('Notification tab in background but not logged in!');
|
||||
}
|
||||
try {
|
||||
await notificationTap(notificationResponse, clients: [client]);
|
||||
} finally {
|
||||
await client.dispose(closeDatabase: false);
|
||||
pushIsolateReceivePort.sendPort.send('DONE');
|
||||
IsolateNameServer.removePortNameMapping(AppConfig.pushIsolatePortName);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
Future<void> notificationTap(
|
||||
NotificationResponse notificationResponse, {
|
||||
GoRouter? router,
|
||||
required List<Client> clients,
|
||||
L10n? l10n,
|
||||
}) async {
|
||||
Logs().d(
|
||||
'Notification action handler started',
|
||||
notificationResponse.notificationResponseType.name,
|
||||
);
|
||||
final payload = FluffyChatPushPayload.fromString(
|
||||
notificationResponse.payload ?? '',
|
||||
);
|
||||
final client =
|
||||
clients.firstWhereOrNull(
|
||||
(client) => client.clientName == payload.clientName,
|
||||
) ??
|
||||
clients.first;
|
||||
|
||||
updateSummaryNotification(
|
||||
flutterLocalNotificationsPlugin: FlutterLocalNotificationsPlugin(),
|
||||
clientName: client.clientName,
|
||||
l10n: await lookupL10n(PlatformDispatcher.instance.locale),
|
||||
);
|
||||
|
||||
switch (notificationResponse.notificationResponseType) {
|
||||
case NotificationResponseType.selectedNotification:
|
||||
final roomId = payload.roomId;
|
||||
if (roomId == null) return;
|
||||
|
||||
if (router == null) {
|
||||
Logs().v('Ignore select notification action in background mode');
|
||||
return;
|
||||
}
|
||||
Logs().v('Open room from notification tap', roomId);
|
||||
await client.roomsLoading;
|
||||
await client.accountDataLoading;
|
||||
if (client.getRoomById(roomId) == null) {
|
||||
await client
|
||||
.waitForRoomInSync(roomId)
|
||||
.timeout(const Duration(seconds: 30));
|
||||
}
|
||||
router.go(
|
||||
client.getRoomById(roomId)?.membership == Membership.invite
|
||||
? '/rooms?client=${client.clientName}'
|
||||
: '/rooms/$roomId?client=${client.clientName}',
|
||||
);
|
||||
case NotificationResponseType.selectedNotificationAction:
|
||||
final actionType = FluffyChatNotificationActions.values.singleWhereOrNull(
|
||||
(action) => action.name == notificationResponse.actionId,
|
||||
);
|
||||
if (actionType == null) {
|
||||
throw Exception('Selected notification with action but no action ID');
|
||||
}
|
||||
final roomId = payload.roomId;
|
||||
if (roomId == null) {
|
||||
throw Exception('Selected notification with action but no payload');
|
||||
}
|
||||
await client.roomsLoading;
|
||||
await client.accountDataLoading;
|
||||
await client.userDeviceKeysLoading;
|
||||
final room = client.getRoomById(roomId);
|
||||
if (room == null) {
|
||||
throw Exception(
|
||||
'Selected notification with action but unknown room $roomId',
|
||||
);
|
||||
}
|
||||
switch (actionType) {
|
||||
case FluffyChatNotificationActions.markAsRead:
|
||||
await room.setReadMarker(
|
||||
payload.eventId ?? room.lastEvent!.eventId,
|
||||
mRead: payload.eventId ?? room.lastEvent!.eventId,
|
||||
public: AppSettings.sendPublicReadReceipts.value,
|
||||
);
|
||||
case FluffyChatNotificationActions.reply:
|
||||
final input = notificationResponse.input;
|
||||
if (input == null || input.isEmpty) {
|
||||
throw Exception(
|
||||
'Selected notification with reply action but without input',
|
||||
);
|
||||
}
|
||||
|
||||
await room.sendTextEvent(
|
||||
input,
|
||||
parseCommands: false,
|
||||
displayPendingEvent: false,
|
||||
);
|
||||
case FluffyChatNotificationActions.mute:
|
||||
await room.setPushRuleState(PushRuleState.mentionsOnly);
|
||||
case FluffyChatNotificationActions.open:
|
||||
router?.go(
|
||||
client.getRoomById(roomId)?.membership == Membership.invite
|
||||
? '/rooms?client=${client.clientName}'
|
||||
: '/rooms/$roomId?client=${client.clientName}',
|
||||
);
|
||||
case FluffyChatNotificationActions.enterCall:
|
||||
router?.go('/rooms/$roomId?client=${client.clientName}&action=call');
|
||||
}
|
||||
case NotificationResponseType.notificationDismissed:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
enum FluffyChatNotificationActions { markAsRead, reply, mute, open, enterCall }
|
||||
26
lib/utils/other_party_can_receive.dart
Normal file
26
lib/utils/other_party_can_receive.dart
Normal file
@@ -0,0 +1,26 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
extension OtherPartyCanReceiveExtension on Room {
|
||||
bool get otherPartyCanReceiveMessages {
|
||||
if (!encrypted) return true;
|
||||
final users = getParticipants()
|
||||
.map((u) => u.id)
|
||||
.where((userId) => userId != client.userID)
|
||||
.toSet();
|
||||
if (users.isEmpty) return true;
|
||||
|
||||
for (final userId in users) {
|
||||
if (client.userDeviceKeys[userId]?.deviceKeys.values.isNotEmpty == true) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class OtherPartyCanNotReceiveMessages implements Exception {}
|
||||
108
lib/utils/platform_infos.dart
Normal file
108
lib/utils/platform_infos.dart
Normal file
@@ -0,0 +1,108 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:url_launcher/url_launcher_string.dart';
|
||||
|
||||
import '../config/app_config.dart';
|
||||
|
||||
abstract class PlatformInfos {
|
||||
static bool get isWeb => kIsWeb;
|
||||
static bool get isLinux => !kIsWeb && Platform.isLinux;
|
||||
static bool get isWindows => !kIsWeb && Platform.isWindows;
|
||||
static bool get isMacOS => !kIsWeb && Platform.isMacOS;
|
||||
static bool get isIOS => !kIsWeb && Platform.isIOS;
|
||||
static bool get isAndroid => !kIsWeb && Platform.isAndroid;
|
||||
|
||||
static bool get isCupertinoStyle => isIOS || isMacOS;
|
||||
|
||||
static bool get isMobile => isAndroid || isIOS;
|
||||
|
||||
/// For desktops which don't support ChachedNetworkImage yet
|
||||
static bool get isBetaDesktop => isWindows || isLinux;
|
||||
|
||||
static bool get isDesktop => isLinux || isWindows || isMacOS;
|
||||
|
||||
static bool get usesTouchscreen => !isMobile;
|
||||
|
||||
static bool get supportsVideoPlayer =>
|
||||
!PlatformInfos.isWindows && !PlatformInfos.isLinux;
|
||||
|
||||
static bool get supportsCustomImageResizer =>
|
||||
PlatformInfos.isWeb || PlatformInfos.isMobile;
|
||||
|
||||
/// Web could also record in theory but currently creates broken opus
|
||||
static bool get platformCanRecord => (isMobile || isMacOS);
|
||||
|
||||
static bool get supportsAppLock => (isMobile || isMacOS);
|
||||
|
||||
static String get appDisplayName =>
|
||||
'${AppSettings.applicationName.value} ${isWeb ? 'web' : Platform.operatingSystem}${kReleaseMode ? '' : 'Debug'}';
|
||||
|
||||
static Future<String> getVersion() async {
|
||||
var version = kIsWeb ? 'Web' : 'Unknown';
|
||||
try {
|
||||
version = (await PackageInfo.fromPlatform()).version;
|
||||
} catch (_) {}
|
||||
return version;
|
||||
}
|
||||
|
||||
static Future<void> showDialog(BuildContext context) async {
|
||||
final l10n = L10n.of(context);
|
||||
final version = await PlatformInfos.getVersion();
|
||||
if (!context.mounted) return;
|
||||
showAboutDialog(
|
||||
context: context,
|
||||
children: [
|
||||
Text(l10n.versionWithNumber(version)),
|
||||
TextButton.icon(
|
||||
onPressed: () => launchUrlString(AppConfig.sourceCodeUrl),
|
||||
icon: const Icon(Icons.source_outlined),
|
||||
label: Text(l10n.sourceCode),
|
||||
),
|
||||
Builder(
|
||||
builder: (innerContext) {
|
||||
return TextButton.icon(
|
||||
onPressed: () {
|
||||
context.go('/logs');
|
||||
Navigator.of(innerContext).pop();
|
||||
},
|
||||
icon: const Icon(Icons.list_outlined),
|
||||
label: Text(l10n.logs),
|
||||
);
|
||||
},
|
||||
),
|
||||
Builder(
|
||||
builder: (innerContext) {
|
||||
return TextButton.icon(
|
||||
onPressed: () {
|
||||
context.go('/configs');
|
||||
Navigator.of(innerContext).pop();
|
||||
},
|
||||
icon: const Icon(Icons.settings_applications_outlined),
|
||||
label: Text(l10n.advancedConfigs),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
applicationIcon: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(64),
|
||||
child: Image.asset(
|
||||
'./assets/logo/mini/logo_mini.png',
|
||||
width: 64,
|
||||
height: 64,
|
||||
),
|
||||
),
|
||||
applicationName: AppSettings.applicationName.value,
|
||||
);
|
||||
}
|
||||
}
|
||||
25
lib/utils/position_from_build_context.dart
Normal file
25
lib/utils/position_from_build_context.dart
Normal file
@@ -0,0 +1,25 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
extension PositionFromBuildContext on BuildContext {
|
||||
RelativeRect get position {
|
||||
final overlay = Overlay.of(this).context.findRenderObject() as RenderBox;
|
||||
|
||||
final button = findRenderObject() as RenderBox;
|
||||
|
||||
return RelativeRect.fromRect(
|
||||
Rect.fromPoints(
|
||||
button.localToGlobal(const Offset(0, -65), ancestor: overlay),
|
||||
button.localToGlobal(
|
||||
button.size.bottomRight(Offset.zero) + const Offset(-50, 0),
|
||||
ancestor: overlay,
|
||||
),
|
||||
),
|
||||
Offset.zero & overlay.size,
|
||||
);
|
||||
}
|
||||
}
|
||||
547
lib/utils/push_helper.dart
Normal file
547
lib/utils/push_helper.dart
Normal file
@@ -0,0 +1,547 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/call_kit_params.dart';
|
||||
import 'package:tatchat/utils/client_manager.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/matrix_live_kit_call.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/matrix_locals.dart';
|
||||
import 'package:tatchat/utils/notification_avatar_extension.dart';
|
||||
import 'package:tatchat/utils/notification_background_handler.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/utils/start_push_foreground_service.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_callkit_incoming/flutter_callkit_incoming.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:flutter_new_badger/flutter_new_badger.dart';
|
||||
import 'package:flutter_shortcuts_new/flutter_shortcuts_new.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart' hide Result;
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
final Map<String, DateTime> lastReceivedPushNotification = {};
|
||||
|
||||
Future<void> pushHelper(
|
||||
PushNotification notification, {
|
||||
List<Client>? clients,
|
||||
L10n? l10n,
|
||||
String? activeRoomId,
|
||||
required FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin,
|
||||
}) async {
|
||||
l10n ??= await lookupL10n(PlatformDispatcher.instance.locale);
|
||||
|
||||
try {
|
||||
await _tryPushHelper(
|
||||
notification,
|
||||
clients: clients,
|
||||
l10n: l10n,
|
||||
activeRoomId: activeRoomId,
|
||||
flutterLocalNotificationsPlugin: flutterLocalNotificationsPlugin,
|
||||
).timeout(const Duration(seconds: 30));
|
||||
} catch (e, s) {
|
||||
if (PlatformInfos.isAndroid &&
|
||||
e is! TimeoutException &&
|
||||
e is! IOException &&
|
||||
e is! http.ClientException) {
|
||||
Logs().e('Push Helper has crashed! Writing into temporary file...', e, s);
|
||||
final store = await SharedPreferences.getInstance();
|
||||
await store.setStringList(AppConfig.pushHelperCrashReportKey, [
|
||||
e.toString(),
|
||||
s.toString(),
|
||||
]);
|
||||
}
|
||||
|
||||
if (notification.roomId != null) {
|
||||
await flutterLocalNotificationsPlugin.show(
|
||||
id: notification.notificationId,
|
||||
title: l10n.newMessageInFluffyChat,
|
||||
body: l10n.openAppToReadMessages,
|
||||
notificationDetails: NotificationDetails(
|
||||
iOS: DarwinNotificationDetails(
|
||||
threadIdentifier:
|
||||
'${notification.clientName}_${notification.roomId}',
|
||||
),
|
||||
android: AndroidNotificationDetails(
|
||||
AppConfig.pushNotificationsChannelId,
|
||||
l10n.incomingMessages,
|
||||
number: notification.counts?.unread,
|
||||
ticker: l10n.unreadChatsInApp(
|
||||
AppSettings.applicationName.value,
|
||||
(notification.counts?.unread ?? 0).toString(),
|
||||
),
|
||||
importance: Importance.high,
|
||||
priority: Priority.max,
|
||||
shortcutId: notification.roomId,
|
||||
category: AndroidNotificationCategory.message,
|
||||
groupKey: notification.clientName,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
rethrow;
|
||||
} finally {
|
||||
ForegroundServices.stopService('background_push');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _tryPushHelper(
|
||||
PushNotification notification, {
|
||||
List<Client>? clients,
|
||||
L10n? l10n,
|
||||
String? activeRoomId,
|
||||
required FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin,
|
||||
}) async {
|
||||
final isBackgroundMessage = clients == null;
|
||||
Logs().v(
|
||||
'Push helper has been started (background=$isBackgroundMessage).',
|
||||
notification.toJson(),
|
||||
);
|
||||
|
||||
final clientName = notification.clientName;
|
||||
final store = await AppSettings.init();
|
||||
|
||||
final client = clientName == null
|
||||
? (clients?.first ??
|
||||
(await ClientManager.getClients(
|
||||
initialize: false,
|
||||
store: store,
|
||||
)).first)
|
||||
: (clients?.firstWhereOrNull(
|
||||
(client) => client.clientName == clientName,
|
||||
) ??
|
||||
await ClientManager.createClient(clientName, store));
|
||||
|
||||
lastReceivedPushNotification[client.clientName] = DateTime.now();
|
||||
|
||||
l10n ??= await L10n.delegate.load(PlatformDispatcher.instance.locale);
|
||||
|
||||
Logs().v('Load event...');
|
||||
final event = await client.getEventByPushNotification(
|
||||
notification,
|
||||
storeInDatabase: false,
|
||||
);
|
||||
|
||||
updateAppBadge(notification.counts?.unread ?? 0);
|
||||
|
||||
if (event == null) {
|
||||
Logs().v('Notification is a clearing indicator.');
|
||||
if (clients?.length == 1 && (notification.counts?.unread == 0)) {
|
||||
await flutterLocalNotificationsPlugin.cancelAll();
|
||||
} else {
|
||||
// Make sure client is fully loaded and synced before dismiss notifications:
|
||||
await client.roomsLoading;
|
||||
await client
|
||||
.oneShotSync()
|
||||
.timeout(const Duration(seconds: 8))
|
||||
.catchError((_) => null);
|
||||
|
||||
final activeNotifications = await flutterLocalNotificationsPlugin
|
||||
.getActiveNotifications();
|
||||
activeNotifications.removeWhere(
|
||||
(notification) => notification.groupKey != client.clientName,
|
||||
);
|
||||
var needsUpdateForSummaryNotification = false;
|
||||
for (final activeNotification in activeNotifications) {
|
||||
final room = client.rooms.singleWhereOrNull(
|
||||
(room) =>
|
||||
'${client.clientName}_${room.id}'.hashCode ==
|
||||
activeNotification.id,
|
||||
);
|
||||
if (room != null && !room.isUnreadOrInvited) {
|
||||
flutterLocalNotificationsPlugin.cancel(id: activeNotification.id!);
|
||||
if (PlatformInfos.isAndroid) needsUpdateForSummaryNotification = true;
|
||||
}
|
||||
}
|
||||
if (needsUpdateForSummaryNotification) {
|
||||
await updateSummaryNotification(
|
||||
clientName: client.clientName,
|
||||
l10n: l10n,
|
||||
flutterLocalNotificationsPlugin: flutterLocalNotificationsPlugin,
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
Logs().v('Push helper got notification event of type ${event.type}.');
|
||||
|
||||
if (!client.pushruleEvaluator.match(event).notify) {
|
||||
Logs().i('Push helper: filtered by client-side push rules.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type == RtcNotificationContent.eventType &&
|
||||
event.tryParseRtcNotificationContent()?.notificationType == .ring &&
|
||||
PlatformInfos.isMobile) {
|
||||
_showIncomingCall(event, l10n);
|
||||
return;
|
||||
}
|
||||
|
||||
if (notification.roomId != null &&
|
||||
activeRoomId == notification.roomId &&
|
||||
WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed) {
|
||||
Logs().v('Room is in foreground. Stop push helper here.');
|
||||
return;
|
||||
}
|
||||
|
||||
final matrixLocals = MatrixLocals(l10n);
|
||||
|
||||
// Calculate the body
|
||||
final body = event.type == EventTypes.Encrypted
|
||||
? l10n.newMessageInFluffyChat
|
||||
: await event.calcLocalizedBody(
|
||||
matrixLocals,
|
||||
plaintextBody: true,
|
||||
withSenderNamePrefix: false,
|
||||
hideReply: true,
|
||||
hideEdit: true,
|
||||
removeMarkdown: true,
|
||||
);
|
||||
|
||||
// The person object for the android message style notification
|
||||
final avatar = event.room.avatar;
|
||||
final senderAvatar = event.room.isDirectChat
|
||||
? avatar
|
||||
: event.senderFromMemoryOrFallback.avatarUrl;
|
||||
|
||||
final ownUser = event.room.unsafeGetUserFromMemoryOrFallback(client.userID!);
|
||||
|
||||
final userAvatarFile = await client.tryDownloadNotificationAvatar(
|
||||
ownUser.avatarUrl,
|
||||
);
|
||||
final roomAvatarFile = await client.tryDownloadNotificationAvatar(avatar);
|
||||
final senderAvatarFile = await client.tryDownloadNotificationAvatar(
|
||||
senderAvatar,
|
||||
);
|
||||
|
||||
final id = '${client.clientName}_${notification.roomId}'.hashCode;
|
||||
|
||||
final senderName = event.senderFromMemoryOrFallback.calcDisplayname();
|
||||
// Show notification
|
||||
|
||||
final newMessage = Message(
|
||||
body,
|
||||
event.originServerTs,
|
||||
Person(
|
||||
bot: event.messageType == MessageTypes.Notice,
|
||||
key: event.senderId,
|
||||
name: senderName,
|
||||
icon: senderAvatarFile == null
|
||||
? null
|
||||
: ByteArrayAndroidIcon(senderAvatarFile),
|
||||
),
|
||||
);
|
||||
|
||||
final messagingStyleInformation = PlatformInfos.isAndroid
|
||||
? await AndroidFlutterLocalNotificationsPlugin()
|
||||
.getActiveNotificationMessagingStyle(id: id)
|
||||
: null;
|
||||
messagingStyleInformation?.messages?.add(newMessage);
|
||||
|
||||
final roomName = event.room.getLocalizedDisplayname(MatrixLocals(l10n));
|
||||
|
||||
final notificationGroupId = event.room.isDirectChat
|
||||
? 'directChats'
|
||||
: 'groupChats';
|
||||
final groupName = event.room.isDirectChat ? l10n.directChats : l10n.groups;
|
||||
|
||||
final messageRooms = AndroidNotificationChannelGroup(
|
||||
notificationGroupId,
|
||||
groupName,
|
||||
);
|
||||
final roomsChannel = AndroidNotificationChannel(
|
||||
event.room.id,
|
||||
roomName,
|
||||
groupId: notificationGroupId,
|
||||
);
|
||||
|
||||
await flutterLocalNotificationsPlugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
AndroidFlutterLocalNotificationsPlugin
|
||||
>()
|
||||
?.createNotificationChannelGroup(messageRooms);
|
||||
await flutterLocalNotificationsPlugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
AndroidFlutterLocalNotificationsPlugin
|
||||
>()
|
||||
?.createNotificationChannel(roomsChannel);
|
||||
|
||||
final androidPlatformChannelSpecifics = AndroidNotificationDetails(
|
||||
AppConfig.pushNotificationsChannelId,
|
||||
l10n.incomingMessages,
|
||||
number: notification.counts?.unread,
|
||||
category: AndroidNotificationCategory.message,
|
||||
shortcutId: event.room.id,
|
||||
styleInformation:
|
||||
messagingStyleInformation ??
|
||||
MessagingStyleInformation(
|
||||
Person(
|
||||
name: ownUser.calcDisplayname(),
|
||||
icon: userAvatarFile == null
|
||||
? null
|
||||
: ByteArrayAndroidIcon(userAvatarFile),
|
||||
key: event.room.client.userID,
|
||||
),
|
||||
conversationTitle: event.room.isDirectChat ? null : roomName,
|
||||
groupConversation: !event.room.isDirectChat,
|
||||
messages: [newMessage],
|
||||
),
|
||||
ticker: event.calcLocalizedBodyFallback(
|
||||
matrixLocals,
|
||||
plaintextBody: true,
|
||||
withSenderNamePrefix: !event.room.isDirectChat,
|
||||
hideReply: true,
|
||||
hideEdit: true,
|
||||
removeMarkdown: true,
|
||||
),
|
||||
importance: Importance.high,
|
||||
priority: Priority.max,
|
||||
groupKey: client.clientName,
|
||||
actions: switch (event.type) {
|
||||
EventTypes.Message ||
|
||||
EventTypes.Encrypted ||
|
||||
EventTypes.Sticker => <AndroidNotificationAction>[
|
||||
AndroidNotificationAction(
|
||||
FluffyChatNotificationActions.reply.name,
|
||||
l10n.reply,
|
||||
inputs: [AndroidNotificationActionInput(label: l10n.writeAMessage)],
|
||||
allowGeneratedReplies: true,
|
||||
semanticAction: SemanticAction.reply,
|
||||
),
|
||||
AndroidNotificationAction(
|
||||
FluffyChatNotificationActions.markAsRead.name,
|
||||
l10n.markAsRead,
|
||||
semanticAction: SemanticAction.markAsRead,
|
||||
),
|
||||
AndroidNotificationAction(
|
||||
FluffyChatNotificationActions.mute.name,
|
||||
l10n.mute,
|
||||
semanticAction: SemanticAction.mute,
|
||||
),
|
||||
],
|
||||
RtcNotificationContent.eventType => [
|
||||
AndroidNotificationAction(
|
||||
FluffyChatNotificationActions.enterCall.name,
|
||||
l10n.enterCall,
|
||||
semanticAction: SemanticAction.call,
|
||||
),
|
||||
],
|
||||
_ => null,
|
||||
},
|
||||
);
|
||||
final iOSAttachmentPath = PlatformInfos.isIOS
|
||||
? await client.getIosNotificationAvatar(event.room.avatar)
|
||||
: null;
|
||||
final iOSPlatformChannelSpecifics = DarwinNotificationDetails(
|
||||
threadIdentifier: '${notification.clientName}_${notification.roomId}',
|
||||
attachments: iOSAttachmentPath == null
|
||||
? null
|
||||
: [
|
||||
DarwinNotificationAttachment(
|
||||
iOSAttachmentPath,
|
||||
identifier: 'image',
|
||||
),
|
||||
],
|
||||
);
|
||||
final platformChannelSpecifics = NotificationDetails(
|
||||
android: androidPlatformChannelSpecifics,
|
||||
iOS: iOSPlatformChannelSpecifics,
|
||||
);
|
||||
|
||||
final title = event.room.getLocalizedDisplayname(MatrixLocals(l10n));
|
||||
|
||||
if (PlatformInfos.isAndroid && messagingStyleInformation == null) {
|
||||
await _setShortcut(event, l10n, title, roomAvatarFile);
|
||||
}
|
||||
|
||||
final needsTitleAndBody = !PlatformInfos.isAndroid;
|
||||
|
||||
await flutterLocalNotificationsPlugin.show(
|
||||
id: notification.notificationId,
|
||||
title: needsTitleAndBody ? title : null,
|
||||
body: needsTitleAndBody ? body : null,
|
||||
notificationDetails: platformChannelSpecifics,
|
||||
payload: FluffyChatPushPayload(
|
||||
client.clientName,
|
||||
event.room.id,
|
||||
event.eventId,
|
||||
).toString(),
|
||||
);
|
||||
|
||||
// Send summary notification on Android
|
||||
if (PlatformInfos.isAndroid) {
|
||||
await updateSummaryNotification(
|
||||
clientName: client.clientName,
|
||||
l10n: l10n,
|
||||
flutterLocalNotificationsPlugin: flutterLocalNotificationsPlugin,
|
||||
);
|
||||
}
|
||||
Logs().v('Push helper has been completed!');
|
||||
}
|
||||
|
||||
void updateAppBadge(int unreadCount) {
|
||||
if (PlatformInfos.isAndroid || PlatformInfos.isMacOS || PlatformInfos.isIOS) {
|
||||
if (unreadCount == 0) {
|
||||
FlutterNewBadger.removeBadge();
|
||||
} else {
|
||||
FlutterNewBadger.setBadge(unreadCount);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateSummaryNotification({
|
||||
required FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin,
|
||||
required String clientName,
|
||||
required L10n l10n,
|
||||
}) async {
|
||||
final activeNotifications =
|
||||
(await flutterLocalNotificationsPlugin.getActiveNotifications())
|
||||
.where((n) => n.groupKey == clientName)
|
||||
.toList();
|
||||
|
||||
if (activeNotifications.length <= 1) {
|
||||
await flutterLocalNotificationsPlugin.cancel(id: clientName.hashCode);
|
||||
return;
|
||||
}
|
||||
|
||||
if (activeNotifications.any(
|
||||
(notification) => notification.id == clientName.hashCode,
|
||||
)) {
|
||||
// Already have a visible summary notification!
|
||||
return;
|
||||
}
|
||||
|
||||
await flutterLocalNotificationsPlugin.show(
|
||||
id: clientName.hashCode,
|
||||
notificationDetails: NotificationDetails(
|
||||
android: AndroidNotificationDetails(
|
||||
AppConfig.pushNotificationsChannelId,
|
||||
l10n.incomingMessages,
|
||||
groupKey: clientName,
|
||||
setAsGroupSummary: true,
|
||||
styleInformation: InboxStyleInformation(
|
||||
activeNotifications.map((n) => n.body ?? '').toList(),
|
||||
),
|
||||
autoCancel: false,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class FluffyChatPushPayload {
|
||||
final String? clientName, roomId, eventId;
|
||||
|
||||
FluffyChatPushPayload(this.clientName, this.roomId, this.eventId);
|
||||
|
||||
factory FluffyChatPushPayload.fromString(String payload) {
|
||||
final parts = payload.split('|');
|
||||
if (parts.length != 3) {
|
||||
return FluffyChatPushPayload(null, null, null);
|
||||
}
|
||||
return FluffyChatPushPayload(parts.first, parts[1], parts[2]);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() => '$clientName|$roomId|$eventId';
|
||||
}
|
||||
|
||||
/// Creates a shortcut for Android platform but does not block displaying the
|
||||
/// notification. This is optional but provides a nicer view of the
|
||||
/// notification popup.
|
||||
Future<void> _setShortcut(
|
||||
Event event,
|
||||
L10n l10n,
|
||||
String title,
|
||||
Uint8List? avatarFile,
|
||||
) async {
|
||||
final flutterShortcuts = FlutterShortcuts();
|
||||
await flutterShortcuts.initialize(debug: !kReleaseMode);
|
||||
await flutterShortcuts.pushShortcutItem(
|
||||
shortcut: ShortcutItem(
|
||||
id: event.room.id,
|
||||
action: AppConfig.inviteLinkPrefix + event.room.id,
|
||||
shortLabel: title,
|
||||
conversationShortcut: true,
|
||||
icon: avatarFile == null ? null : base64Encode(avatarFile),
|
||||
shortcutIconAsset: avatarFile == null
|
||||
? ShortcutIconAsset.androidAsset
|
||||
: ShortcutIconAsset.memoryAsset,
|
||||
isImportant: event.room.isFavourite,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
extension on PushNotification {
|
||||
String? get clientName =>
|
||||
devices?.firstOrNull?.data?.tryGet<String>('client_name');
|
||||
int get notificationId {
|
||||
final roomId = this.roomId;
|
||||
if (roomId == null) return 0;
|
||||
final clientName = this.clientName;
|
||||
if (clientName == null) return roomId.hashCode;
|
||||
return '${clientName}_$roomId'.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showIncomingCall(Event event, L10n l10n) async {
|
||||
final callId = '${event.room.id}|${event.room.client.clientName}';
|
||||
final activeCalls = await FlutterCallkitIncoming.activeCalls();
|
||||
if (activeCalls.any((call) => call.id == callId)) {
|
||||
Logs().d(
|
||||
'Call with this ID is already active. Ignoring this Push Notification...',
|
||||
callId,
|
||||
);
|
||||
return;
|
||||
}
|
||||
final intentStr = event.content.tryGet<String>('m.call.intent');
|
||||
final intent =
|
||||
MatrixRtcCallIntent.values.singleWhereOrNull(
|
||||
(i) => i.name == intentStr,
|
||||
) ??
|
||||
.video;
|
||||
final timeout =
|
||||
event.tryParseRtcNotificationContent()?.lifetime ??
|
||||
RtcNotificationContent.defaultLifetime;
|
||||
final params = await buildFluffyChatCallKitParams(
|
||||
event.room,
|
||||
l10n: l10n,
|
||||
intent: intent,
|
||||
timeout: timeout,
|
||||
);
|
||||
final timeoutDateTime = DateTime.now().add(timeout);
|
||||
await FlutterCallkitIncoming.showCallkitIncoming(params);
|
||||
|
||||
while (DateTime.now().isBefore(timeoutDateTime)) {
|
||||
await event.room.client.oneShotSync();
|
||||
if (!event.room.hasActiveMatrixRtcCall) {
|
||||
Logs().i('The other party has ended the call');
|
||||
await FlutterCallkitIncoming.endCall(params.id);
|
||||
break;
|
||||
}
|
||||
if (event.room.ownMatrixRtcMembership != null) {
|
||||
Logs().d('User has joined the call.');
|
||||
break;
|
||||
}
|
||||
if (event.room.getActiveMatrixRtcMembers().any(
|
||||
(member) =>
|
||||
member.senderId == event.room.client.userID! &&
|
||||
member.deviceId != event.room.client.deviceID!,
|
||||
)) {
|
||||
Logs().i('User has accepted the call on a different device');
|
||||
await FlutterCallkitIncoming.endCall(params.id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
65
lib/utils/resize_video.dart
Normal file
65
lib/utils/resize_video.dart
Normal file
@@ -0,0 +1,65 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:cross_file/cross_file.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:light_compressor_v2/light_compressor_v2.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:mime/mime.dart';
|
||||
|
||||
extension ResizeImage on XFile {
|
||||
Future<MatrixVideoFile> getVideoInfo({bool compress = true}) async {
|
||||
MediaInfo? mediaInfo;
|
||||
String? destinationPath;
|
||||
try {
|
||||
if (PlatformInfos.isMobile || PlatformInfos.isMacOS) {
|
||||
final result = await LightCompressor().compressVideo(
|
||||
path: path,
|
||||
videoQuality: VideoQuality.medium,
|
||||
android: AndroidConfig(isSharedStorage: false),
|
||||
ios: IOSConfig(saveInGallery: false),
|
||||
video: Video(videoName: name, targetSizeMb: 5),
|
||||
);
|
||||
if (result is OnFailure) {
|
||||
throw result.message;
|
||||
}
|
||||
if (result is OnSuccess) {
|
||||
destinationPath = result.destinationPath;
|
||||
}
|
||||
if (destinationPath != null) {
|
||||
mediaInfo = await LightCompressor().getMediaInfo(destinationPath);
|
||||
}
|
||||
}
|
||||
} catch (e, s) {
|
||||
Logs().w('Error while fetching video media info', e, s);
|
||||
}
|
||||
|
||||
return MatrixVideoFile(
|
||||
bytes: destinationPath != null
|
||||
? await XFile(destinationPath).readAsBytes()
|
||||
: await readAsBytes(),
|
||||
name: name,
|
||||
mimeType: destinationPath != null
|
||||
? lookupMimeType(destinationPath)
|
||||
: mimeType,
|
||||
width: mediaInfo?.width,
|
||||
height: mediaInfo?.height,
|
||||
duration: mediaInfo?.duration?.inMilliseconds,
|
||||
);
|
||||
}
|
||||
|
||||
Future<MatrixImageFile?> getVideoThumbnail() async {
|
||||
if (!PlatformInfos.isMobile) return null;
|
||||
|
||||
try {
|
||||
final thumbnailPath = await LightCompressor().getVideoThumbnail(path);
|
||||
final bytes = await XFile(thumbnailPath).readAsBytes();
|
||||
return MatrixImageFile(bytes: bytes, name: name);
|
||||
} catch (e, s) {
|
||||
Logs().w('Error while compressing video', e, s);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
62
lib/utils/room_status_extension.dart
Normal file
62
lib/utils/room_status_extension.dart
Normal file
@@ -0,0 +1,62 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../config/app_config.dart';
|
||||
|
||||
extension RoomStatusExtension on Room {
|
||||
String getLocalizedTypingText(BuildContext context) {
|
||||
var typingText = '';
|
||||
final typingUsers = this.typingUsers;
|
||||
typingUsers.removeWhere((User u) => u.id == client.userID);
|
||||
|
||||
if (AppConfig.hideTypingUsernames) {
|
||||
typingText = L10n.of(context).isTyping;
|
||||
if (typingUsers.first.id != directChatMatrixID) {
|
||||
typingText = L10n.of(context).numUsersTyping(typingUsers.length);
|
||||
}
|
||||
} else if (typingUsers.length == 1) {
|
||||
typingText = L10n.of(context).isTyping;
|
||||
if (typingUsers.first.id != directChatMatrixID) {
|
||||
typingText = L10n.of(
|
||||
context,
|
||||
).userIsTyping(typingUsers.first.calcDisplayname());
|
||||
}
|
||||
} else if (typingUsers.length == 2) {
|
||||
typingText = L10n.of(context).userAndUserAreTyping(
|
||||
typingUsers.first.calcDisplayname(),
|
||||
typingUsers[1].calcDisplayname(),
|
||||
);
|
||||
} else if (typingUsers.length > 2) {
|
||||
typingText = L10n.of(context).userAndOthersAreTyping(
|
||||
typingUsers.first.calcDisplayname(),
|
||||
(typingUsers.length - 1),
|
||||
);
|
||||
}
|
||||
return typingText;
|
||||
}
|
||||
|
||||
List<User> getSeenByUsers(Timeline timeline, {String? eventId}) {
|
||||
if (timeline.events.isEmpty) return [];
|
||||
eventId ??= timeline.events.first.eventId;
|
||||
|
||||
final lastReceipts = <User>{};
|
||||
// now we iterate the timeline events until we hit the first rendered event
|
||||
for (final event in timeline.events) {
|
||||
lastReceipts.addAll(event.receipts.map((r) => r.user));
|
||||
if (event.eventId == eventId) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
lastReceipts.removeWhere(
|
||||
(user) =>
|
||||
user.id == client.userID || user.id == timeline.events.first.senderId,
|
||||
);
|
||||
return lastReceipts.toList();
|
||||
}
|
||||
}
|
||||
38
lib/utils/show_scaffold_dialog.dart
Normal file
38
lib/utils/show_scaffold_dialog.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
Future<T?> showScaffoldDialog<T>({
|
||||
required BuildContext context,
|
||||
Color? barrierColor,
|
||||
Color? containerColor,
|
||||
double maxWidth = 480,
|
||||
double maxHeight = 720,
|
||||
required Widget Function(BuildContext context) builder,
|
||||
}) => showDialog<T>(
|
||||
context: context,
|
||||
useSafeArea: false,
|
||||
builder: FluffyThemes.isColumnMode(context)
|
||||
? (context) => Center(
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
color:
|
||||
containerColor ?? Theme.of(context).scaffoldBackgroundColor,
|
||||
),
|
||||
clipBehavior: Clip.hardEdge,
|
||||
margin: const EdgeInsets.all(16),
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: maxWidth,
|
||||
maxHeight: maxHeight,
|
||||
),
|
||||
child: builder(context),
|
||||
),
|
||||
)
|
||||
: builder,
|
||||
);
|
||||
73
lib/utils/show_update_snackbar.dart
Normal file
73
lib/utils/show_update_snackbar.dart
Normal file
@@ -0,0 +1,73 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/adaptive_dialog_action.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:url_launcher/url_launcher_string.dart';
|
||||
|
||||
abstract class UpdateNotifier {
|
||||
static const String versionStoreKey = 'last_known_version';
|
||||
|
||||
static Future<void> showUpdateDialog(BuildContext context) async {
|
||||
final l10n = L10n.of(context);
|
||||
final currentVersion = await PlatformInfos.getVersion();
|
||||
final store = await SharedPreferences.getInstance();
|
||||
final storedVersion = store.getString(versionStoreKey);
|
||||
if (!context.mounted) return;
|
||||
|
||||
if (currentVersion != storedVersion) {
|
||||
if (storedVersion != null) {
|
||||
showAdaptiveDialog(
|
||||
barrierDismissible: true,
|
||||
context: context,
|
||||
builder: (context) => AlertDialog.adaptive(
|
||||
title: Text(
|
||||
l10n.updateInstalled(currentVersion),
|
||||
style: TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
content: Text(l10n.possibleByYou),
|
||||
actions: [
|
||||
AdaptiveDialogAction(
|
||||
bigButtons: true,
|
||||
onPressed: () => launchUrlString(AppConfig.helpUrl),
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
spacing: 4,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.favorite,
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
Text(
|
||||
l10n.support,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
AdaptiveDialogAction(
|
||||
bigButtons: true,
|
||||
onPressed: () => launchUrlString(AppConfig.changelogUrl),
|
||||
child: Text(l10n.changelog),
|
||||
),
|
||||
AdaptiveDialogAction(
|
||||
bigButtons: true,
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(l10n.close),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
await store.setString(versionStoreKey, currentVersion);
|
||||
}
|
||||
}
|
||||
}
|
||||
30
lib/utils/sign_in_flows/calc_redirect_url.dart
Normal file
30
lib/utils/sign_in_flows/calc_redirect_url.dart
Normal file
@@ -0,0 +1,30 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:universal_html/html.dart' as html;
|
||||
|
||||
(Uri redirectUrl, String urlScheme) calcRedirectUrl({
|
||||
bool withAuthHtmlPath = false,
|
||||
}) {
|
||||
var redirectUrl = kIsWeb
|
||||
? Uri.parse(html.window.location.href.split('#').first.split('?').first)
|
||||
: (PlatformInfos.isMobile || PlatformInfos.isMacOS)
|
||||
? Uri.parse('${AppConfig.appSsoUrlScheme.toLowerCase()}:/login')
|
||||
: Uri.parse('http://localhost:3001/login');
|
||||
|
||||
if (kIsWeb && withAuthHtmlPath) {
|
||||
redirectUrl = redirectUrl.resolveUri(Uri(pathSegments: ['auth.html']));
|
||||
}
|
||||
|
||||
final urlScheme =
|
||||
(PlatformInfos.isMobile || PlatformInfos.isWeb || PlatformInfos.isMacOS)
|
||||
? redirectUrl.scheme
|
||||
: 'http://localhost:3001';
|
||||
|
||||
return (redirectUrl, urlScheme);
|
||||
}
|
||||
104
lib/utils/sign_in_flows/check_homeserver.dart
Normal file
104
lib/utils/sign_in_flows/check_homeserver.dart
Normal file
@@ -0,0 +1,104 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/sign_in/view_model/model/public_homeserver_data.dart';
|
||||
import 'package:tatchat/utils/localized_exception_extension.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/utils/sign_in_flows/oidc_login.dart';
|
||||
import 'package:tatchat/utils/sign_in_flows/sso_login.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:url_launcher/url_launcher_string.dart';
|
||||
|
||||
Future<void> connectToHomeserverFlow(
|
||||
PublicHomeserverData homeserverData,
|
||||
BuildContext context,
|
||||
void Function(AsyncSnapshot<bool>) setState,
|
||||
bool signUp,
|
||||
) async {
|
||||
setState(AsyncSnapshot.waiting());
|
||||
try {
|
||||
final homeserverInput = homeserverData.name!;
|
||||
var homeserver = Uri.parse(homeserverInput);
|
||||
if (homeserver.scheme.isEmpty) {
|
||||
homeserver = Uri.https(homeserverInput, '');
|
||||
}
|
||||
final l10n = L10n.of(context);
|
||||
final client = await Matrix.of(context).getLoginClient();
|
||||
final (_, _, loginFlows, authMetadata) = await client.checkHomeserver(
|
||||
homeserver,
|
||||
fetchAuthMetadata: true,
|
||||
);
|
||||
|
||||
final regLink = homeserverData.regLink;
|
||||
final supportsSso = loginFlows.any((flow) => flow.type == 'm.login.sso');
|
||||
|
||||
if ((kIsWeb || PlatformInfos.isLinux) &&
|
||||
(supportsSso || authMetadata != null || (signUp && regLink != null))) {
|
||||
if (!context.mounted) return;
|
||||
final consent = await showOkCancelAlertDialog(
|
||||
context: context,
|
||||
title: l10n.appWantsToUseForLogin(homeserverInput),
|
||||
message: l10n.appWantsToUseForLoginDescription,
|
||||
okLabel: l10n.continueText,
|
||||
);
|
||||
if (consent != OkCancelResult.ok) return;
|
||||
if (!context.mounted) return;
|
||||
}
|
||||
if (!context.mounted) return;
|
||||
|
||||
if (authMetadata != null && AppSettings.enableMatrixNativeOIDC.value) {
|
||||
await oidcLoginFlow(client, context, signUp);
|
||||
} else if (supportsSso) {
|
||||
await ssoLoginFlow(client, context, signUp, loginFlows);
|
||||
} else {
|
||||
final segments = GoRouter.of(context)
|
||||
.routeInformationProvider
|
||||
.value
|
||||
.uri
|
||||
.pathSegments;
|
||||
final location =
|
||||
segments.length >= 3 &&
|
||||
segments[0] == 'rooms' &&
|
||||
segments[1] == 'settings'
|
||||
? '/rooms/settings/addaccount'
|
||||
: '/home';
|
||||
if (signUp && regLink != null) {
|
||||
await launchUrlString(regLink);
|
||||
if (!context.mounted) return;
|
||||
}
|
||||
context.go(
|
||||
'$location/${signUp && regLink == null ? 'register' : 'login'}',
|
||||
extra: client,
|
||||
);
|
||||
setState(AsyncSnapshot.withData(ConnectionState.done, true));
|
||||
return;
|
||||
}
|
||||
|
||||
await AppSettings.defaultHomeserver.setItem(homeserverInput);
|
||||
|
||||
if (context.mounted) {
|
||||
setState(AsyncSnapshot.withData(ConnectionState.done, true));
|
||||
context.go('/backup');
|
||||
}
|
||||
} catch (e, s) {
|
||||
Logs().w('Unable to login', e, s);
|
||||
setState(AsyncSnapshot.withError(ConnectionState.done, e, s));
|
||||
if (!context.mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
e.toLocalizedString(context, ExceptionContext.checkHomeserver),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
92
lib/utils/sign_in_flows/oidc_login.dart
Normal file
92
lib/utils/sign_in_flows/oidc_login.dart
Normal file
@@ -0,0 +1,92 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/oidc_session_json_extension.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/utils/sign_in_flows/calc_redirect_url.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
Future<void> oidcLoginFlow(
|
||||
Client client,
|
||||
BuildContext context,
|
||||
bool signUp,
|
||||
) async {
|
||||
Logs().i('Starting Matrix Native OIDC Flow...');
|
||||
|
||||
final (redirectUrl, urlScheme) = calcRedirectUrl();
|
||||
|
||||
final clientUri = Uri.parse(AppSettings.website.value);
|
||||
final supportWebPlatform =
|
||||
kIsWeb &&
|
||||
kReleaseMode &&
|
||||
redirectUrl.scheme == 'https' &&
|
||||
redirectUrl.host.contains(clientUri.host);
|
||||
if (kIsWeb && !supportWebPlatform) {
|
||||
Logs().w(
|
||||
'OIDC Application Type web is not supported. Using native now. Please use this instance not in production!',
|
||||
);
|
||||
}
|
||||
|
||||
final oidcClientData = await client.registerOidcClient(
|
||||
redirectUris: [redirectUrl],
|
||||
applicationType: supportWebPlatform
|
||||
? OidcApplicationType.web
|
||||
: OidcApplicationType.native,
|
||||
clientInformation: OidcClientInformation(
|
||||
clientName: AppSettings.applicationName.value,
|
||||
clientUri: clientUri,
|
||||
logoUri: Uri.parse(AppSettings.logoUrl.value),
|
||||
tosUri: Uri.parse(AppSettings.tos.value),
|
||||
policyUri: Uri.parse(AppSettings.privacyPolicy.value),
|
||||
),
|
||||
);
|
||||
|
||||
final session = await client.initOidcLoginSession(
|
||||
oidcClientData: oidcClientData,
|
||||
redirectUri: redirectUrl,
|
||||
prompt: signUp ? 'create' : null,
|
||||
);
|
||||
|
||||
if (!context.mounted) return;
|
||||
|
||||
if (kIsWeb) {
|
||||
final store = await SharedPreferences.getInstance();
|
||||
store.setString(
|
||||
OidcSessionJsonExtension.homeserverStoreKey,
|
||||
client.homeserver!.toString(),
|
||||
);
|
||||
store.setString(
|
||||
OidcSessionJsonExtension.storeKey,
|
||||
jsonEncode(session.toJson()),
|
||||
);
|
||||
}
|
||||
|
||||
final returnUrlString = await FlutterWebAuth2.authenticate(
|
||||
url: session.authenticationUri.toString(),
|
||||
callbackUrlScheme: urlScheme,
|
||||
options: FlutterWebAuth2Options(
|
||||
useWebview: PlatformInfos.isMobile,
|
||||
windowName: '_self',
|
||||
),
|
||||
);
|
||||
if (kIsWeb) return; // On Web we return at intro page when app starts again!
|
||||
|
||||
final returnUrl = Uri.parse(returnUrlString);
|
||||
final queryParameters = returnUrl.fragment.isNotEmpty
|
||||
? Uri.parse(returnUrl.fragment).queryParameters
|
||||
: returnUrl.queryParameters;
|
||||
|
||||
final code = queryParameters['code'] as String;
|
||||
final state = queryParameters['state'] as String;
|
||||
|
||||
await client.oidcLogin(session: session, code: code, state: state);
|
||||
}
|
||||
74
lib/utils/sign_in_flows/sso_login.dart
Normal file
74
lib/utils/sign_in_flows/sso_login.dart
Normal file
@@ -0,0 +1,74 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/utils/sign_in_flows/calc_redirect_url.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_modal_action_popup.dart';
|
||||
import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
Future<void> ssoLoginFlow(
|
||||
Client client,
|
||||
BuildContext context,
|
||||
bool signUp,
|
||||
List<LoginFlow> loginFlows,
|
||||
) async {
|
||||
final (redirectUrl, urlScheme) = calcRedirectUrl(withAuthHtmlPath: true);
|
||||
|
||||
Logs().i('Starting legacy SSO Flow with redirect URL', redirectUrl);
|
||||
|
||||
final ssoProviders =
|
||||
(loginFlows
|
||||
.firstWhere((flow) => flow.type == 'm.login.sso')
|
||||
.additionalProperties['identity_providers']
|
||||
as List?)
|
||||
?.map(
|
||||
(json) => (
|
||||
name: json['name'] as String,
|
||||
id: json['id'] as String,
|
||||
brand: json['brand'] as String?,
|
||||
icon: json['icon'] as String?,
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
|
||||
final provider = ssoProviders == null
|
||||
? null
|
||||
: await showModalActionPopup(
|
||||
context: context,
|
||||
title: L10n.of(context).logInTo(client.homeserver!.host),
|
||||
actions: ssoProviders
|
||||
.map(
|
||||
(provider) =>
|
||||
AdaptiveModalAction(label: provider.name, value: provider),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
|
||||
final url = client.homeserver!.replace(
|
||||
path:
|
||||
'/_matrix/client/v3/login/sso/redirect${provider == null ? '' : '/${provider.id}'}',
|
||||
queryParameters: {
|
||||
'redirectUrl': redirectUrl.toString(),
|
||||
'action': signUp ? 'register' : 'login',
|
||||
},
|
||||
);
|
||||
|
||||
final result = await FlutterWebAuth2.authenticate(
|
||||
url: url.toString(),
|
||||
callbackUrlScheme: urlScheme,
|
||||
options: FlutterWebAuth2Options(useWebview: PlatformInfos.isMobile),
|
||||
);
|
||||
final token = Uri.parse(result).queryParameters['loginToken'];
|
||||
if (token?.isEmpty ?? false) return;
|
||||
|
||||
await client.login(
|
||||
LoginType.mLoginToken,
|
||||
token: token,
|
||||
initialDeviceDisplayName: PlatformInfos.appDisplayName,
|
||||
);
|
||||
}
|
||||
26
lib/utils/size_string.dart
Normal file
26
lib/utils/size_string.dart
Normal file
@@ -0,0 +1,26 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
extension SizeString on num {
|
||||
String get sizeString {
|
||||
var size = toDouble();
|
||||
if (size < 1000) {
|
||||
return '${size.round()} Bytes';
|
||||
}
|
||||
if (size < 1000 * 1000) {
|
||||
size = size / 1000;
|
||||
size = (size * 10).round() / 10;
|
||||
return '$size KB';
|
||||
}
|
||||
if (size < 1000 * 1000 * 1000) {
|
||||
size = size / 1000000;
|
||||
size = (size * 10).round() / 10;
|
||||
return '$size MB';
|
||||
}
|
||||
size = size / 1000 * 1000 * 1000 * 1000;
|
||||
size = (size * 10).round() / 10;
|
||||
return '$size GB';
|
||||
}
|
||||
}
|
||||
86
lib/utils/start_push_foreground_service.dart
Normal file
86
lib/utils/start_push_foreground_service.dart
Normal file
@@ -0,0 +1,86 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
|
||||
import 'package:matrix/matrix_api_lite/utils/logs.dart';
|
||||
import 'package:universal_html/html.dart' as html;
|
||||
|
||||
import '../l10n/l10n.dart';
|
||||
|
||||
abstract class ForegroundServices {
|
||||
static final List<String> runningServices = [];
|
||||
|
||||
static bool get platformSupported =>
|
||||
PlatformInfos.isMobile || PlatformInfos.isWeb;
|
||||
|
||||
static bool _beforeUnload(html.Event e) {
|
||||
e.preventDefault();
|
||||
return true;
|
||||
}
|
||||
|
||||
static Future<void> stopService(String name) async {
|
||||
runningServices.remove(name);
|
||||
if (runningServices.isNotEmpty) return;
|
||||
if (kIsWeb) {
|
||||
html.window.removeEventListener('beforeunload', _beforeUnload);
|
||||
return;
|
||||
}
|
||||
FlutterForegroundTask.stopService();
|
||||
}
|
||||
|
||||
static Future<void> startService(String name) async {
|
||||
try {
|
||||
runningServices.add(name);
|
||||
if (kIsWeb) {
|
||||
html.window.addEventListener('beforeunload', _beforeUnload);
|
||||
return;
|
||||
}
|
||||
if (PlatformInfos.isMobile) {
|
||||
final l10n = await L10n.delegate.load(
|
||||
PlatformDispatcher.instance.locale,
|
||||
);
|
||||
FlutterForegroundTask.init(
|
||||
androidNotificationOptions: AndroidNotificationOptions(
|
||||
channelId: 'fluffychat_sync',
|
||||
channelName: l10n.loadingMessages,
|
||||
channelDescription: l10n.loadingMessages,
|
||||
onlyAlertOnce: true,
|
||||
playSound: false,
|
||||
enableVibration: false,
|
||||
priority: NotificationPriority.LOW,
|
||||
),
|
||||
iosNotificationOptions: const IOSNotificationOptions(
|
||||
showNotification: false,
|
||||
playSound: false,
|
||||
),
|
||||
foregroundTaskOptions: ForegroundTaskOptions(
|
||||
eventAction: ForegroundTaskEventAction.nothing(),
|
||||
allowWakeLock: true,
|
||||
),
|
||||
);
|
||||
if (await FlutterForegroundTask.isRunningService) {
|
||||
Logs().d('[PushHelper] Foreground service already running');
|
||||
return;
|
||||
}
|
||||
final result = await FlutterForegroundTask.startService(
|
||||
serviceTypes: [ForegroundServiceTypes.shortService],
|
||||
notificationTitle: 'FluffyChat',
|
||||
notificationText: l10n.loadingMessages,
|
||||
notificationIcon: NotificationIcon(metaDataName: 'ic_launcher'),
|
||||
);
|
||||
final started = result is ServiceRequestSuccess;
|
||||
Logs().d('[PushHelper] Foreground service start: $started ($result)');
|
||||
} else if (kIsWeb) {
|
||||
// TODO: Implement window.onBeforeUnload overwrite
|
||||
}
|
||||
return;
|
||||
} catch (e, s) {
|
||||
Logs().w('[PushHelper] Unable to start foreground service', e, s);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
53
lib/utils/stream_extension.dart
Normal file
53
lib/utils/stream_extension.dart
Normal file
@@ -0,0 +1,53 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
extension StreamExtension on Stream {
|
||||
/// Returns a new Stream which outputs only `true` for every update of the original
|
||||
/// stream, ratelimited by the Duration t
|
||||
Stream<bool> rateLimit(Duration t) {
|
||||
final controller = StreamController<bool>();
|
||||
Timer? timer;
|
||||
var gotMessage = false;
|
||||
// as we call our inline-defined function recursively we need to make sure that the
|
||||
// variable exists prior of creating the function. Silly dart.
|
||||
Function? onMessage;
|
||||
// callback to determine if we should send out an update
|
||||
onMessage = () {
|
||||
// do nothing if it is already closed
|
||||
if (controller.isClosed) {
|
||||
return;
|
||||
}
|
||||
if (timer == null) {
|
||||
// if we don't have a timer yet, send out the update and start a timer
|
||||
gotMessage = false;
|
||||
controller.add(true);
|
||||
timer = Timer(t, () {
|
||||
// the timer has ended...delete it and, if we got a message, re-run the
|
||||
// method to send out an update!
|
||||
timer = null;
|
||||
if (gotMessage) {
|
||||
onMessage?.call();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// set that we got a message
|
||||
gotMessage = true;
|
||||
}
|
||||
};
|
||||
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();
|
||||
controller.close();
|
||||
};
|
||||
return controller.stream;
|
||||
}
|
||||
}
|
||||
25
lib/utils/string_color.dart
Normal file
25
lib/utils/string_color.dart
Normal file
@@ -0,0 +1,25 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
extension StringColor on String {
|
||||
static final _colorSchemeCache = <String, ColorScheme>{};
|
||||
|
||||
ColorScheme get colorScheme =>
|
||||
_colorSchemeCache[this] ??= ColorScheme.fromSeed(
|
||||
seedColor: _getColorLight(0.3),
|
||||
dynamicSchemeVariant: DynamicSchemeVariant.rainbow,
|
||||
);
|
||||
|
||||
Color _getColorLight(double light) {
|
||||
var number = 0.0;
|
||||
for (var i = 0; i < length; i++) {
|
||||
number += codeUnitAt(i);
|
||||
}
|
||||
number = (number % 12) * 25.5;
|
||||
return HSLColor.fromAHSL(0.75, number, 1, light).toColor();
|
||||
}
|
||||
}
|
||||
31
lib/utils/sync_status_localization.dart
Normal file
31
lib/utils/sync_status_localization.dart
Normal file
@@ -0,0 +1,31 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/localized_exception_extension.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
extension SyncStatusLocalization on SyncStatusUpdate {
|
||||
String calcLocalizedString(BuildContext context) {
|
||||
final progress = this.progress;
|
||||
switch (status) {
|
||||
case SyncStatus.waitingForResponse:
|
||||
return L10n.of(context).waitingForServer;
|
||||
case SyncStatus.error:
|
||||
return ((error?.exception ?? Object()) as Object).toLocalizedString(
|
||||
context,
|
||||
);
|
||||
case SyncStatus.processing:
|
||||
case SyncStatus.cleaningUp:
|
||||
case SyncStatus.finished:
|
||||
return progress == null
|
||||
? L10n.of(context).synchronizingPleaseWait
|
||||
: L10n.of(context).synchronizingPleaseWaitCounter(
|
||||
(progress * 100).round().toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
54
lib/utils/tatu_share.dart
Normal file
54
lib/utils/tatu_share.dart
Normal file
@@ -0,0 +1,54 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:share_plus/share_plus.dart';
|
||||
|
||||
import '../widgets/matrix.dart';
|
||||
|
||||
abstract class TatuShare {
|
||||
static Future<void> share(
|
||||
String text,
|
||||
BuildContext context, {
|
||||
bool copyOnly = false,
|
||||
}) async {
|
||||
final l10n = L10n.of(context);
|
||||
final scaffoldMessenger = ScaffoldMessenger.of(context);
|
||||
if (PlatformInfos.isMobile && !copyOnly) {
|
||||
final box = context.findRenderObject() as RenderBox;
|
||||
await SharePlus.instance.share(
|
||||
ShareParams(
|
||||
text: text,
|
||||
sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
await Clipboard.setData(ClipboardData(text: text));
|
||||
if (!PlatformInfos.isMobile) {
|
||||
scaffoldMessenger.showSnackBar(
|
||||
SnackBar(showCloseIcon: true, content: Text(l10n.copiedToClipboard)),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
static Future<void> shareInviteLink(BuildContext context) async {
|
||||
final l10n = L10n.of(context);
|
||||
final client = Matrix.of(context).client;
|
||||
final ownProfile = await client.fetchOwnProfile();
|
||||
if (!context.mounted) return;
|
||||
await TatuShare.share(
|
||||
l10n.inviteText(
|
||||
ownProfile.displayName ?? client.userID!,
|
||||
'https://matrix.to/#/${client.userID}?client=im.tatuchat',
|
||||
),
|
||||
context,
|
||||
);
|
||||
}
|
||||
}
|
||||
110
lib/utils/uia_request_manager.dart
Normal file
110
lib/utils/uia_request_manager.dart
Normal file
@@ -0,0 +1,110 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_text_input_dialog.dart';
|
||||
import 'package:tatchat/widgets/tatu_chat_app.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
extension UiaRequestManager on MatrixState {
|
||||
Future uiaRequestHandler(UiaRequest uiaRequest) async {
|
||||
final l10n = L10n.of(context);
|
||||
final navigatorContext =
|
||||
TatuChatApp.router.routerDelegate.navigatorKey.currentContext ??
|
||||
context;
|
||||
try {
|
||||
if (uiaRequest.state != UiaRequestState.waitForUser ||
|
||||
uiaRequest.nextStages.isEmpty) {
|
||||
Logs().d('Uia Request Stage: ${uiaRequest.state}');
|
||||
return;
|
||||
}
|
||||
final stage = uiaRequest.nextStages.first;
|
||||
Logs().d('Uia Request Stage: $stage');
|
||||
switch (stage) {
|
||||
case AuthenticationTypes.password:
|
||||
final input =
|
||||
cachedPassword ??
|
||||
(await showTextInputDialog(
|
||||
context: navigatorContext,
|
||||
title: l10n.pleaseEnterYourPassword,
|
||||
okLabel: l10n.ok,
|
||||
cancelLabel: l10n.cancel,
|
||||
minLines: 1,
|
||||
maxLines: 1,
|
||||
obscureText: true,
|
||||
hintText: '******',
|
||||
));
|
||||
if (input == null || input.isEmpty) {
|
||||
return uiaRequest.cancel();
|
||||
}
|
||||
return await uiaRequest.completeStage(
|
||||
AuthenticationPassword(
|
||||
session: uiaRequest.session,
|
||||
password: input,
|
||||
identifier: AuthenticationUserIdentifier(user: client.userID!),
|
||||
),
|
||||
);
|
||||
case AuthenticationTypes.dummy:
|
||||
return await uiaRequest.completeStage(
|
||||
AuthenticationData(
|
||||
type: AuthenticationTypes.dummy,
|
||||
session: uiaRequest.session,
|
||||
),
|
||||
);
|
||||
default:
|
||||
final stageUrl = uiaRequest.params
|
||||
.tryGetMap<String, Object?>(stage)
|
||||
?.tryGet<String>('url');
|
||||
final fallbackUrl = client.homeserver!.replace(
|
||||
path: '/_matrix/client/v3/auth/$stage/fallback/web',
|
||||
queryParameters: {'session': uiaRequest.session},
|
||||
);
|
||||
final url = stageUrl != null
|
||||
? (Uri.tryParse(stageUrl) ?? fallbackUrl)
|
||||
: fallbackUrl;
|
||||
|
||||
final consent = await showOkCancelAlertDialog(
|
||||
useRootNavigator: false,
|
||||
title: l10n.pleaseFollowInstructionsOnWeb,
|
||||
context: navigatorContext,
|
||||
okLabel: l10n.open,
|
||||
cancelLabel: l10n.cancel,
|
||||
);
|
||||
if (consent != OkCancelResult.ok) return uiaRequest.cancel();
|
||||
|
||||
launchUrl(url, mode: LaunchMode.inAppBrowserView);
|
||||
final completer = Completer();
|
||||
final listener = AppLifecycleListener(onResume: completer.complete);
|
||||
await completer.future;
|
||||
listener.dispose();
|
||||
|
||||
return await uiaRequest.completeStage(
|
||||
AuthenticationData(
|
||||
session: uiaRequest.session,
|
||||
type: stageUrl == null ? null : stage,
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e, s) {
|
||||
Logs().e('Error while background UIA', e, s);
|
||||
return uiaRequest.cancel(e is Exception ? e : Exception(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class UiaException implements Exception {
|
||||
final String reason;
|
||||
|
||||
UiaException(this.reason);
|
||||
|
||||
@override
|
||||
String toString() => reason;
|
||||
}
|
||||
253
lib/utils/url_launcher.dart
Normal file
253
lib/utils/url_launcher.dart
Normal file
@@ -0,0 +1,253 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:collection/collection.dart' show IterableExtension;
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/user_dialog.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:punycode/punycode.dart';
|
||||
import 'package:url_launcher/url_launcher_string.dart';
|
||||
|
||||
import '../widgets/adaptive_dialogs/public_room_dialog.dart';
|
||||
import 'platform_infos.dart';
|
||||
|
||||
class UrlLauncher {
|
||||
/// The url to open.
|
||||
final String? url;
|
||||
|
||||
/// The visible name in the GUI. For example the name of a markdown link
|
||||
/// which may differ from the actual url to open.
|
||||
final String? name;
|
||||
|
||||
final BuildContext context;
|
||||
|
||||
const UrlLauncher(this.context, this.url, [this.name]);
|
||||
|
||||
Future<void> launchUrl() async {
|
||||
final l10n = L10n.of(context);
|
||||
final scaffoldMessenger = ScaffoldMessenger.of(context);
|
||||
if (url!.toLowerCase().startsWith(AppConfig.deepLinkPrefix) ||
|
||||
url!.toLowerCase().startsWith(AppConfig.inviteLinkPrefix) ||
|
||||
{'#', '@', '!', '+', '\$'}.contains(url![0]) ||
|
||||
url!.toLowerCase().startsWith(AppConfig.schemePrefix)) {
|
||||
return openMatrixToUrl();
|
||||
}
|
||||
final uri = Uri.tryParse(url!);
|
||||
if (uri == null) {
|
||||
// we can't open this thing
|
||||
scaffoldMessenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.cantOpenUri(url!))),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (name != null && url != name) {
|
||||
// If there is a name which differs from the url, we need to make sure
|
||||
// that the user can see the actual url before opening the browser.
|
||||
final consent = await showOkCancelAlertDialog(
|
||||
context: context,
|
||||
title: l10n.openLinkInBrowser,
|
||||
message: url,
|
||||
okLabel: l10n.open,
|
||||
cancelLabel: l10n.cancel,
|
||||
);
|
||||
if (consent != OkCancelResult.ok) return;
|
||||
}
|
||||
|
||||
if (!{'https', 'http'}.contains(uri.scheme)) {
|
||||
// just launch non-https / non-http uris directly
|
||||
|
||||
// we need to transmute geo URIs on desktop and on iOS
|
||||
if ((!PlatformInfos.isMobile || PlatformInfos.isIOS) &&
|
||||
uri.scheme == 'geo') {
|
||||
final latlong = uri.path
|
||||
.split(';')
|
||||
.first
|
||||
.split(',')
|
||||
.map(double.tryParse)
|
||||
.toList();
|
||||
if (latlong.length == 2 &&
|
||||
latlong.first != null &&
|
||||
latlong.last != null) {
|
||||
if (PlatformInfos.isIOS) {
|
||||
// iOS is great at not following standards, so we need to transmute the geo URI
|
||||
// to an apple maps thingy
|
||||
// https://developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html
|
||||
final ll = '${latlong.first},${latlong.last}';
|
||||
launchUrlString('https://maps.apple.com/?q=$ll&sll=$ll');
|
||||
} else {
|
||||
// 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}',
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
launchUrlString(url!);
|
||||
return;
|
||||
}
|
||||
if (uri.host.isEmpty) {
|
||||
scaffoldMessenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.cantOpenUri(url!))),
|
||||
);
|
||||
return;
|
||||
}
|
||||
// okay, we have either an http or an https URI.
|
||||
// As some platforms have issues with opening unicode URLs, we are going to help
|
||||
// them out by punycode-encoding them for them ourself.
|
||||
final newHost = uri.host
|
||||
.split('.')
|
||||
.map((hostPartEncoded) {
|
||||
final hostPart = Uri.decodeComponent(hostPartEncoded);
|
||||
final hostPartPunycode = punycodeEncode(hostPart);
|
||||
return hostPartPunycode != '$hostPart-'
|
||||
? 'xn--$hostPartPunycode'
|
||||
: hostPart;
|
||||
})
|
||||
.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,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> openMatrixToUrl() async {
|
||||
final matrix = Matrix.of(context);
|
||||
final url = this.url!.replaceFirst(
|
||||
AppConfig.deepLinkPrefix,
|
||||
AppConfig.inviteLinkPrefix,
|
||||
);
|
||||
|
||||
// The identifier might be a matrix.to url and needs escaping. Or, it might have multiple
|
||||
// identifiers (room id & event id), or it might also have a query part.
|
||||
// All this needs parsing.
|
||||
final identityParts =
|
||||
url.parseIdentifierIntoParts() ??
|
||||
Uri.tryParse(url)?.host.parseIdentifierIntoParts() ??
|
||||
Uri.tryParse(url)?.pathSegments
|
||||
.lastWhereOrNull((_) => true)
|
||||
?.parseIdentifierIntoParts();
|
||||
if (identityParts == null) {
|
||||
return; // no match, nothing to do
|
||||
}
|
||||
if (identityParts.primaryIdentifier.sigil == '#' ||
|
||||
identityParts.primaryIdentifier.sigil == '!') {
|
||||
// we got a room! Let's open that one
|
||||
final roomIdOrAlias = identityParts.primaryIdentifier;
|
||||
final event = identityParts.secondaryIdentifier;
|
||||
var room =
|
||||
matrix.client.getRoomByAlias(roomIdOrAlias) ??
|
||||
matrix.client.getRoomById(roomIdOrAlias);
|
||||
var roomId = room?.id;
|
||||
// we make the servers a set and later on convert to a list, so that we can easily
|
||||
// deduplicate servers added via alias lookup and query parameter
|
||||
final servers = <String>{};
|
||||
if (room == null && roomIdOrAlias.sigil == '#') {
|
||||
// we were unable to find the room locally...so resolve it
|
||||
final response = await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => matrix.client.getRoomIdByAlias(roomIdOrAlias),
|
||||
);
|
||||
final result = response.result;
|
||||
if (result != null) {
|
||||
roomId = result.roomId;
|
||||
servers.addAll(result.servers!);
|
||||
room = matrix.client.getRoomById(roomId!);
|
||||
}
|
||||
}
|
||||
servers.addAll(identityParts.via);
|
||||
if (!context.mounted) return;
|
||||
if (room != null) {
|
||||
if (room.isSpace) {
|
||||
// TODO: Implement navigate to space
|
||||
context.go('/rooms/${room.id}');
|
||||
|
||||
return;
|
||||
}
|
||||
// we have the room, so....just open it
|
||||
if (event != null) {
|
||||
context.go(
|
||||
'/${Uri(pathSegments: ['rooms', room.id], queryParameters: {'event': event})}',
|
||||
);
|
||||
} else {
|
||||
context.go('/rooms/${room.id}');
|
||||
}
|
||||
return;
|
||||
} else {
|
||||
if (!context.mounted) return;
|
||||
await showAdaptiveDialog(
|
||||
context: context,
|
||||
barrierDismissible: true,
|
||||
builder: (c) =>
|
||||
PublicRoomDialog(roomAlias: identityParts.primaryIdentifier),
|
||||
);
|
||||
}
|
||||
if (roomIdOrAlias.sigil == '!') {
|
||||
if (!context.mounted) return;
|
||||
if (await showOkCancelAlertDialog(
|
||||
useRootNavigator: false,
|
||||
context: context,
|
||||
title: 'Join room $roomIdOrAlias',
|
||||
) ==
|
||||
OkCancelResult.ok) {
|
||||
roomId = roomIdOrAlias;
|
||||
if (!context.mounted) return;
|
||||
final response = await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => matrix.client.joinRoom(
|
||||
roomIdOrAlias,
|
||||
via: servers.isNotEmpty ? servers.toList() : null,
|
||||
),
|
||||
);
|
||||
if (response.error != null) return;
|
||||
if (!context.mounted) return;
|
||||
// wait for two seconds so that it probably came down /sync
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => Future.delayed(const Duration(seconds: 2)),
|
||||
);
|
||||
if (!context.mounted) return;
|
||||
if (event != null) {
|
||||
context.go(
|
||||
Uri(
|
||||
pathSegments: ['rooms', response.result!],
|
||||
queryParameters: {'event': event},
|
||||
).toString(),
|
||||
);
|
||||
} else {
|
||||
context.go('/rooms/${response.result!}');
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (identityParts.primaryIdentifier.sigil == '@') {
|
||||
final userId = identityParts.primaryIdentifier;
|
||||
var noProfileWarning = false;
|
||||
final profileResult = await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () =>
|
||||
matrix.client.getProfileFromUserId(userId).catchError((_) {
|
||||
noProfileWarning = true;
|
||||
return Profile(userId: userId);
|
||||
}),
|
||||
);
|
||||
if (!context.mounted) return;
|
||||
await UserDialog.show(
|
||||
context: context,
|
||||
profile: profileResult.result!,
|
||||
noProfileWarning: noProfileWarning,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
15
lib/utils/verified_room_extension.dart
Normal file
15
lib/utils/verified_room_extension.dart
Normal file
@@ -0,0 +1,15 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
extension VerifiedRoomExtension on Room {
|
||||
bool get allUsersVerified {
|
||||
final users = getParticipants();
|
||||
return !users.any(
|
||||
(user) => client.userDeviceKeys[user.id]?.masterKey?.verified != true,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user