fluffychat/lib/pages/homeserver_picker.dart

254 lines
7.8 KiB
Dart
Raw Normal View History

2021-06-06 17:07:19 +02:00
import 'dart:async';
2021-07-15 14:04:29 +02:00
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:matrix/matrix.dart';
import 'package:fluffychat/pages/views/homeserver_picker_view.dart';
import 'package:fluffychat/utils/famedlysdk_store.dart';
2021-05-22 08:53:52 +02:00
import 'package:fluffychat/widgets/matrix.dart';
2021-04-09 16:29:48 +02:00
import 'package:fluffychat/config/app_config.dart';
import 'package:fluffychat/config/setting_keys.dart';
2021-06-06 17:07:19 +02:00
import 'package:flutter/foundation.dart';
2020-10-03 11:11:28 +02:00
import 'package:flutter_gen/gen_l10n/l10n.dart';
2020-04-12 10:35:45 +02:00
import 'package:flutter/material.dart';
2021-06-11 10:08:04 +02:00
import 'package:url_launcher/url_launcher.dart';
2021-01-17 15:33:31 +01:00
import '../utils/localized_exception_extension.dart';
2021-05-23 13:11:55 +02:00
import 'package:vrouter/vrouter.dart';
2021-06-06 17:07:19 +02:00
import 'package:fluffychat/utils/platform_infos.dart';
import 'package:future_loading_dialog/future_loading_dialog.dart';
import 'package:uni_links/uni_links.dart';
import '../main.dart';
2020-04-12 10:35:45 +02:00
2021-01-17 15:33:31 +01:00
class HomeserverPicker extends StatefulWidget {
@override
2021-04-09 16:28:26 +02:00
HomeserverPickerController createState() => HomeserverPickerController();
2021-01-17 15:33:31 +01:00
}
2020-04-12 10:35:45 +02:00
2021-04-09 16:28:26 +02:00
class HomeserverPickerController extends State<HomeserverPicker> {
bool isLoading = false;
String domain = AppConfig.defaultHomeserver;
final TextEditingController homeserverController =
2021-01-22 21:39:37 +01:00
TextEditingController(text: AppConfig.defaultHomeserver);
2021-06-06 17:07:19 +02:00
StreamSubscription _intentDataStreamSubscription;
2021-06-11 10:08:04 +02:00
String error;
Timer _coolDown;
void setDomain(String domain) {
this.domain = domain;
_coolDown?.cancel();
if (domain.isNotEmpty) {
_coolDown = Timer(Duration(seconds: 1), checkHomeserverAction);
}
}
2021-06-06 17:07:19 +02:00
void _loginWithToken(String token) {
if (token?.isEmpty ?? true) return;
2021-06-06 17:07:19 +02:00
showFutureLoadingDialog(
context: context,
future: () async {
if (Matrix.of(context).client.homeserver == null) {
await Matrix.of(context).client.checkHomeserver(
2021-06-11 10:08:04 +02:00
await Store()
.getItem(HomeserverPickerController.ssoHomeserverKey),
);
}
await Matrix.of(context).client.login(
type: AuthenticationTypes.token,
token: token,
initialDeviceDisplayName: PlatformInfos.clientName,
);
},
2021-06-06 17:07:19 +02:00
);
}
void _processIncomingUris(String text) async {
if (text == null || !text.startsWith(AppConfig.appOpenUrlScheme)) return;
2021-07-15 14:04:29 +02:00
await browser?.close();
2021-07-08 17:10:20 +02:00
VRouter.of(context).to('/home');
2021-06-06 17:07:19 +02:00
final token = Uri.parse(text).queryParameters['loginToken'];
if (token != null) _loginWithToken(token);
}
void _initReceiveUri() {
if (!PlatformInfos.isMobile) return;
// For receiving shared Uris
_intentDataStreamSubscription = linkStream.listen(_processIncomingUris);
if (FluffyChatApp.gotInitialLink == false) {
FluffyChatApp.gotInitialLink = true;
getInitialLink().then(_processIncomingUris);
}
}
@override
void initState() {
super.initState();
_initReceiveUri();
if (kIsWeb) {
WidgetsBinding.instance.addPostFrameCallback((_) {
2021-07-08 18:42:46 +02:00
final token = Matrix.of(context).widget.queryParameters['loginToken'];
if (token != null) _loginWithToken(token);
2021-06-06 17:07:19 +02:00
});
}
}
@override
void dispose() {
super.dispose();
_intentDataStreamSubscription?.cancel();
}
2021-01-17 15:33:31 +01:00
2021-04-09 16:28:26 +02:00
/// Starts an analysis of the given homeserver. It uses the current domain and
/// makes sure that it is prefixed with https. Then it searches for the
/// well-known information and forwards to the login page depending on the
2021-06-11 10:08:04 +02:00
/// login type.
2021-04-09 16:28:26 +02:00
void checkHomeserverAction() async {
2021-06-11 10:08:04 +02:00
_coolDown?.cancel();
2021-01-22 21:39:37 +01:00
try {
2021-04-09 16:28:26 +02:00
if (domain.isEmpty) throw L10n.of(context).changeTheHomeserver;
var homeserver = domain;
2021-01-22 21:39:37 +01:00
if (!homeserver.startsWith('https://')) {
homeserver = 'https://$homeserver';
}
2021-01-18 22:59:02 +01:00
2021-06-11 10:08:04 +02:00
setState(() {
error = _rawLoginTypes = registrationSupported = null;
isLoading = true;
});
final wellKnown =
await Matrix.of(context).client.checkHomeserver(homeserver);
var jitsi = wellKnown?.content
?.tryGet<Map<String, dynamic>>('im.vector.riot.jitsi')
?.tryGet<String>('preferredDomain');
if (jitsi != null) {
if (!jitsi.endsWith('/')) {
jitsi += '/';
}
Logs().v('Found custom jitsi instance $jitsi');
await Matrix.of(context)
.store
.setItem(SettingKeys.jitsiInstance, jitsi);
AppConfig.jitsiInstance = jitsi;
}
2021-01-17 15:33:31 +01:00
} catch (e) {
2021-06-11 10:08:04 +02:00
setState(() => error = '${(e as Object).toLocalizedString(context)}');
2021-01-17 15:33:31 +01:00
} finally {
if (mounted) {
2021-04-09 16:28:26 +02:00
setState(() => isLoading = false);
2021-01-17 15:33:31 +01:00
}
2020-04-12 10:35:45 +02:00
}
}
2021-06-11 10:08:04 +02:00
Map<String, dynamic> _rawLoginTypes;
bool registrationSupported;
List<IdentityProvider> get identityProviders {
if (!ssoLoginSupported) return [];
final rawProviders = _rawLoginTypes.tryGetList('flows').singleWhere(
(flow) =>
flow['type'] == AuthenticationTypes.sso)['identity_providers'];
final list = (rawProviders as List)
2021-06-11 10:08:04 +02:00
.map((json) => IdentityProvider.fromJson(json))
.toList();
2021-07-15 14:04:29 +02:00
if (PlatformInfos.isCupertinoStyle) {
list.sort((a, b) => a.brand == 'apple' ? -1 : 1);
}
return list;
2021-06-11 10:08:04 +02:00
}
bool get passwordLoginSupported =>
Matrix.of(context)
.client
.supportedLoginTypes
.contains(AuthenticationTypes.password) &&
_rawLoginTypes
.tryGetList('flows')
.any((flow) => flow['type'] == AuthenticationTypes.password);
bool get ssoLoginSupported =>
Matrix.of(context)
.client
.supportedLoginTypes
.contains(AuthenticationTypes.sso) &&
_rawLoginTypes
.tryGetList('flows')
.any((flow) => flow['type'] == AuthenticationTypes.sso);
Future<Map<String, dynamic>> getLoginTypes() async {
_rawLoginTypes ??= await Matrix.of(context).client.request(
RequestType.GET,
'/client/r0/login',
);
if (registrationSupported == null) {
try {
await Matrix.of(context).client.register();
registrationSupported = true;
} on MatrixException catch (e) {
registrationSupported = e.requireAdditionalAuthentication ?? false;
}
}
return _rawLoginTypes;
}
2021-07-15 14:04:29 +02:00
ChromeSafariBrowser browser;
2021-06-11 10:08:04 +02:00
static const String ssoHomeserverKey = 'sso-homeserver';
void ssoLoginAction(String id) {
if (kIsWeb) {
// We store the homserver in the local storage instead of a redirect
// parameter because of possible CSRF attacks.
Store().setItem(
ssoHomeserverKey, Matrix.of(context).client.homeserver.toString());
}
final redirectUrl = kIsWeb
2021-06-18 16:15:11 +02:00
? AppConfig.webBaseUrl + '/#/'
2021-06-18 11:21:00 +02:00
: AppConfig.appOpenUrlScheme.toLowerCase() + '://login';
2021-07-15 14:04:29 +02:00
final url =
'${Matrix.of(context).client.homeserver?.toString()}/_matrix/client/r0/login/sso/redirect/${Uri.encodeComponent(id)}?redirectUrl=${Uri.encodeQueryComponent(redirectUrl)}';
2021-07-18 19:04:09 +02:00
if (PlatformInfos.isMobile) {
2021-07-15 14:04:29 +02:00
browser ??= ChromeSafariBrowser();
browser.open(url: Uri.parse(url));
} else {
2021-07-18 19:04:09 +02:00
launch(redirectUrl);
2021-07-15 14:04:29 +02:00
}
2021-06-11 10:08:04 +02:00
}
void signUpAction() => launch(
2021-07-15 14:04:29 +02:00
'${Matrix.of(context).client.homeserver?.toString()}/_matrix/static/client/register',
forceSafariVC: true,
forceWebView: true,
);
2021-06-11 10:08:04 +02:00
bool _initialized = false;
2020-04-12 10:35:45 +02:00
@override
Widget build(BuildContext context) {
Matrix.of(context).navigatorContext = context;
2021-06-11 10:08:04 +02:00
if (!_initialized) {
_initialized = true;
checkHomeserverAction();
}
return HomeserverPickerView(this);
}
2020-04-12 10:35:45 +02:00
}
2021-06-11 10:08:04 +02:00
class IdentityProvider {
final String id;
final String name;
final String icon;
final String brand;
IdentityProvider({this.id, this.name, this.icon, this.brand});
factory IdentityProvider.fromJson(Map<String, dynamic> json) =>
IdentityProvider(
id: json['id'],
name: json['name'],
icon: json['icon'],
brand: json['brand'],
);
}