Encrypted messaging app
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

381 lines
12 KiB

  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'package:Capsule/utils/storage/session_cookie.dart';
  4. import 'package:Capsule/views/main/conversation/permissions.dart';
  5. import 'package:flutter/material.dart';
  6. import 'package:http/http.dart' as http;
  7. import '/components/custom_title_bar.dart';
  8. import '/components/flash_message.dart';
  9. import '/components/select_message_ttl.dart';
  10. import '/exceptions/update_data_exception.dart';
  11. import '/models/friends.dart';
  12. import '/utils/encryption/crypto_utils.dart';
  13. import '/utils/storage/write_file.dart';
  14. import '/views/main/conversation/create_add_users.dart';
  15. import '/models/conversation_users.dart';
  16. import '/models/conversations.dart';
  17. import '/models/my_profile.dart';
  18. import '/views/main/conversation/settings_user_list_item.dart';
  19. import '/views/main/conversation/edit_details.dart';
  20. import '/components/custom_circle_avatar.dart';
  21. import '/utils/storage/database.dart';
  22. import '/utils/storage/conversations.dart';
  23. class ConversationSettings extends StatefulWidget {
  24. const ConversationSettings({
  25. Key? key,
  26. required this.conversation,
  27. }) : super(key: key);
  28. final Conversation conversation;
  29. @override
  30. State<ConversationSettings> createState() => _ConversationSettingsState();
  31. }
  32. class _ConversationSettingsState extends State<ConversationSettings> {
  33. List<ConversationUser> users = [];
  34. MyProfile? profile;
  35. TextEditingController nameController = TextEditingController();
  36. @override
  37. Widget build(BuildContext context) {
  38. return Scaffold(
  39. appBar: CustomTitleBar(
  40. title: Text(
  41. widget.conversation.name + ' Settings',
  42. style: TextStyle(
  43. fontSize: 16,
  44. fontWeight: FontWeight.w600,
  45. color: Theme.of(context).appBarTheme.toolbarTextStyle?.color
  46. ),
  47. ),
  48. showBack: true,
  49. ),
  50. body: Padding(
  51. padding: const EdgeInsets.all(15),
  52. child: SingleChildScrollView(
  53. child: Column(
  54. children: <Widget> [
  55. const SizedBox(height: 30),
  56. conversationName(),
  57. const SizedBox(height: 25),
  58. widget.conversation.admin ?
  59. sectionTitle('Settings') :
  60. const SizedBox.shrink(),
  61. widget.conversation.admin ?
  62. settings() :
  63. const SizedBox.shrink(),
  64. widget.conversation.admin ?
  65. const SizedBox(height: 25) :
  66. const SizedBox.shrink(),
  67. sectionTitle('Members', showUsersAdd: widget.conversation.admin && !widget.conversation.twoUser),
  68. usersList(),
  69. const SizedBox(height: 25),
  70. myAccess(),
  71. ],
  72. ),
  73. ),
  74. ),
  75. );
  76. }
  77. Widget conversationName() {
  78. return Row(
  79. children: <Widget> [
  80. CustomCircleAvatar(
  81. icon: const Icon(Icons.people, size: 40),
  82. radius: 30,
  83. image: widget.conversation.icon,
  84. ),
  85. const SizedBox(width: 10),
  86. Text(
  87. widget.conversation.name,
  88. style: const TextStyle(
  89. fontSize: 25,
  90. fontWeight: FontWeight.w500,
  91. ),
  92. ),
  93. (widget.conversation.admin && widget.conversation.adminEditInfo) && !widget.conversation.twoUser ? IconButton(
  94. iconSize: 20,
  95. icon: const Icon(Icons.edit),
  96. padding: const EdgeInsets.all(5.0),
  97. splashRadius: 25,
  98. onPressed: () {
  99. Navigator.of(context).push(
  100. MaterialPageRoute(builder: (context) => ConversationEditDetails(
  101. // TODO: Move saveCallback to somewhere else
  102. saveCallback: (String conversationName, File? file) async {
  103. bool updatedImage = false;
  104. File? writtenFile;
  105. if (file != null) {
  106. updatedImage = file.hashCode != widget.conversation.icon.hashCode;
  107. writtenFile = await writeImage(
  108. widget.conversation.id,
  109. file.readAsBytesSync(),
  110. );
  111. }
  112. widget.conversation.name = conversationName;
  113. widget.conversation.icon = writtenFile;
  114. await saveConversation();
  115. await updateConversation(widget.conversation, updatedImage: updatedImage)
  116. .catchError((error) {
  117. String message = error.toString();
  118. if (error.runtimeType != UpdateDataException) {
  119. message = 'An error occured, please try again later';
  120. }
  121. showMessage(message, context);
  122. });
  123. setState(() {});
  124. Navigator.pop(context);
  125. },
  126. conversation: widget.conversation,
  127. )),
  128. ).then(onGoBack);
  129. },
  130. ) : const SizedBox.shrink(),
  131. ],
  132. );
  133. }
  134. Future<void> getUsers() async {
  135. users = await getConversationUsers(widget.conversation);
  136. profile = await MyProfile.getProfile();
  137. setState(() {});
  138. }
  139. @override
  140. void initState() {
  141. nameController.text = widget.conversation.name;
  142. super.initState();
  143. getUsers();
  144. }
  145. Widget myAccess() {
  146. return Align(
  147. alignment: Alignment.centerLeft,
  148. child: Column(
  149. crossAxisAlignment: CrossAxisAlignment.stretch,
  150. children: [
  151. TextButton.icon(
  152. label: const Text(
  153. 'Leave Conversation',
  154. style: TextStyle(fontSize: 16)
  155. ),
  156. icon: const Icon(Icons.exit_to_app),
  157. style: const ButtonStyle(
  158. alignment: Alignment.centerLeft,
  159. ),
  160. onPressed: () {
  161. print('Leave Group');
  162. }
  163. ),
  164. ],
  165. ),
  166. );
  167. }
  168. Widget sectionTitle(String title, { bool showUsersAdd = false}) {
  169. return Align(
  170. alignment: Alignment.centerLeft,
  171. child: Padding(
  172. padding: const EdgeInsets.only(right: 6),
  173. child: Row(
  174. children: [
  175. Expanded(
  176. child: Container(
  177. padding: const EdgeInsets.only(left: 12),
  178. child: Text(
  179. title,
  180. style: const TextStyle(fontSize: 20),
  181. ),
  182. ),
  183. ),
  184. !showUsersAdd ?
  185. const SizedBox.shrink() :
  186. IconButton(
  187. icon: const Icon(Icons.add),
  188. padding: const EdgeInsets.all(0),
  189. onPressed: () async {
  190. List<Friend> friends = await unselectedFriends();
  191. Navigator.of(context).push(
  192. MaterialPageRoute(builder: (context) => ConversationAddFriendsList(
  193. friends: friends,
  194. saveCallback: (List<Friend> selectedFriends) async {
  195. addUsersToConversation(
  196. widget.conversation,
  197. selectedFriends,
  198. );
  199. await updateConversation(widget.conversation, includeUsers: true);
  200. await getUsers();
  201. Navigator.pop(context);
  202. },
  203. ))
  204. );
  205. },
  206. ),
  207. ],
  208. )
  209. )
  210. );
  211. }
  212. Widget settings() {
  213. return Align(
  214. alignment: Alignment.centerLeft,
  215. child: Column(
  216. crossAxisAlignment: CrossAxisAlignment.stretch,
  217. children: [
  218. const SizedBox(height: 5),
  219. TextButton.icon(
  220. label: const Text(
  221. 'Disappearing Messages',
  222. style: TextStyle(fontSize: 16)
  223. ),
  224. icon: const Icon(Icons.timer),
  225. style: ButtonStyle(
  226. alignment: Alignment.centerLeft,
  227. foregroundColor: MaterialStateProperty.resolveWith<Color>(
  228. (Set<MaterialState> states) {
  229. return Theme.of(context).colorScheme.onBackground;
  230. },
  231. )
  232. ),
  233. onPressed: () {
  234. Navigator.of(context).push(
  235. MaterialPageRoute(builder: (context) => SelectMessageTTL(
  236. widgetTitle: 'Message Expiry',
  237. currentSelected: widget.conversation.messageExpiryDefault,
  238. backCallback: (String messageExpiry) async {
  239. widget.conversation.messageExpiryDefault = messageExpiry;
  240. http.post(
  241. await MyProfile.getServerUrl(
  242. 'api/v1/auth/conversations/${widget.conversation.id}/message_expiry'
  243. ),
  244. headers: {
  245. 'cookie': await getSessionCookie(),
  246. },
  247. body: jsonEncode({
  248. 'message_expiry': messageExpiry,
  249. }),
  250. ).then((http.Response response) {
  251. if (response.statusCode == 204) {
  252. return;
  253. }
  254. showMessage(
  255. 'Could not change the default message expiry, please try again later.',
  256. context,
  257. );
  258. });
  259. saveConversation();
  260. }
  261. ))
  262. );
  263. }
  264. ),
  265. TextButton.icon(
  266. label: const Text(
  267. 'Permissions',
  268. style: TextStyle(fontSize: 16)
  269. ),
  270. icon: const Icon(Icons.lock),
  271. style: ButtonStyle(
  272. alignment: Alignment.centerLeft,
  273. foregroundColor: MaterialStateProperty.resolveWith<Color>(
  274. (Set<MaterialState> states) {
  275. return Theme.of(context).colorScheme.onBackground;
  276. },
  277. )
  278. ),
  279. onPressed: () {
  280. Navigator.of(context).push(
  281. MaterialPageRoute(builder: (context) => ConversationPermissions(
  282. conversation: widget.conversation,
  283. ))
  284. );
  285. }
  286. ),
  287. ],
  288. ),
  289. );
  290. }
  291. Widget usersList() {
  292. return ListView.builder(
  293. itemCount: users.length,
  294. shrinkWrap: true,
  295. padding: const EdgeInsets.only(top: 5, bottom: 0),
  296. physics: const NeverScrollableScrollPhysics(),
  297. itemBuilder: (context, i) {
  298. return ConversationSettingsUserListItem(
  299. user: users[i],
  300. isAdmin: widget.conversation.admin,
  301. twoUser: widget.conversation.twoUser,
  302. profile: profile!, // TODO: Fix this
  303. );
  304. }
  305. );
  306. }
  307. Future<List<Friend>> unselectedFriends() async {
  308. final db = await getDatabaseConnection();
  309. List<String> notInArgs = [];
  310. for (var user in users) {
  311. notInArgs.add(user.userId);
  312. }
  313. final List<Map<String, dynamic>> maps = await db.query(
  314. 'friends',
  315. where: 'friend_id not in (${List.filled(notInArgs.length, '?').join(',')})',
  316. whereArgs: notInArgs,
  317. orderBy: 'username',
  318. );
  319. return List.generate(maps.length, (i) {
  320. return Friend(
  321. id: maps[i]['id'],
  322. userId: maps[i]['user_id'],
  323. friendId: maps[i]['friend_id'],
  324. friendSymmetricKey: maps[i]['symmetric_key'],
  325. publicKey: CryptoUtils.rsaPublicKeyFromPem(maps[i]['asymmetric_public_key']),
  326. acceptedAt: maps[i]['accepted_at'],
  327. username: maps[i]['username'],
  328. );
  329. });
  330. }
  331. onGoBack(dynamic value) async {
  332. nameController.text = widget.conversation.name;
  333. getUsers();
  334. setState(() {});
  335. }
  336. saveConversation() async {
  337. final db = await getDatabaseConnection();
  338. db.update(
  339. 'conversations',
  340. widget.conversation.toMap(),
  341. where: 'id = ?',
  342. whereArgs: [widget.conversation.id],
  343. );
  344. }
  345. }