FurryChat/lib/views/chat_list.dart

486 lines
22 KiB
Dart
Raw Normal View History

2020-01-02 14:10:21 +00:00
import 'dart:async';
2020-04-02 12:05:32 +00:00
import 'dart:io';
2020-01-02 14:10:21 +00:00
2020-01-01 18:10:13 +00:00
import 'package:famedlysdk/famedlysdk.dart';
2020-06-10 08:07:01 +00:00
import 'package:famedlysdk/matrix_api.dart';
2020-07-04 08:22:51 +00:00
import 'package:fluffychat/components/connection_status_header.dart';
import 'package:fluffychat/components/dialogs/simple_dialogs.dart';
import 'package:fluffychat/components/list_items/presence_list_item.dart';
2020-02-22 19:05:04 +00:00
import 'package:fluffychat/components/list_items/public_room_list_item.dart';
import 'package:flutter/foundation.dart';
2020-01-01 18:10:13 +00:00
import 'package:flutter/material.dart';
2020-04-02 12:05:32 +00:00
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
import 'package:share/share.dart';
import '../components/adaptive_page_layout.dart';
import '../components/list_items/chat_list_item.dart';
import '../components/matrix.dart';
2020-05-07 05:52:40 +00:00
import '../l10n/l10n.dart';
import '../utils/app_route.dart';
import '../utils/url_launcher.dart';
import 'archive.dart';
2020-05-12 09:58:47 +00:00
import 'homeserver_picker.dart';
import 'new_group.dart';
import 'new_private_chat.dart';
import 'settings.dart';
enum SelectMode { normal, share }
2020-01-17 10:37:02 +00:00
2020-01-01 18:10:13 +00:00
class ChatListView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return AdaptivePageLayout(
primaryPage: FocusPage.FIRST,
firstScaffold: ChatList(),
secondScaffold: Scaffold(
body: Center(
2020-05-13 13:58:59 +00:00
child: Image.asset('assets/logo.png', width: 100, height: 100),
2020-01-01 18:10:13 +00:00
),
),
);
}
}
class ChatList extends StatefulWidget {
final String activeChat;
const ChatList({this.activeChat, Key key}) : super(key: key);
2020-01-01 18:10:13 +00:00
@override
_ChatListState createState() => _ChatListState();
}
class _ChatListState extends State<ChatList> {
bool get searchMode => searchController.text?.isNotEmpty ?? false;
2020-01-02 21:55:12 +00:00
final TextEditingController searchController = TextEditingController();
2020-06-27 11:09:21 +00:00
final FocusNode _searchFocusNode = FocusNode();
2020-02-22 19:05:04 +00:00
Timer coolDown;
PublicRoomsResponse publicRoomsResponse;
bool loadingPublicRooms = false;
String searchServer;
2020-01-01 18:10:13 +00:00
2020-05-09 07:30:03 +00:00
final ScrollController _scrollController = ScrollController();
2020-05-09 05:17:55 +00:00
Future<void> waitForFirstSync(BuildContext context) async {
2020-05-13 13:58:59 +00:00
var client = Matrix.of(context).client;
2020-01-02 21:31:39 +00:00
if (client.prevBatch?.isEmpty ?? true) {
2020-01-02 14:10:21 +00:00
await client.onFirstSync.stream.first;
2020-01-02 21:31:39 +00:00
}
2020-01-02 14:10:21 +00:00
return true;
2020-01-01 18:10:13 +00:00
}
2020-05-09 07:30:03 +00:00
bool _scrolledToTop = true;
2020-01-02 21:55:12 +00:00
@override
void initState() {
2020-05-09 07:30:03 +00:00
_scrollController.addListener(() async {
if (_scrollController.position.pixels > 0 && _scrolledToTop) {
setState(() => _scrolledToTop = false);
} else if (_scrollController.position.pixels == 0 && !_scrolledToTop) {
setState(() => _scrolledToTop = true);
}
});
2020-02-22 19:05:04 +00:00
searchController.addListener(() {
coolDown?.cancel();
if (searchController.text.isEmpty) {
setState(() {
loadingPublicRooms = false;
publicRoomsResponse = null;
});
return;
}
2020-02-22 19:05:04 +00:00
coolDown = Timer(Duration(seconds: 1), () async {
setState(() => loadingPublicRooms = true);
final newPublicRoomsResponse =
2020-04-27 11:36:39 +00:00
await SimpleDialogs(context).tryRequestWithErrorToast(
2020-08-16 10:54:43 +00:00
Matrix.of(context).client.searchPublicRooms(
2020-02-22 19:05:04 +00:00
limit: 30,
includeAllNetworks: true,
genericSearchTerm: searchController.text,
server: searchServer,
),
);
setState(() {
loadingPublicRooms = false;
if (newPublicRoomsResponse != false) {
publicRoomsResponse = newPublicRoomsResponse;
if (searchController.text.isNotEmpty &&
searchController.text.isValidMatrixId &&
2020-05-13 13:58:59 +00:00
searchController.text.sigil == '#') {
2020-06-10 08:07:01 +00:00
publicRoomsResponse.chunk.add(
PublicRoom.fromJson({
'aliases': [searchController.text],
'name': searchController.text,
'room_id': searchController.text,
}),
2020-02-22 19:05:04 +00:00
);
}
}
});
});
setState(() => null);
});
2020-04-02 12:05:32 +00:00
_initReceiveSharingINtent();
2020-01-02 21:55:12 +00:00
super.initState();
}
2020-01-19 18:28:12 +00:00
StreamSubscription _intentDataStreamSubscription;
2020-04-02 12:05:32 +00:00
StreamSubscription _intentFileStreamSubscription;
2020-01-19 18:28:12 +00:00
2020-04-02 12:05:32 +00:00
void _processIncomingSharedFiles(List<SharedMediaFile> files) {
if (files?.isEmpty ?? true) return;
if (Navigator.of(context).canPop()) {
Navigator.of(context).popUntil((r) => r.isFirst);
}
2020-05-13 13:58:59 +00:00
final file = File(files.first.path);
2020-04-02 12:05:32 +00:00
Matrix.of(context).shareContent = {
2020-05-13 13:58:59 +00:00
'msgtype': 'chat.fluffy.shared_file',
'file': MatrixFile(
2020-04-02 12:05:32 +00:00
bytes: file.readAsBytesSync(),
2020-07-02 09:30:59 +00:00
name: file.path,
2020-03-29 10:06:25 +00:00
),
2020-04-02 12:05:32 +00:00
};
}
void _processIncomingSharedText(String text) {
if (text == null) return;
if (Navigator.of(context).canPop()) {
Navigator.of(context).popUntil((r) => r.isFirst);
}
2020-05-13 13:58:59 +00:00
if (text.startsWith('https://matrix.to/#/')) {
2020-04-02 12:05:32 +00:00
UrlLauncher(context, text).openMatrixToUrl();
return;
}
Matrix.of(context).shareContent = {
2020-05-13 13:58:59 +00:00
'msgtype': 'm.text',
'body': text,
2020-04-02 12:05:32 +00:00
};
}
void _initReceiveSharingINtent() {
if (kIsWeb) return;
// For sharing images coming from outside the app while the app is in the memory
_intentFileStreamSubscription = ReceiveSharingIntent.getMediaStream()
.listen(_processIncomingSharedFiles, onError: print);
// For sharing images coming from outside the app while the app is closed
ReceiveSharingIntent.getInitialMedia().then(_processIncomingSharedFiles);
// For sharing or opening urls/text coming from outside the app while the app is in the memory
_intentDataStreamSubscription = ReceiveSharingIntent.getTextStream()
.listen(_processIncomingSharedText, onError: print);
// For sharing or opening urls/text coming from outside the app while the app is closed
ReceiveSharingIntent.getInitialText().then(_processIncomingSharedText);
2020-01-19 18:28:12 +00:00
}
void _drawerTapAction(Widget view) {
Navigator.of(context).pop();
Navigator.of(context).pushAndRemoveUntil(
AppRoute.defaultRoute(
context,
view,
),
(r) => r.isFirst,
);
}
void _setStatus(BuildContext context) async {
Navigator.of(context).pop();
final status = await SimpleDialogs(context).enterText(
multiLine: true,
2020-05-07 05:52:40 +00:00
titleText: L10n.of(context).setStatus,
labelText: L10n.of(context).setStatus,
hintText: L10n.of(context).statusExampleMessage,
);
if (status?.isEmpty ?? true) return;
2020-04-27 11:36:39 +00:00
await SimpleDialogs(context).tryRequestWithLoadingDialog(
2020-08-16 10:54:43 +00:00
Matrix.of(context).client.sendPresence(
2020-06-10 08:07:01 +00:00
Matrix.of(context).client.userID, PresenceType.online,
statusMsg: status),
);
}
2020-01-01 18:10:13 +00:00
@override
void dispose() {
2020-01-02 21:55:12 +00:00
searchController.removeListener(
() => setState(() => null),
);
2020-01-19 18:28:12 +00:00
_intentDataStreamSubscription?.cancel();
2020-04-02 12:05:32 +00:00
_intentFileStreamSubscription?.cancel();
2020-01-01 18:10:13 +00:00
super.dispose();
}
@override
Widget build(BuildContext context) {
2020-05-12 09:58:47 +00:00
return StreamBuilder<LoginState>(
stream: Matrix.of(context).client.onLoginStateChanged.stream,
2020-05-09 05:17:55 +00:00
builder: (context, snapshot) {
2020-05-12 09:58:47 +00:00
if (snapshot.data == LoginState.loggedOut) {
Timer(Duration(seconds: 1), () {
Matrix.of(context).clean();
Navigator.of(context).pushAndRemoveUntil(
AppRoute.defaultRoute(context, HomeserverPicker()),
(r) => false);
});
}
return StreamBuilder(
stream: Matrix.of(context).onShareContentChanged.stream,
builder: (context, snapshot) {
final selectMode = Matrix.of(context).shareContent == null
? SelectMode.normal
: SelectMode.share;
return Scaffold(
drawer: selectMode == SelectMode.share
? null
: Drawer(
child: SafeArea(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
ListTile(
leading: Icon(Icons.edit),
title: Text(L10n.of(context).setStatus),
onTap: () => _setStatus(context),
),
Divider(height: 1),
ListTile(
leading: Icon(Icons.people_outline),
title: Text(L10n.of(context).createNewGroup),
onTap: () => _drawerTapAction(NewGroupView()),
),
ListTile(
leading: Icon(Icons.person_add),
title: Text(L10n.of(context).newPrivateChat),
onTap: () =>
_drawerTapAction(NewPrivateChatView()),
),
Divider(height: 1),
ListTile(
leading: Icon(Icons.archive),
title: Text(L10n.of(context).archive),
onTap: () => _drawerTapAction(
Archive(),
),
),
ListTile(
leading: Icon(Icons.settings),
title: Text(L10n.of(context).settings),
onTap: () => _drawerTapAction(
SettingsView(),
),
),
Divider(height: 1),
ListTile(
leading: Icon(Icons.share),
title: Text(L10n.of(context).inviteContact),
onTap: () {
Navigator.of(context).pop();
Share.share(L10n.of(context).inviteText(
Matrix.of(context).client.userID,
2020-05-13 13:58:59 +00:00
'https://matrix.to/#/${Matrix.of(context).client.userID}'));
2020-05-12 09:58:47 +00:00
},
),
],
),
2020-05-09 05:17:55 +00:00
),
2020-05-12 09:58:47 +00:00
),
appBar: AppBar(
2020-06-24 07:42:28 +00:00
//elevation: _scrolledToTop ? 0 : null,
2020-05-12 09:58:47 +00:00
leading: selectMode != SelectMode.share
? null
: IconButton(
icon: Icon(Icons.close),
onPressed: () =>
Matrix.of(context).shareContent = null,
2020-05-09 05:17:55 +00:00
),
2020-05-12 09:58:47 +00:00
titleSpacing: 0,
title: selectMode == SelectMode.share
? Text(L10n.of(context).share)
2020-06-24 07:42:28 +00:00
: Padding(
2020-06-25 07:15:53 +00:00
padding:
EdgeInsets.only(top: 8, bottom: 8, right: 8),
2020-06-24 13:04:58 +00:00
child: TextField(
autocorrect: false,
controller: searchController,
2020-06-27 11:09:21 +00:00
focusNode: _searchFocusNode,
2020-06-24 13:04:58 +00:00
decoration: InputDecoration(
contentPadding: EdgeInsets.all(9),
border: InputBorder.none,
hintText: L10n.of(context).searchForAChat,
2020-06-27 11:09:21 +00:00
suffixIcon: searchMode
? IconButton(
icon: Icon(Icons.backspace),
onPressed: () => setState(() {
searchController.clear();
_searchFocusNode.unfocus();
}),
)
: null,
2020-05-12 09:58:47 +00:00
),
2020-05-09 05:17:55 +00:00
),
),
2020-04-26 17:08:55 +00:00
),
2020-05-12 09:58:47 +00:00
floatingActionButton:
(AdaptivePageLayout.columnMode(context) ||
selectMode == SelectMode.share)
? null
2020-06-24 07:42:28 +00:00
: FloatingActionButton(
2020-05-12 09:58:47 +00:00
child: Icon(Icons.add),
backgroundColor: Theme.of(context).primaryColor,
2020-06-24 07:42:28 +00:00
onPressed: () => Navigator.of(context)
.pushAndRemoveUntil(
AppRoute.defaultRoute(
context, NewPrivateChatView()),
(r) => r.isFirst),
2020-04-27 08:12:12 +00:00
),
2020-08-22 09:02:08 +00:00
body: Column(
children: [
ConnectionStatusHeader(),
Expanded(
child: StreamBuilder(
stream: Matrix.of(context)
.client
.onSync
.stream
.where((s) => s.hasRoomUpdate),
builder: (context, snapshot) {
return FutureBuilder<void>(
future: waitForFirstSync(context),
builder: (BuildContext context, snapshot) {
if (snapshot.hasData) {
var rooms = List<Room>.from(
Matrix.of(context).client.rooms);
rooms.removeWhere((Room room) =>
room.lastEvent == null ||
(searchMode &&
!room.displayname
.toLowerCase()
.contains(searchController.text
.toLowerCase() ??
'')));
if (rooms.isEmpty &&
(!searchMode ||
publicRoomsResponse == null)) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Icon(
searchMode
? Icons.search
: Icons.chat_bubble_outline,
size: 80,
color: Colors.grey,
),
Text(searchMode
? L10n.of(context).noRoomsFound
: L10n.of(context)
.startYourFirstChat),
],
),
2020-07-04 08:22:51 +00:00
);
2020-05-12 09:58:47 +00:00
}
2020-08-22 09:02:08 +00:00
final publicRoomsCount =
(publicRoomsResponse?.chunk?.length ??
0);
final totalCount =
rooms.length + publicRoomsCount;
final directChats = rooms
.where((r) => r.isDirectChat)
.toList();
final presences =
Matrix.of(context).client.presences;
directChats.sort((a, b) => presences[
b.directChatMatrixID]
?.presence
?.statusMsg !=
null
? 1
: b.lastEvent.originServerTs.compareTo(
a.lastEvent.originServerTs));
return ListView.separated(
controller: _scrollController,
separatorBuilder: (BuildContext context,
int i) =>
i == totalCount - publicRoomsCount
? ListTile(
title: Text(
L10n.of(context)
.publicRooms +
':',
style: TextStyle(
fontWeight:
FontWeight.bold,
color: Theme.of(context)
.primaryColor,
),
),
)
: Container(),
itemCount: totalCount + 1,
itemBuilder:
(BuildContext context, int i) {
if (i == 0) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
(directChats.isEmpty ||
selectMode ==
SelectMode.share)
? Container()
: PreferredSize(
preferredSize:
Size.fromHeight(90),
child: Container(
height: 82,
child:
ListView.builder(
scrollDirection:
Axis.horizontal,
itemCount:
directChats
.length,
itemBuilder: (BuildContext
context,
int i) =>
PresenceListItem(
directChats[
i]),
),
),
),
],
);
}
i--;
return i < rooms.length
? ChatListItem(
rooms[i],
activeChat:
widget.activeChat ==
rooms[i].id,
)
: PublicRoomListItem(
publicRoomsResponse
.chunk[i - rooms.length]);
});
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
2020-05-12 09:58:47 +00:00
);
2020-08-22 09:02:08 +00:00
}),
),
],
),
2020-05-12 09:58:47 +00:00
);
});
2020-05-09 05:17:55 +00:00
});
2020-01-01 18:10:13 +00:00
}
}