commit 0038967f704c279d1caf26e849d7d8460bb9937e Author: Moj1403 Date: Mon Apr 13 23:41:27 2026 +0330 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3820a95 --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..54bb785 --- /dev/null +++ b/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "cd9e44ff10cac283eafc97d6ed58720c45f1be9e" + channel: "master" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + base_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + - platform: android + create_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + base_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + - platform: ios + create_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + base_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + - platform: linux + create_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + base_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + - platform: macos + create_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + base_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + - platform: web + create_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + base_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + - platform: windows + create_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + base_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/README.md b/README.md new file mode 100644 index 0000000..a27bb52 --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# saba_secure_sms + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/analyze_results.txt b/analyze_results.txt new file mode 100644 index 0000000..bddee3f --- /dev/null +++ b/analyze_results.txt @@ -0,0 +1,415 @@ +Analyzing saba-dart... + + info • The import of 'dart:ui' is unnecessary because all of the used elements are also provided by the import of 'package:flutter/material.dart' • lib/screens/chat_screen.dart:3:8 • unnecessary_import + error • The argument type 'MessageBubble' can't be assigned to the parameter type 'Widget?'. • lib/screens/chat_screen.dart:1567:34 • argument_type_not_assignable + info • Don't invoke 'print' in production code • lib/screens/compose_screen.dart:62:7 • avoid_print + info • Don't use 'BuildContext's across async gaps • lib/screens/compose_screen.dart:129:7 • use_build_context_synchronously + info • Use interpolation to compose strings and values • lib/screens/compose_screen.dart:255:20 • prefer_interpolation_to_compose_strings + info • 'withOpacity' is deprecated and shouldn't be used. Use .withValues() to avoid precision loss • lib/screens/compose_screen.dart:415:63 • deprecated_member_use + info • 'withOpacity' is deprecated and shouldn't be used. Use .withValues() to avoid precision loss • lib/screens/compose_screen.dart:582:22 • deprecated_member_use + info • Statements in an if should be enclosed in a block • lib/screens/compose_screen.dart:639:7 • curly_braces_in_flow_control_structures + info • Statements in an if should be enclosed in a block • lib/screens/compose_screen.dart:689:11 • curly_braces_in_flow_control_structures + info • Don't use 'BuildContext's across async gaps • lib/screens/compose_screen.dart:695:15 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps • lib/screens/compose_screen.dart:700:29 • use_build_context_synchronously + info • The import of 'dart:ui' is unnecessary because all of the used elements are also provided by the import of 'package:flutter/material.dart' • lib/screens/group_chat_screen.dart:2:8 • unnecessary_import +warning • The value of the field '_selectedSim' isn't used • lib/screens/group_chat_screen.dart:95:25 • unused_field +warning • The value of the field '_loadingSims' isn't used • lib/screens/group_chat_screen.dart:98:8 • unused_field + info • Don't use 'BuildContext's across async gaps, guarded by an unrelated 'mounted' check • lib/screens/group_chat_screen.dart:226:29 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps, guarded by an unrelated 'mounted' check • lib/screens/group_chat_screen.dart:410:29 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps • lib/screens/group_chat_screen.dart:530:28 • use_build_context_synchronously + error • The element type 'MessageBubble' can't be assigned to the list type 'Widget' • lib/screens/group_chat_screen.dart:692:29 • list_element_type_not_assignable + error • Too many positional arguments: 0 expected, but 2 found • lib/screens/group_chat_screen.dart:716:21 • extra_positional_arguments_could_be_named + error • Expected to find ')' • lib/screens/group_chat_screen.dart:735:19 • expected_token + error • Expected to find ';' • lib/screens/group_chat_screen.dart:739:11 • expected_token +warning • Dead code • lib/screens/group_chat_screen.dart:739:12 • dead_code + error • Expected an identifier • lib/screens/group_chat_screen.dart:739:12 • missing_identifier + error • Expected to find ';' • lib/screens/group_chat_screen.dart:739:12 • expected_token + error • Unexpected text ';' • lib/screens/group_chat_screen.dart:739:12 • unexpected_token + error • Expected an identifier • lib/screens/group_chat_screen.dart:740:9 • missing_identifier + error • Expected to find ';' • lib/screens/group_chat_screen.dart:740:9 • expected_token + error • Unexpected text ';' • lib/screens/group_chat_screen.dart:740:9 • unexpected_token + error • Expected an identifier • lib/screens/group_chat_screen.dart:740:10 • missing_identifier + error • Expected to find ';' • lib/screens/group_chat_screen.dart:740:10 • expected_token + error • Unexpected text ';' • lib/screens/group_chat_screen.dart:740:10 • unexpected_token + error • Expected an identifier • lib/screens/group_chat_screen.dart:741:7 • missing_identifier + error • Expected to find ';' • lib/screens/group_chat_screen.dart:741:7 • expected_token + error • Unexpected text ';' • lib/screens/group_chat_screen.dart:741:7 • unexpected_token + error • Expected an identifier • lib/screens/group_chat_screen.dart:741:8 • missing_identifier + error • Expected to find ';' • lib/screens/group_chat_screen.dart:741:8 • expected_token + error • Unexpected text ';' • lib/screens/group_chat_screen.dart:741:8 • unexpected_token + error • Expected an identifier • lib/screens/group_chat_screen.dart:742:5 • missing_identifier + error • Unexpected text ';' • lib/screens/group_chat_screen.dart:742:5 • unexpected_token + info • Unnecessary empty statement • lib/screens/group_chat_screen.dart:742:6 • empty_statements + info • Don't use 'BuildContext's across async gaps • lib/screens/group_chat_screen.dart:819:15 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps • lib/screens/group_chat_screen.dart:824:29 • use_build_context_synchronously + error • The class '_HomeScreenState' doesn't have an unnamed constructor • lib/screens/home_screen.dart:19:38 • new_with_undefined_constructor_default + info • Don't use 'BuildContext's across async gaps • lib/screens/home_screen.dart:185:11 • use_build_context_synchronously + info • Don't invoke 'print' in production code • lib/screens/home_screen.dart:244:7 • avoid_print + info • Don't use 'BuildContext's across async gaps • lib/screens/home_screen.dart:300:28 • use_build_context_synchronously + error • Expected to find ';' • lib/screens/home_screen.dart:309:39 • expected_token +warning • Dead code • lib/screens/home_screen.dart:311:15 • dead_code + error • Expected an identifier • lib/screens/home_screen.dart:311:15 • missing_identifier + error • Expected to find ')' • lib/screens/home_screen.dart:311:15 • expected_token + error • Expected a class member • lib/screens/home_screen.dart:312:14 • expected_class_member + info • An uninitialized field should have an explicit type annotation • lib/screens/home_screen.dart:313:13 • prefer_typing_uninitialized_variables + error • Expected to find ';' • lib/screens/home_screen.dart:313:13 • expected_token + error • Variables must be declared using the keywords 'const', 'final', 'var' or a type name • lib/screens/home_screen.dart:313:13 • missing_const_final_var_or_type + error • Expected a class member • lib/screens/home_screen.dart:313:18 • expected_class_member + error • Getters, setters and methods can't be declared to be 'const' • lib/screens/home_screen.dart:313:20 • const_method + info • The variable name 'Image' isn't a lowerCamelCase identifier • lib/screens/home_screen.dart:313:26 • non_constant_identifier_names + error • Named parameters must be enclosed in curly braces ('{' and '}') • lib/screens/home_screen.dart:314:20 • named_parameter_outside_group + error • Using a colon as the separator before a default value is no longer supported • lib/screens/home_screen.dart:314:20 • obsolete_colon_for_default_value + info • Use 'const' with the constructor to improve performance • lib/screens/home_screen.dart:314:22 • prefer_const_constructors + error • The default value of an optional parameter must be constant • lib/screens/home_screen.dart:314:22 • non_constant_default_value + error • Named parameters must be enclosed in curly braces ('{' and '}') • lib/screens/home_screen.dart:315:21 • named_parameter_outside_group + error • Using a colon as the separator before a default value is no longer supported • lib/screens/home_screen.dart:315:21 • obsolete_colon_for_default_value + error • Named parameters must be enclosed in curly braces ('{' and '}') • lib/screens/home_screen.dart:316:18 • named_parameter_outside_group + error • Using a colon as the separator before a default value is no longer supported • lib/screens/home_screen.dart:316:18 • obsolete_colon_for_default_value + error • A function body must be provided • lib/screens/home_screen.dart:317:14 • missing_function_body + error • Expected a class member • lib/screens/home_screen.dart:317:14 • expected_class_member + error • Expected a class member • lib/screens/home_screen.dart:318:11 • expected_class_member + error • Expected a class member • lib/screens/home_screen.dart:318:12 • expected_class_member + error • Expected a class member • lib/screens/home_screen.dart:319:9 • expected_class_member + error • Expected a class member • lib/screens/home_screen.dart:319:10 • expected_class_member + info • An uninitialized field should have an explicit type annotation • lib/screens/home_screen.dart:320:9 • prefer_typing_uninitialized_variables + error • Expected to find ';' • lib/screens/home_screen.dart:320:9 • expected_token + error • Variables must be declared using the keywords 'const', 'final', 'var' or a type name • lib/screens/home_screen.dart:320:9 • missing_const_final_var_or_type + error • Expected a class member • lib/screens/home_screen.dart:320:16 • expected_class_member + error • Expected a class member • lib/screens/home_screen.dart:320:18 • expected_class_member + info • The variable name 'IconButton' isn't a lowerCamelCase identifier • lib/screens/home_screen.dart:321:11 • non_constant_identifier_names + error • Named parameters must be enclosed in curly braces ('{' and '}') • lib/screens/home_screen.dart:322:17 • named_parameter_outside_group + error • Using a colon as the separator before a default value is no longer supported • lib/screens/home_screen.dart:322:17 • obsolete_colon_for_default_value + error • Named parameters must be enclosed in curly braces ('{' and '}') • lib/screens/home_screen.dart:323:22 • named_parameter_outside_group + error • Using a colon as the separator before a default value is no longer supported • lib/screens/home_screen.dart:323:22 • obsolete_colon_for_default_value + error • The default value of an optional parameter must be constant • lib/screens/home_screen.dart:323:24 • non_constant_default_value + error • A function body must be provided • lib/screens/home_screen.dart:327:12 • missing_function_body + error • Expected a class member • lib/screens/home_screen.dart:327:12 • expected_class_member + info • The variable name 'IconButton' isn't a lowerCamelCase identifier • lib/screens/home_screen.dart:328:11 • non_constant_identifier_names + error • The name 'IconButton' is already defined • lib/screens/home_screen.dart:328:11 • duplicate_definition + error • Named parameters must be enclosed in curly braces ('{' and '}') • lib/screens/home_screen.dart:329:17 • named_parameter_outside_group + error • Using a colon as the separator before a default value is no longer supported • lib/screens/home_screen.dart:329:17 • obsolete_colon_for_default_value + error • Named parameters must be enclosed in curly braces ('{' and '}') • lib/screens/home_screen.dart:330:22 • named_parameter_outside_group + error • Using a colon as the separator before a default value is no longer supported • lib/screens/home_screen.dart:330:22 • obsolete_colon_for_default_value + error • The default value of an optional parameter must be constant • lib/screens/home_screen.dart:330:24 • non_constant_default_value + error • A function body must be provided • lib/screens/home_screen.dart:332:9 • missing_function_body + error • Expected a class member • lib/screens/home_screen.dart:332:9 • expected_class_member + error • Expected a class member • lib/screens/home_screen.dart:332:10 • expected_class_member + info • An uninitialized field should have an explicit type annotation • lib/screens/home_screen.dart:333:9 • prefer_typing_uninitialized_variables + error • Expected to find ';' • lib/screens/home_screen.dart:333:9 • expected_token + error • Variables must be declared using the keywords 'const', 'final', 'var' or a type name • lib/screens/home_screen.dart:333:9 • missing_const_final_var_or_type + error • Expected a class member • lib/screens/home_screen.dart:333:15 • expected_class_member + info • The variable name 'PreferredSize' isn't a lowerCamelCase identifier • lib/screens/home_screen.dart:333:17 • non_constant_identifier_names + error • Named parameters must be enclosed in curly braces ('{' and '}') • lib/screens/home_screen.dart:334:24 • named_parameter_outside_group + error • Using a colon as the separator before a default value is no longer supported • lib/screens/home_screen.dart:334:24 • obsolete_colon_for_default_value + error • Named parameters must be enclosed in curly braces ('{' and '}') • lib/screens/home_screen.dart:335:16 • named_parameter_outside_group + error • Using a colon as the separator before a default value is no longer supported • lib/screens/home_screen.dart:335:16 • obsolete_colon_for_default_value + error • The default value of an optional parameter must be constant • lib/screens/home_screen.dart:335:18 • non_constant_default_value + error • A function body must be provided • lib/screens/home_screen.dart:352:10 • missing_function_body + error • Expected a class member • lib/screens/home_screen.dart:352:10 • expected_class_member + error • Expected a class member • lib/screens/home_screen.dart:353:7 • expected_class_member + error • Expected a class member • lib/screens/home_screen.dart:353:8 • expected_class_member + info • An uninitialized field should have an explicit type annotation • lib/screens/home_screen.dart:354:7 • prefer_typing_uninitialized_variables + error • Expected to find ';' • lib/screens/home_screen.dart:354:7 • expected_token + error • Variables must be declared using the keywords 'const', 'final', 'var' or a type name • lib/screens/home_screen.dart:354:7 • missing_const_final_var_or_type + error • Expected a class member • lib/screens/home_screen.dart:354:11 • expected_class_member + info • The variable name 'TabBarView' isn't a lowerCamelCase identifier • lib/screens/home_screen.dart:354:13 • non_constant_identifier_names + error • Named parameters must be enclosed in curly braces ('{' and '}') • lib/screens/home_screen.dart:355:19 • named_parameter_outside_group + error • Using a colon as the separator before a default value is no longer supported • lib/screens/home_screen.dart:355:19 • obsolete_colon_for_default_value + error • The default value of an optional parameter must be constant • lib/screens/home_screen.dart:355:21 • non_constant_default_value + error • Named parameters must be enclosed in curly braces ('{' and '}') • lib/screens/home_screen.dart:356:17 • named_parameter_outside_group + error • Using a colon as the separator before a default value is no longer supported • lib/screens/home_screen.dart:356:17 • obsolete_colon_for_default_value + error • The default value of an optional parameter must be constant • lib/screens/home_screen.dart:356:19 • non_constant_default_value + error • A function body must be provided • lib/screens/home_screen.dart:497:8 • missing_function_body + error • Expected a class member • lib/screens/home_screen.dart:497:8 • expected_class_member + info • An uninitialized field should have an explicit type annotation • lib/screens/home_screen.dart:498:7 • prefer_typing_uninitialized_variables + error • Expected to find ';' • lib/screens/home_screen.dart:498:7 • expected_token + error • Variables must be declared using the keywords 'const', 'final', 'var' or a type name • lib/screens/home_screen.dart:498:7 • missing_const_final_var_or_type + error • Expected a class member • lib/screens/home_screen.dart:498:27 • expected_class_member + error • The name of a constructor must match the name of the enclosing class • lib/screens/home_screen.dart:498:29 • invalid_constructor_name +warning • A value for optional parameter 'backgroundColor' isn't ever given • lib/screens/home_screen.dart:499:9 • unused_element_parameter + error • Named parameters must be enclosed in curly braces ('{' and '}') • lib/screens/home_screen.dart:499:24 • named_parameter_outside_group + error • Using a colon as the separator before a default value is no longer supported • lib/screens/home_screen.dart:499:24 • obsolete_colon_for_default_value + error • The default value of an optional parameter must be constant • lib/screens/home_screen.dart:499:26 • non_constant_default_value +warning • A value for optional parameter 'icon' isn't ever given • lib/screens/home_screen.dart:500:9 • unused_element_parameter + error • Named parameters must be enclosed in curly braces ('{' and '}') • lib/screens/home_screen.dart:500:13 • named_parameter_outside_group + error • Using a colon as the separator before a default value is no longer supported • lib/screens/home_screen.dart:500:13 • obsolete_colon_for_default_value + error • The default value of an optional parameter must be constant • lib/screens/home_screen.dart:500:15 • non_constant_default_value +warning • A value for optional parameter 'label' isn't ever given • lib/screens/home_screen.dart:502:9 • unused_element_parameter + error • Named parameters must be enclosed in curly braces ('{' and '}') • lib/screens/home_screen.dart:502:14 • named_parameter_outside_group + error • Using a colon as the separator before a default value is no longer supported • lib/screens/home_screen.dart:502:14 • obsolete_colon_for_default_value + error • The default value of an optional parameter must be constant • lib/screens/home_screen.dart:502:16 • non_constant_default_value +warning • A value for optional parameter 'onPressed' isn't ever given • lib/screens/home_screen.dart:505:9 • unused_element_parameter + error • Named parameters must be enclosed in curly braces ('{' and '}') • lib/screens/home_screen.dart:505:18 • named_parameter_outside_group + error • Using a colon as the separator before a default value is no longer supported • lib/screens/home_screen.dart:505:18 • obsolete_colon_for_default_value + error • The default value of an optional parameter must be constant • lib/screens/home_screen.dart:505:20 • non_constant_default_value + info • Empty constructor bodies should be written using a ';' rather than '{}' • lib/screens/home_screen.dart:510:8 • empty_constructor_bodies + error • A function body must be provided • lib/screens/home_screen.dart:510:8 • missing_function_body + error • Expected a class member • lib/screens/home_screen.dart:510:8 • expected_class_member + error • Expected a class member • lib/screens/home_screen.dart:511:5 • expected_class_member + error • Expected a class member • lib/screens/home_screen.dart:511:6 • expected_class_member + error • Undefined name 'primaryColor' • lib/screens/home_screen.dart:653:54 • undefined_identifier + error • Undefined name 'primaryColor' • lib/screens/home_screen.dart:671:68 • undefined_identifier + error • Expected a method, getter, setter or operator declaration • lib/screens/home_screen.dart:684:1 • expected_executable + info • Use 'const' with the constructor to improve performance • lib/screens/settings_screen.dart:109:21 • prefer_const_constructors + info • Use 'const' literals as arguments to constructors of '@immutable' classes • lib/screens/settings_screen.dart:110:33 • prefer_const_literals_to_create_immutables + info • Use 'const' with the constructor to improve performance • lib/screens/settings_screen.dart:161:21 • prefer_const_constructors + info • Use 'const' literals as arguments to constructors of '@immutable' classes • lib/screens/settings_screen.dart:162:33 • prefer_const_literals_to_create_immutables + info • Use 'const' with the constructor to improve performance • lib/screens/settings_screen.dart:212:21 • prefer_const_constructors + info • Use 'const' literals as arguments to constructors of '@immutable' classes • lib/screens/settings_screen.dart:213:33 • prefer_const_literals_to_create_immutables + info • 'activeColor' is deprecated and shouldn't be used. Use activeThumbColor instead. This feature was deprecated after v3.31.0-2.0.pre • lib/screens/settings_screen.dart:241:27 • deprecated_member_use + info • 'value' is deprecated and shouldn't be used. Use component accessors like .r or .g, or toARGB32 for an explicit conversion • lib/screens/settings_screen.dart:286:49 • deprecated_member_use + info • 'value' is deprecated and shouldn't be used. Use component accessors like .r or .g, or toARGB32 for an explicit conversion • lib/screens/settings_screen.dart:286:64 • deprecated_member_use + info • 'value' is deprecated and shouldn't be used. Use component accessors like .r or .g, or toARGB32 for an explicit conversion • lib/screens/settings_screen.dart:291:57 • deprecated_member_use + info • 'withOpacity' is deprecated and shouldn't be used. Use .withValues() to avoid precision loss • lib/screens/settings_screen.dart:312:30 • deprecated_member_use + error • The argument type 'CardTheme' can't be assigned to the parameter type 'CardThemeData?'. • lib/utils/app_theme.dart:81:18 • argument_type_not_assignable + info • The private field _memoryCache could be 'final' • lib/utils/contact_helper.dart:5:30 • prefer_final_fields + info • Don't invoke 'print' in production code • lib/utils/contact_helper.dart:19:7 • avoid_print + info • Don't invoke 'print' in production code • lib/utils/crypto_helper.dart:29:7 • avoid_print + error • Classes can only extend other classes • lib/widgets/message_bubble.dart:5:29 • extends_non_class + error • Undefined class 'VoidCallback' • lib/widgets/message_bubble.dart:14:9 • undefined_class + error • No associated named super constructor parameter • lib/widgets/message_bubble.dart:20:11 • super_formal_parameter_without_associated_named + error • Undefined class 'State' • lib/widgets/message_bubble.dart:35:3 • undefined_class +warning • The method doesn't override an inherited method • lib/widgets/message_bubble.dart:35:24 • override_on_non_overriding_member + error • Mixin can only be applied to class • lib/widgets/message_bubble.dart:38:35 • mixin_with_non_class_superclass + error • Classes can only mix in mixins and classes • lib/widgets/message_bubble.dart:39:10 • mixin_of_non_class + error • Undefined class 'AnimationController' • lib/widgets/message_bubble.dart:41:8 • undefined_class + error • Undefined class 'Animation' • lib/widgets/message_bubble.dart:42:8 • undefined_class + error • The name 'Offset' isn't a type, so it can't be used as a type argument • lib/widgets/message_bubble.dart:42:18 • non_type_as_type_argument + error • Undefined class 'Animation' • lib/widgets/message_bubble.dart:43:8 • undefined_class +warning • The method doesn't override an inherited method • lib/widgets/message_bubble.dart:46:8 • override_on_non_overriding_member + error • The method 'initState' isn't defined in a superclass of '_MessageBubbleState' • lib/widgets/message_bubble.dart:47:11 • undefined_super_member + error • The method 'AnimationController' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:48:28 • undefined_method + error • The method 'CurvedAnimation' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:53:22 • undefined_method + error • Undefined name 'Curves' • lib/widgets/message_bubble.dart:55:14 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:59:33 • undefined_identifier + error • The method 'Tween' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:61:23 • undefined_method + error • The name 'Offset' isn't a type, so it can't be used as a type argument • lib/widgets/message_bubble.dart:61:29 • non_type_as_type_argument + error • The method 'Offset' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:62:14 • undefined_method + error • Undefined name 'Offset' • lib/widgets/message_bubble.dart:63:12 • undefined_identifier + error • The method 'CurvedAnimation' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:64:15 • undefined_method + error • Undefined name 'Curves' • lib/widgets/message_bubble.dart:66:14 • undefined_identifier +warning • The method doesn't override an inherited method • lib/widgets/message_bubble.dart:73:8 • override_on_non_overriding_member + error • The method 'dispose' isn't defined in a superclass of '_MessageBubbleState' • lib/widgets/message_bubble.dart:75:11 • undefined_super_member + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:79:7 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:80:7 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:81:7 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:81:25 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:84:21 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:85:14 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:89:9 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:90:14 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:92:9 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:93:14 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:95:12 • undefined_identifier + error • Undefined class 'Widget' • lib/widgets/message_bubble.dart:99:3 • undefined_class +warning • The method doesn't override an inherited method • lib/widgets/message_bubble.dart:99:10 • override_on_non_overriding_member + error • Undefined class 'BuildContext' • lib/widgets/message_bubble.dart:99:16 • undefined_class + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:100:27 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:100:57 • undefined_identifier + error • The name 'Color' isn't a type, so it can't be used as a type argument • lib/widgets/message_bubble.dart:103:16 • non_type_as_type_argument + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:103:39 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:104:12 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:104:30 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:105:12 • undefined_identifier + error • The name 'Color' isn't a class • lib/widgets/message_bubble.dart:106:22 • creation_with_non_type + error • The name 'Color' isn't a class • lib/widgets/message_bubble.dart:106:47 • creation_with_non_type + error • The name 'Color' isn't a class • lib/widgets/message_bubble.dart:107:22 • creation_with_non_type + error • The name 'Color' isn't a class • lib/widgets/message_bubble.dart:107:47 • creation_with_non_type + error • Undefined class 'Color' • lib/widgets/message_bubble.dart:110:11 • undefined_class + error • The name 'Color' isn't a class • lib/widgets/message_bubble.dart:111:17 • creation_with_non_type + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:112:12 • undefined_identifier + error • The name 'Color' isn't a class • lib/widgets/message_bubble.dart:112:36 • creation_with_non_type + error • The name 'Color' isn't a class • lib/widgets/message_bubble.dart:112:62 • creation_with_non_type + error • The method 'FadeTransition' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:114:12 • undefined_method + error • The method 'SlideTransition' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:116:14 • undefined_method + error • The method 'Row' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:118:16 • undefined_method + error • Undefined name 'TextDirection' • lib/widgets/message_bubble.dart:119:26 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:121:15 • undefined_identifier + error • Undefined name 'MainAxisAlignment' • lib/widgets/message_bubble.dart:121:29 • undefined_identifier + error • Undefined name 'MainAxisAlignment' • lib/widgets/message_bubble.dart:121:53 • undefined_identifier + error • The method 'Padding' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:123:13 • undefined_method + error • Undefined name 'EdgeInsets' • lib/widgets/message_bubble.dart:124:24 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:125:23 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:126:24 • undefined_identifier + error • The method 'CustomPaint' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:130:22 • undefined_method + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:132:26 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:133:29 • undefined_identifier + error • The method 'LinearGradient' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:134:25 • undefined_method + error • Undefined name 'Alignment' • lib/widgets/message_bubble.dart:136:34 • undefined_identifier + error • Undefined name 'Alignment' • lib/widgets/message_bubble.dart:137:32 • undefined_identifier + error • The method 'LinearGradient' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:140:29 • undefined_method + error • The name 'Color' isn't a class • lib/widgets/message_bubble.dart:142:41 • creation_with_non_type + error • The name 'Color' isn't a class • lib/widgets/message_bubble.dart:143:41 • creation_with_non_type + error • Undefined name 'Alignment' • lib/widgets/message_bubble.dart:145:38 • undefined_identifier + error • Undefined name 'Alignment' • lib/widgets/message_bubble.dart:146:36 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:149:25 • undefined_identifier + error • The method 'Container' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:151:24 • undefined_method + error • Undefined name 'EdgeInsets' • lib/widgets/message_bubble.dart:152:34 • undefined_identifier + error • The method 'BoxConstraints' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:153:32 • undefined_method + error • Undefined name 'MediaQuery' • lib/widgets/message_bubble.dart:154:33 • undefined_identifier + error • The method 'Column' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:155:26 • undefined_method + error • Undefined name 'CrossAxisAlignment' • lib/widgets/message_bubble.dart:156:41 • undefined_identifier + error • Undefined name 'MainAxisSize' • lib/widgets/message_bubble.dart:157:35 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:159:27 • undefined_identifier + error • The method 'Padding' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:160:25 • undefined_method + error • Undefined name 'EdgeInsets' • lib/widgets/message_bubble.dart:161:42 • undefined_identifier + error • The method 'Row' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:162:34 • undefined_method + error • Undefined name 'MainAxisSize' • lib/widgets/message_bubble.dart:163:43 • undefined_identifier + error • The method 'Icon' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:165:31 • undefined_method + error • Undefined name 'Icons' • lib/widgets/message_bubble.dart:167:39 • undefined_identifier + error • Undefined name 'Icons' • lib/widgets/message_bubble.dart:168:39 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:170:40 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:171:39 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:173:43 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:174:43 • undefined_identifier + error • The name 'SizedBox' isn't a class • lib/widgets/message_bubble.dart:176:37 • creation_with_non_type + error • The method 'Text' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:177:31 • undefined_method + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:180:40 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:182:44 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:184:48 • undefined_identifier + error • The method 'TextStyle' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:187:40 • undefined_method + error • Undefined name 'FontWeight' • lib/widgets/message_bubble.dart:188:47 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:189:42 • undefined_identifier + error • The name 'Color' isn't a class • lib/widgets/message_bubble.dart:190:47 • creation_with_non_type + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:192:45 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:193:45 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:200:27 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:202:38 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:203:43 • undefined_identifier + error • The method 'Container' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:204:34 • undefined_method + error • The method 'BoxDecoration' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:207:41 • undefined_method + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:208:38 • undefined_identifier + error • Undefined name 'BorderRadius' • lib/widgets/message_bubble.dart:209:45 • undefined_identifier + error • The method 'Text' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:214:25 • undefined_method + error • The method 'TextStyle' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:216:34 • undefined_method + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:217:36 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:218:35 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:220:39 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:221:39 • undefined_identifier + error • Undefined name 'FontWeight' • lib/widgets/message_bubble.dart:223:52 • undefined_identifier + error • Undefined name 'FontWeight' • lib/widgets/message_bubble.dart:223:70 • undefined_identifier + error • The name 'SizedBox' isn't a class • lib/widgets/message_bubble.dart:229:31 • creation_with_non_type + error • The method 'Container' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:230:25 • undefined_method + error • Undefined name 'EdgeInsets' • lib/widgets/message_bubble.dart:231:42 • undefined_identifier + error • The method 'BoxDecoration' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:233:39 • undefined_method + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:234:36 • undefined_identifier + error • Undefined name 'BorderRadius' • lib/widgets/message_bubble.dart:235:43 • undefined_identifier + error • Undefined name 'Border' • lib/widgets/message_bubble.dart:236:37 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:237:40 • undefined_identifier + error • The method 'Row' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:239:34 • undefined_method + error • The name 'Icon' isn't a class • lib/widgets/message_bubble.dart:241:37 • creation_with_non_type + error • Undefined name 'Icons' • lib/widgets/message_bubble.dart:241:42 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:242:52 • undefined_identifier + error • The name 'SizedBox' isn't a class • lib/widgets/message_bubble.dart:243:37 • creation_with_non_type + error • The name 'Expanded' isn't a class • lib/widgets/message_bubble.dart:244:37 • creation_with_non_type + error • The method 'Text' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:245:40 • undefined_method + error • The method 'TextStyle' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:247:42 • undefined_method + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:249:46 • undefined_identifier + error • Undefined name 'FontWeight' • lib/widgets/message_bubble.dart:250:51 • undefined_identifier + error • The method 'IconButton' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:253:31 • undefined_method + error • The name 'Icon' isn't a class • lib/widgets/message_bubble.dart:254:45 • creation_with_non_type + error • Undefined name 'Icons' • lib/widgets/message_bubble.dart:254:50 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:255:44 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:256:44 • undefined_identifier + error • Undefined name 'EdgeInsets' • lib/widgets/message_bubble.dart:257:42 • undefined_identifier + error • The name 'BoxConstraints' isn't a class • lib/widgets/message_bubble.dart:258:52 • creation_with_non_type + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:264:27 • undefined_identifier + error • The name 'SizedBox' isn't a class • lib/widgets/message_bubble.dart:265:31 • creation_with_non_type + error • The method 'InkWell' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:266:25 • undefined_method + error • The method 'setState' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:267:40 • undefined_method + error • The method 'Text' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:268:34 • undefined_method + error • The method 'TextStyle' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:272:36 • undefined_method + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:274:38 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:275:37 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:276:37 • undefined_identifier + error • Undefined name 'TextDecoration' • lib/widgets/message_bubble.dart:277:43 • undefined_identifier + error • The name 'SizedBox' isn't a class • lib/widgets/message_bubble.dart:282:29 • creation_with_non_type + error • The method 'Row' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:283:23 • undefined_method + error • Undefined name 'MainAxisSize' • lib/widgets/message_bubble.dart:284:39 • undefined_identifier + error • Undefined name 'MainAxisAlignment' • lib/widgets/message_bubble.dart:285:44 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:287:31 • undefined_identifier + error • The method 'Flexible' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:288:29 • undefined_method + error • The method 'Padding' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:289:38 • undefined_method + error • Undefined name 'EdgeInsets' • lib/widgets/message_bubble.dart:290:48 • undefined_identifier + error • The method 'Text' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:291:40 • undefined_method + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:292:35 • undefined_identifier + error • Undefined name 'TextAlign' • lib/widgets/message_bubble.dart:293:46 • undefined_identifier + error • Undefined name 'TextOverflow' • lib/widgets/message_bubble.dart:294:45 • undefined_identifier + error • The method 'TextStyle' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:295:42 • undefined_method + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:297:44 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:298:43 • undefined_identifier + error • Undefined name 'Theme' • lib/widgets/message_bubble.dart:299:43 • undefined_identifier + error • The method 'Text' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:305:27 • undefined_method + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:306:41 • undefined_identifier + error • The method 'TextStyle' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:307:36 • undefined_method + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:310:35 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:310:49 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:310:66 • undefined_identifier + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:313:31 • undefined_identifier + error • The name 'SizedBox' isn't a class • lib/widgets/message_bubble.dart:314:35 • creation_with_non_type + error • Undefined class 'Widget' • lib/widgets/message_bubble.dart:330:3 • undefined_class + error • Undefined name 'widget' • lib/widgets/message_bubble.dart:331:13 • undefined_identifier + error • The name 'SizedBox' isn't a class • lib/widgets/message_bubble.dart:333:22 • creation_with_non_type + error • The method 'CircularProgressIndicator' isn't defined for the type '_MessageBubbleState' • lib/widgets/message_bubble.dart:336:18 • undefined_method + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:337:20 • undefined_identifier + error • The name 'Icon' isn't a class • lib/widgets/message_bubble.dart:342:22 • creation_with_non_type + error • Undefined name 'Icons' • lib/widgets/message_bubble.dart:342:27 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:342:60 • undefined_identifier + error • The name 'Icon' isn't a class • lib/widgets/message_bubble.dart:344:22 • creation_with_non_type + error • Undefined name 'Icons' • lib/widgets/message_bubble.dart:344:27 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:344:65 • undefined_identifier + error • The name 'SizedBox' isn't a class • lib/widgets/message_bubble.dart:346:22 • creation_with_non_type + error • Classes can only extend other classes • lib/widgets/message_bubble.dart:356:29 • extends_non_class + error • Undefined class 'Color' • lib/widgets/message_bubble.dart:357:9 • undefined_class + error • Undefined class 'Gradient' • lib/widgets/message_bubble.dart:358:9 • undefined_class +warning • The method doesn't override an inherited method • lib/widgets/message_bubble.dart:364:8 • override_on_non_overriding_member + error • Undefined class 'Canvas' • lib/widgets/message_bubble.dart:364:14 • undefined_class + error • Undefined class 'Size' • lib/widgets/message_bubble.dart:364:29 • undefined_class + error • Undefined class 'Paint' • lib/widgets/message_bubble.dart:365:11 • undefined_class + error • The method 'Paint' isn't defined for the type 'BubblePainter' • lib/widgets/message_bubble.dart:365:25 • undefined_method + error • Undefined name 'PaintingStyle' • lib/widgets/message_bubble.dart:365:42 • undefined_identifier + error • Undefined name 'Rect' • lib/widgets/message_bubble.dart:369:11 • undefined_identifier + error • Undefined class 'Radius' • lib/widgets/message_bubble.dart:374:11 • undefined_class + error • Undefined name 'Radius' • lib/widgets/message_bubble.dart:374:33 • undefined_identifier + error • Undefined class 'Path' • lib/widgets/message_bubble.dart:375:11 • undefined_class + error • The method 'Path' isn't defined for the type 'BubblePainter' • lib/widgets/message_bubble.dart:375:23 • undefined_method + error • Undefined name 'RRect' • lib/widgets/message_bubble.dart:380:21 • undefined_identifier + error • Undefined name 'Radius' • lib/widgets/message_bubble.dart:388:22 • undefined_identifier + error • The method 'Path' isn't defined for the type 'BubblePainter' • lib/widgets/message_bubble.dart:392:22 • undefined_method + error • Undefined name 'Offset' • lib/widgets/message_bubble.dart:397:30 • undefined_identifier + error • Undefined name 'RRect' • lib/widgets/message_bubble.dart:400:21 • undefined_identifier + error • Undefined name 'Radius' • lib/widgets/message_bubble.dart:407:21 • undefined_identifier + error • The method 'Path' isn't defined for the type 'BubblePainter' • lib/widgets/message_bubble.dart:412:22 • undefined_method + error • Undefined name 'Offset' • lib/widgets/message_bubble.dart:417:30 • undefined_identifier + error • The name 'Offset' isn't a class • lib/widgets/message_bubble.dart:422:24 • creation_with_non_type + error • The name 'Color' isn't a class • lib/widgets/message_bubble.dart:423:42 • creation_with_non_type + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:423:85 • undefined_identifier + error • Undefined name 'Colors' • lib/widgets/message_bubble.dart:423:123 • undefined_identifier +warning • The method doesn't override an inherited method • lib/widgets/message_bubble.dart:431:8 • override_on_non_overriding_member + error • Undefined class 'CustomPainter' • lib/widgets/message_bubble.dart:431:22 • undefined_class + info • Can't use a relative path to import a library in 'lib' • test/background_logic_test.dart:2:8 • avoid_relative_lib_imports + info • Don't invoke 'print' in production code • test/background_logic_test.dart:15:5 • avoid_print + info • Don't invoke 'print' in production code • test/background_logic_test.dart:20:3 • avoid_print + info • Use 'const' for final variables initialized to a constant value • test/background_logic_test.dart:23:3 • prefer_const_declarations + info • Don't invoke 'print' in production code • test/background_logic_test.dart:26:3 • avoid_print + info • Use 'const' for final variables initialized to a constant value • test/background_logic_test.dart:27:3 • prefer_const_declarations + info • Don't invoke 'print' in production code • test/background_logic_test.dart:31:3 • avoid_print + info • Don't invoke 'print' in production code • test/background_logic_test.dart:34:3 • avoid_print + info • Use 'const' for final variables initialized to a constant value • test/background_logic_test.dart:35:3 • prefer_const_declarations + info • Don't invoke 'print' in production code • test/background_logic_test.dart:48:3 • avoid_print + info • Don't invoke 'print' in production code • test/background_logic_test.dart:50:3 • avoid_print + info • Can't use a relative path to import a library in 'lib' • test/protocol_test.dart:1:8 • avoid_relative_lib_imports + info • Don't invoke 'print' in production code • test/protocol_test.dart:5:5 • avoid_print + info • Don't invoke 'print' in production code • test/protocol_test.dart:7:5 • avoid_print + info • Don't invoke 'print' in production code • test/protocol_test.dart:13:3 • avoid_print + info • Don't invoke 'print' in production code • test/protocol_test.dart:79:3 • avoid_print + error • A value of type 'MessageBubble' can't be assigned to a parameter of type 'Widget?' in a const constructor • test/widget_test.dart:10:11 • const_constructor_param_type_mismatch + error • The argument type 'MessageBubble' can't be assigned to the parameter type 'Widget?'. • test/widget_test.dart:10:17 • argument_type_not_assignable + error • Invalid constant value • test/widget_test.dart:16:21 • invalid_constant + error • Undefined name 'MessageStatus' • test/widget_test.dart:16:21 • undefined_identifier + error • A value of type 'MessageBubble' can't be assigned to a parameter of type 'Widget?' in a const constructor • test/widget_test.dart:33:11 • const_constructor_param_type_mismatch + error • The argument type 'MessageBubble' can't be assigned to the parameter type 'Widget?'. • test/widget_test.dart:33:17 • argument_type_not_assignable + error • Invalid constant value • test/widget_test.dart:37:21 • invalid_constant + error • Undefined name 'MessageStatus' • test/widget_test.dart:37:21 • undefined_identifier + +411 issues found. (ran in 4.8s) diff --git a/analyze_results_v2.txt b/analyze_results_v2.txt new file mode 100644 index 0000000..3809021 --- /dev/null +++ b/analyze_results_v2.txt @@ -0,0 +1,80 @@ +Analyzing saba-dart... + + info • The import of 'dart:ui' is unnecessary because all of the used elements are also provided by the import of 'package:flutter/material.dart' • lib/screens/chat_screen.dart:3:8 • unnecessary_import + info • Don't invoke 'print' in production code • lib/screens/compose_screen.dart:62:7 • avoid_print + info • Don't use 'BuildContext's across async gaps • lib/screens/compose_screen.dart:129:7 • use_build_context_synchronously + info • Use interpolation to compose strings and values • lib/screens/compose_screen.dart:255:20 • prefer_interpolation_to_compose_strings + info • 'withOpacity' is deprecated and shouldn't be used. Use .withValues() to avoid precision loss • lib/screens/compose_screen.dart:415:63 • deprecated_member_use + info • 'withOpacity' is deprecated and shouldn't be used. Use .withValues() to avoid precision loss • lib/screens/compose_screen.dart:582:22 • deprecated_member_use + info • Statements in an if should be enclosed in a block • lib/screens/compose_screen.dart:639:7 • curly_braces_in_flow_control_structures + info • Statements in an if should be enclosed in a block • lib/screens/compose_screen.dart:689:11 • curly_braces_in_flow_control_structures + info • Don't use 'BuildContext's across async gaps • lib/screens/compose_screen.dart:695:15 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps • lib/screens/compose_screen.dart:700:29 • use_build_context_synchronously + info • The import of 'dart:ui' is unnecessary because all of the used elements are also provided by the import of 'package:flutter/material.dart' • lib/screens/group_chat_screen.dart:2:8 • unnecessary_import + info • Don't use 'BuildContext's across async gaps, guarded by an unrelated 'mounted' check • lib/screens/group_chat_screen.dart:226:29 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps, guarded by an unrelated 'mounted' check • lib/screens/group_chat_screen.dart:410:29 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps • lib/screens/group_chat_screen.dart:530:28 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps • lib/screens/group_chat_screen.dart:897:15 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps • lib/screens/group_chat_screen.dart:902:29 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps • lib/screens/home_screen.dart:185:11 • use_build_context_synchronously + info • Don't invoke 'print' in production code • lib/screens/home_screen.dart:244:7 • avoid_print + info • Don't use 'BuildContext's across async gaps • lib/screens/home_screen.dart:300:28 • use_build_context_synchronously + error • The named parameter 'bottom' isn't defined • lib/screens/home_screen.dart:352:9 • undefined_named_parameter + error • Expected to find ';' • lib/screens/home_screen.dart:372:7 • expected_token +warning • Dead code • lib/screens/home_screen.dart:372:8 • dead_code + error • Expected an identifier • lib/screens/home_screen.dart:372:8 • missing_identifier + error • Unexpected text ';' • lib/screens/home_screen.dart:372:8 • unexpected_token +warning • The label 'body' isn't used • lib/screens/home_screen.dart:373:7 • unused_label + error • Expected to find ';' • lib/screens/home_screen.dart:516:7 • expected_token + error • Expected an identifier • lib/screens/home_screen.dart:516:8 • missing_identifier + error • Unexpected text ';' • lib/screens/home_screen.dart:516:8 • unexpected_token +warning • The label 'floatingActionButton' isn't used • lib/screens/home_screen.dart:517:7 • unused_label + error • Expected to find ';' • lib/screens/home_screen.dart:529:7 • expected_token + error • Expected an identifier • lib/screens/home_screen.dart:529:8 • missing_identifier + error • Expected to find ';' • lib/screens/home_screen.dart:529:8 • expected_token + error • Unexpected text ';' • lib/screens/home_screen.dart:529:8 • unexpected_token + error • Expected an identifier • lib/screens/home_screen.dart:530:5 • missing_identifier + error • Unexpected text ';' • lib/screens/home_screen.dart:530:5 • unexpected_token + info • Unnecessary empty statement • lib/screens/home_screen.dart:530:6 • empty_statements + info • Use 'const' with the constructor to improve performance • lib/screens/settings_screen.dart:109:21 • prefer_const_constructors + info • Use 'const' literals as arguments to constructors of '@immutable' classes • lib/screens/settings_screen.dart:110:33 • prefer_const_literals_to_create_immutables + info • Use 'const' with the constructor to improve performance • lib/screens/settings_screen.dart:161:21 • prefer_const_constructors + info • Use 'const' literals as arguments to constructors of '@immutable' classes • lib/screens/settings_screen.dart:162:33 • prefer_const_literals_to_create_immutables + info • Use 'const' with the constructor to improve performance • lib/screens/settings_screen.dart:212:21 • prefer_const_constructors + info • Use 'const' literals as arguments to constructors of '@immutable' classes • lib/screens/settings_screen.dart:213:33 • prefer_const_literals_to_create_immutables + info • 'activeColor' is deprecated and shouldn't be used. Use activeThumbColor instead. This feature was deprecated after v3.31.0-2.0.pre • lib/screens/settings_screen.dart:241:27 • deprecated_member_use + info • 'value' is deprecated and shouldn't be used. Use component accessors like .r or .g, or toARGB32 for an explicit conversion • lib/screens/settings_screen.dart:286:49 • deprecated_member_use + info • 'value' is deprecated and shouldn't be used. Use component accessors like .r or .g, or toARGB32 for an explicit conversion • lib/screens/settings_screen.dart:286:64 • deprecated_member_use + info • 'value' is deprecated and shouldn't be used. Use component accessors like .r or .g, or toARGB32 for an explicit conversion • lib/screens/settings_screen.dart:291:57 • deprecated_member_use + info • 'withOpacity' is deprecated and shouldn't be used. Use .withValues() to avoid precision loss • lib/screens/settings_screen.dart:312:30 • deprecated_member_use + error • The argument type 'CardTheme' can't be assigned to the parameter type 'CardThemeData?'. • lib/utils/app_theme.dart:81:18 • argument_type_not_assignable + info • The private field _memoryCache could be 'final' • lib/utils/contact_helper.dart:5:30 • prefer_final_fields + info • Don't invoke 'print' in production code • lib/utils/contact_helper.dart:19:7 • avoid_print + info • Don't invoke 'print' in production code • lib/utils/crypto_helper.dart:29:7 • avoid_print +warning • Unused import: '../utils/app_theme.dart' • lib/widgets/message_bubble.dart:4:8 • unused_import + info • Use 'const' with the constructor to improve performance • lib/widgets/message_bubble.dart:141:29 • prefer_const_constructors + info • Use 'const' literals as arguments to constructors of '@immutable' classes • lib/widgets/message_bubble.dart:142:39 • prefer_const_literals_to_create_immutables + info • 'withOpacity' is deprecated and shouldn't be used. Use .withValues() to avoid precision loss • lib/widgets/message_bubble.dart:235:49 • deprecated_member_use + info • Use 'const' for final variables initialized to a constant value • lib/widgets/message_bubble.dart:375:5 • prefer_const_declarations + info • Can't use a relative path to import a library in 'lib' • test/background_logic_test.dart:2:8 • avoid_relative_lib_imports + info • Don't invoke 'print' in production code • test/background_logic_test.dart:15:5 • avoid_print + info • Don't invoke 'print' in production code • test/background_logic_test.dart:20:3 • avoid_print + info • Use 'const' for final variables initialized to a constant value • test/background_logic_test.dart:23:3 • prefer_const_declarations + info • Don't invoke 'print' in production code • test/background_logic_test.dart:26:3 • avoid_print + info • Use 'const' for final variables initialized to a constant value • test/background_logic_test.dart:27:3 • prefer_const_declarations + info • Don't invoke 'print' in production code • test/background_logic_test.dart:31:3 • avoid_print + info • Don't invoke 'print' in production code • test/background_logic_test.dart:34:3 • avoid_print + info • Use 'const' for final variables initialized to a constant value • test/background_logic_test.dart:35:3 • prefer_const_declarations + info • Don't invoke 'print' in production code • test/background_logic_test.dart:48:3 • avoid_print + info • Don't invoke 'print' in production code • test/background_logic_test.dart:50:3 • avoid_print + info • Can't use a relative path to import a library in 'lib' • test/protocol_test.dart:1:8 • avoid_relative_lib_imports + info • Don't invoke 'print' in production code • test/protocol_test.dart:5:5 • avoid_print + info • Don't invoke 'print' in production code • test/protocol_test.dart:7:5 • avoid_print + info • Don't invoke 'print' in production code • test/protocol_test.dart:13:3 • avoid_print + info • Don't invoke 'print' in production code • test/protocol_test.dart:79:3 • avoid_print + error • Invalid constant value • test/widget_test.dart:16:21 • invalid_constant + error • Undefined name 'MessageStatus' • test/widget_test.dart:16:21 • undefined_identifier + error • Invalid constant value • test/widget_test.dart:37:21 • invalid_constant + error • Undefined name 'MessageStatus' • test/widget_test.dart:37:21 • undefined_identifier + +76 issues found. (ran in 6.4s) diff --git a/analyze_results_v3.txt b/analyze_results_v3.txt new file mode 100644 index 0000000..49e5e75 --- /dev/null +++ b/analyze_results_v3.txt @@ -0,0 +1,62 @@ +Analyzing saba-dart... + + info • The import of 'dart:ui' is unnecessary because all of the used elements are also provided by the import of 'package:flutter/material.dart' • lib/screens/chat_screen.dart:3:8 • unnecessary_import + info • Don't invoke 'print' in production code • lib/screens/compose_screen.dart:62:7 • avoid_print + info • Don't use 'BuildContext's across async gaps • lib/screens/compose_screen.dart:129:7 • use_build_context_synchronously + info • Use interpolation to compose strings and values • lib/screens/compose_screen.dart:255:20 • prefer_interpolation_to_compose_strings + info • 'withOpacity' is deprecated and shouldn't be used. Use .withValues() to avoid precision loss • lib/screens/compose_screen.dart:415:63 • deprecated_member_use + info • 'withOpacity' is deprecated and shouldn't be used. Use .withValues() to avoid precision loss • lib/screens/compose_screen.dart:582:22 • deprecated_member_use + info • Statements in an if should be enclosed in a block • lib/screens/compose_screen.dart:639:7 • curly_braces_in_flow_control_structures + info • Statements in an if should be enclosed in a block • lib/screens/compose_screen.dart:689:11 • curly_braces_in_flow_control_structures + info • Don't use 'BuildContext's across async gaps • lib/screens/compose_screen.dart:695:15 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps • lib/screens/compose_screen.dart:700:29 • use_build_context_synchronously + info • The import of 'dart:ui' is unnecessary because all of the used elements are also provided by the import of 'package:flutter/material.dart' • lib/screens/group_chat_screen.dart:2:8 • unnecessary_import + info • Don't use 'BuildContext's across async gaps, guarded by an unrelated 'mounted' check • lib/screens/group_chat_screen.dart:226:29 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps, guarded by an unrelated 'mounted' check • lib/screens/group_chat_screen.dart:410:29 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps • lib/screens/group_chat_screen.dart:530:28 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps • lib/screens/group_chat_screen.dart:897:15 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps • lib/screens/group_chat_screen.dart:902:29 • use_build_context_synchronously + info • Don't use 'BuildContext's across async gaps • lib/screens/home_screen.dart:185:11 • use_build_context_synchronously + info • Don't invoke 'print' in production code • lib/screens/home_screen.dart:244:7 • avoid_print + info • Don't use 'BuildContext's across async gaps • lib/screens/home_screen.dart:300:28 • use_build_context_synchronously + info • Use 'const' with the constructor to improve performance • lib/screens/settings_screen.dart:109:21 • prefer_const_constructors + info • Use 'const' literals as arguments to constructors of '@immutable' classes • lib/screens/settings_screen.dart:110:33 • prefer_const_literals_to_create_immutables + info • Use 'const' with the constructor to improve performance • lib/screens/settings_screen.dart:161:21 • prefer_const_constructors + info • Use 'const' literals as arguments to constructors of '@immutable' classes • lib/screens/settings_screen.dart:162:33 • prefer_const_literals_to_create_immutables + info • Use 'const' with the constructor to improve performance • lib/screens/settings_screen.dart:212:21 • prefer_const_constructors + info • Use 'const' literals as arguments to constructors of '@immutable' classes • lib/screens/settings_screen.dart:213:33 • prefer_const_literals_to_create_immutables + info • 'activeColor' is deprecated and shouldn't be used. Use activeThumbColor instead. This feature was deprecated after v3.31.0-2.0.pre • lib/screens/settings_screen.dart:241:27 • deprecated_member_use + info • 'value' is deprecated and shouldn't be used. Use component accessors like .r or .g, or toARGB32 for an explicit conversion • lib/screens/settings_screen.dart:286:49 • deprecated_member_use + info • 'value' is deprecated and shouldn't be used. Use component accessors like .r or .g, or toARGB32 for an explicit conversion • lib/screens/settings_screen.dart:286:64 • deprecated_member_use + info • 'value' is deprecated and shouldn't be used. Use component accessors like .r or .g, or toARGB32 for an explicit conversion • lib/screens/settings_screen.dart:291:57 • deprecated_member_use + info • 'withOpacity' is deprecated and shouldn't be used. Use .withValues() to avoid precision loss • lib/screens/settings_screen.dart:312:30 • deprecated_member_use + info • The private field _memoryCache could be 'final' • lib/utils/contact_helper.dart:5:30 • prefer_final_fields + info • Don't invoke 'print' in production code • lib/utils/contact_helper.dart:19:7 • avoid_print + info • Don't invoke 'print' in production code • lib/utils/crypto_helper.dart:29:7 • avoid_print +warning • Unused import: '../utils/app_theme.dart' • lib/widgets/message_bubble.dart:4:8 • unused_import + info • Use 'const' with the constructor to improve performance • lib/widgets/message_bubble.dart:141:29 • prefer_const_constructors + info • Use 'const' literals as arguments to constructors of '@immutable' classes • lib/widgets/message_bubble.dart:142:39 • prefer_const_literals_to_create_immutables + info • 'withOpacity' is deprecated and shouldn't be used. Use .withValues() to avoid precision loss • lib/widgets/message_bubble.dart:235:49 • deprecated_member_use + info • Use 'const' for final variables initialized to a constant value • lib/widgets/message_bubble.dart:375:5 • prefer_const_declarations + info • Can't use a relative path to import a library in 'lib' • test/background_logic_test.dart:2:8 • avoid_relative_lib_imports + info • Don't invoke 'print' in production code • test/background_logic_test.dart:15:5 • avoid_print + info • Don't invoke 'print' in production code • test/background_logic_test.dart:20:3 • avoid_print + info • Use 'const' for final variables initialized to a constant value • test/background_logic_test.dart:23:3 • prefer_const_declarations + info • Don't invoke 'print' in production code • test/background_logic_test.dart:26:3 • avoid_print + info • Use 'const' for final variables initialized to a constant value • test/background_logic_test.dart:27:3 • prefer_const_declarations + info • Don't invoke 'print' in production code • test/background_logic_test.dart:31:3 • avoid_print + info • Don't invoke 'print' in production code • test/background_logic_test.dart:34:3 • avoid_print + info • Use 'const' for final variables initialized to a constant value • test/background_logic_test.dart:35:3 • prefer_const_declarations + info • Don't invoke 'print' in production code • test/background_logic_test.dart:48:3 • avoid_print + info • Don't invoke 'print' in production code • test/background_logic_test.dart:50:3 • avoid_print + info • Can't use a relative path to import a library in 'lib' • test/protocol_test.dart:1:8 • avoid_relative_lib_imports + info • Don't invoke 'print' in production code • test/protocol_test.dart:5:5 • avoid_print + info • Don't invoke 'print' in production code • test/protocol_test.dart:7:5 • avoid_print + info • Don't invoke 'print' in production code • test/protocol_test.dart:13:3 • avoid_print + info • Don't invoke 'print' in production code • test/protocol_test.dart:79:3 • avoid_print + error • Invalid constant value • test/widget_test.dart:16:21 • invalid_constant + error • Undefined name 'MessageStatus' • test/widget_test.dart:16:21 • undefined_identifier + error • Invalid constant value • test/widget_test.dart:37:21 • invalid_constant + error • Undefined name 'MessageStatus' • test/widget_test.dart:37:21 • undefined_identifier + +58 issues found. (ran in 6.1s) diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..2a1577b --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,49 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.example.saba_secure_sms" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + isCoreLibraryDesugaringEnabled = true + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_1_8.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.example.saba_secure_sms" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} + +dependencies { + coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.0.4") +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..7661d06 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/example/saba_secure_sms/MainActivity.kt b/android/app/src/main/kotlin/com/example/saba_secure_sms/MainActivity.kt new file mode 100644 index 0000000..053ccd1 --- /dev/null +++ b/android/app/src/main/kotlin/com/example/saba_secure_sms/MainActivity.kt @@ -0,0 +1,140 @@ +package com.example.saba_secure_sms + +import android.app.role.RoleManager +import android.content.Context +import android.content.Intent +import android.os.Build +import android.provider.Telephony +import android.widget.Toast +import android.provider.Settings +import android.content.ComponentName +import android.content.pm.PackageManager +import io.flutter.embedding.android.FlutterActivity +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.MethodChannel + +class MainActivity : FlutterActivity() { + private val CHANNEL = "com.example.saba_secure_sms/sms_role" + + override fun configureFlutterEngine(flutterEngine: FlutterEngine) { + super.configureFlutterEngine(flutterEngine) + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result -> + when (call.method) { + "isDefaultSmsApp" -> { + result.success(isDefaultSmsApp()) + } + "requestDefaultSmsApp" -> { + val status = requestDefaultSmsApp() + result.success(status) + } + "openDefaultAppsSettings" -> { + openDefaultAppsSettings() + result.success(true) + } + "setStealthMode" -> { + val enabled = call.argument("enabled") ?: false + setStealthMode(enabled) + result.success(true) + } + "getStealthMode" -> { + result.success(getStealthMode()) + } + else -> { + result.notImplemented() + } + } + } + } + + private fun isDefaultSmsApp(): Boolean { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + val packageName = packageName + val defaultSmsPackage = Telephony.Sms.getDefaultSmsPackage(this) + packageName == defaultSmsPackage + } else { + false + } + } + + private fun requestDefaultSmsApp(): String { + if (isDefaultSmsApp()) return "already_default" + + return try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + val roleManager = getSystemService(Context.ROLE_SERVICE) as RoleManager + if (roleManager.isRoleAvailable(RoleManager.ROLE_SMS)) { + if (!roleManager.isRoleHeld(RoleManager.ROLE_SMS)) { + val intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_SMS) + startActivityForResult(intent, 1001) + "requesting_role" + } else { + "role_already_held" + } + } else { + "role_not_available" + } + } else { + val intent = Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT) + intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, packageName) + startActivity(intent) + "requesting_intent" + } + } catch (e: Exception) { + Toast.makeText(this, "Error requesting SMS role: ${e.message}", Toast.LENGTH_LONG).show() + "error: ${e.message}" + } + } + + private fun openDefaultAppsSettings() { + try { + val intent = Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS) + startActivity(intent) + } catch (e: Exception) { + try { + val intent = Intent(Settings.ACTION_SETTINGS) + startActivity(intent) + } catch (e2: Exception) { + Toast.makeText(this, "عدم دسترسی به تنظیمات سیستم", Toast.LENGTH_SHORT).show() + } + } + } + + private fun setStealthMode(enabled: Boolean) { + val packageManager = packageManager + val sabaComponent = ComponentName(this, "com.example.saba_secure_sms.MainActivitySaba") + val calcComponent = ComponentName(this, "com.example.saba_secure_sms.MainActivityCalculator") + + if (enabled) { + // Enable Calculator, Disable Saba + packageManager.setComponentEnabledSetting(calcComponent, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP) + packageManager.setComponentEnabledSetting(sabaComponent, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0) // Setting 0 (no flag) will kill the app to force refresh launcher + } else { + // Enable Saba, Disable Calculator + packageManager.setComponentEnabledSetting(sabaComponent, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP) + packageManager.setComponentEnabledSetting(calcComponent, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0) + } + } + + private fun getStealthMode(): Boolean { + val calcComponent = ComponentName(this, "com.example.saba_secure_sms.MainActivityCalculator") + val status = packageManager.getComponentEnabledSetting(calcComponent) + return status == PackageManager.COMPONENT_ENABLED_STATE_ENABLED + } +} + +// Required components for Default SMS App eligibility +class SmsDeliverReceiver : android.content.BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + // Handled by another_telephony plugin via AndroidManifest entry pointing to its receiver + } +} + +class MmsReceiver : android.content.BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + // MMS support not fully implemented but required for role eligibility + } +} + +class HeadlessSmsSendService : android.app.Service() { + override fun onBind(intent: Intent?): android.os.IBinder? = null +} diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_calc.xml b/android/app/src/main/res/drawable/ic_calc.xml new file mode 100644 index 0000000..51968d5 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_calc.xml @@ -0,0 +1,23 @@ + + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..c4ecb6c Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..c2aec7d Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..ae27e47 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..a6aaed3 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..f82b3a5 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values-fa/strings.xml b/android/app/src/main/res/values-fa/strings.xml new file mode 100644 index 0000000..878ee1a --- /dev/null +++ b/android/app/src/main/res/values-fa/strings.xml @@ -0,0 +1,4 @@ + + + صبا + diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..1483177 --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + + Saba + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..a3d26cc --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,43 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} + +subprojects { + fun applyNamespace() { + if (project.hasProperty("android")) { + val extension = project.extensions.findByName("android") + if (extension is com.android.build.gradle.BaseExtension) { + if (extension.namespace == null) { + extension.namespace = project.group.toString() + } + } + } + } + + if (project.state.executed) { + applyNamespace() + } else { + afterEvaluate { applyNamespace() } + } +} diff --git a/android/build/reports/problems/problems-report.html b/android/build/reports/problems/problems-report.html new file mode 100644 index 0000000..2d7c827 --- /dev/null +++ b/android/build/reports/problems/problems-report.html @@ -0,0 +1,663 @@ + + + + + + + + + + + + + Gradle Configuration Cache + + + +
+ +
+ Loading... +
+ + + + + + diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..fbee1d8 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e4ef43f --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..ca7fe06 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.2.20" apply false +} + +include(":app") diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..391a902 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..c7455fc --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,620 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.sabaSecureSms; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.sabaSecureSms.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.sabaSecureSms.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.sabaSecureSms.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.sabaSecureSms; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.sabaSecureSms; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..e3773d4 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..c30b367 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,16 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..e882448 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..2d70fee Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..6682946 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..7167c41 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..a7efba4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..5847287 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..a2b4e21 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..6682946 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..08c01ee Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..bdc7169 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png new file mode 100644 index 0000000..e31c496 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png new file mode 100644 index 0000000..95b8f88 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png new file mode 100644 index 0000000..bf84f43 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png new file mode 100644 index 0000000..d3dcaf2 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..bdc7169 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..acbe8dc Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png new file mode 100644 index 0000000..c4ecb6c Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png new file mode 100644 index 0000000..a6aaed3 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..c10e86b Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..63e854d Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..d280637 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..d27cd36 --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,70 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Saba Secure Sms + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + saba_secure_sms + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/ios/Runner/SceneDelegate.swift b/ios/Runner/SceneDelegate.swift new file mode 100644 index 0000000..b9ce8ea --- /dev/null +++ b/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..aed7b1d --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,59 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_windowmanager_plus/flutter_windowmanager_plus.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'screens/splash_screen.dart'; +import 'utils/app_lock_service.dart'; +import 'utils/app_theme.dart'; +import 'widgets/app_lock_overlay.dart'; + +// Global notifier for the primary theme color +final ValueNotifier themeNotifier = + ValueNotifier(const Color(0xFF3F51B5)); + +void main() async { + WidgetsFlutterBinding.ensureInitialized(); + await FlutterWindowManagerPlus.addFlags(FlutterWindowManagerPlus.FLAG_SECURE); + + // Load saved theme color + final prefs = await SharedPreferences.getInstance(); + final colorValue = prefs.getInt('primary_color_value'); + if (colorValue != null) { + themeNotifier.value = Color(colorValue); + } + + await AppLockService.instance.init(); + + runApp(const MyApp()); +} + +class MyApp extends StatelessWidget { + const MyApp({super.key}); + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder( + valueListenable: themeNotifier, + builder: (context, primaryColor, _) { + return MaterialApp( + debugShowCheckedModeBanner: false, + title: 'saba', + theme: AppTheme.neoDarkTheme(primaryColor), + builder: (context, child) => AppLockOverlay( + child: child ?? const SizedBox.shrink(), + ), + localizationsDelegates: const [ + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: const [ + Locale('fa', 'IR'), + ], + locale: const Locale('fa', 'IR'), + home: const SplashScreen(), + ); + }, + ); + } +} diff --git a/lib/models/chat_model.dart b/lib/models/chat_model.dart new file mode 100644 index 0000000..b197260 --- /dev/null +++ b/lib/models/chat_model.dart @@ -0,0 +1,41 @@ +enum MessageStatus { sending, sent, received, failed, ignored } + +class ChatModel { + int? id; + String? localId; + String body; + String? rawBody; + String? rawViewBody; + String? encryptedPayload; + String? statusLabel; + String? packetId; + String? packetMode; + String? rawPacketId; + int date; + bool isMe; + MessageStatus status; + bool isSecure; + bool canRetryDecryption; + bool isRead; + bool isPendingMultipart; + + ChatModel({ + this.id, + this.localId, + required this.body, + this.rawBody, + this.rawViewBody, + this.encryptedPayload, + this.statusLabel, + this.packetId, + this.packetMode, + this.rawPacketId, + required this.date, + required this.isMe, + required this.status, + this.isSecure = false, + this.canRetryDecryption = false, + this.isPendingMultipart = false, + this.isRead = true, + }); +} diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart new file mode 100644 index 0000000..11f6fbe --- /dev/null +++ b/lib/screens/chat_screen.dart @@ -0,0 +1,2232 @@ +import 'dart:async'; +import 'dart:math'; +import 'dart:ui'; + +import 'package:another_telephony/telephony.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_contacts/flutter_contacts.dart'; +import 'package:permission_handler/permission_handler.dart'; + +import '../models/chat_model.dart'; +import '../utils/app_theme.dart'; +import '../utils/contact_helper.dart'; +import '../utils/database_helper.dart'; +import '../utils/message_processor.dart'; +import '../utils/protocol_helper.dart'; +import '../utils/secure_messaging_service.dart'; +import '../widgets/message_bubble.dart'; + +class MeshBackgroundPainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + // Optimization for Raspberry Pi 3: Use RadialGradient instead of MaskFilter blur + // which is often hardware-accelerated and much cheaper than multi-pass blur. + + final Paint paint1 = Paint() + ..shader = RadialGradient( + colors: [ + const Color(0xFF7000FF).withValues(alpha: 0.12), + const Color(0xFF7000FF).withValues(alpha: 0.0), + ], + ).createShader(Rect.fromCircle( + center: Offset(size.width * 0.2, size.height * 0.15), radius: 300)); + + canvas.drawCircle( + Offset(size.width * 0.2, size.height * 0.15), 300, paint1); + + final Paint paint2 = Paint() + ..shader = RadialGradient( + colors: [ + const Color(0xFF00D2FF).withValues(alpha: 0.1), + const Color(0xFF00D2FF).withValues(alpha: 0.0), + ], + ).createShader(Rect.fromCircle( + center: Offset(size.width * 0.8, size.height * 0.8), radius: 400)); + + canvas.drawCircle(Offset(size.width * 0.8, size.height * 0.8), 400, paint2); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} + +class _MessageCandidate { + final ChatModel message; + final bool preferCandidate; + + const _MessageCandidate( + this.message, { + this.preferCandidate = false, + }); +} + +class ChatScreen extends StatefulWidget { + final String address; + + const ChatScreen({super.key, required this.address}); + + @override + State createState() => _ChatScreenState(); +} + +class _ChatScreenState extends State { + final Telephony telephony = Telephony.instance; + static const platform = MethodChannel('com.example.saba/sim_cards'); + static const nativeChannel = MethodChannel('com.example.saba/sms_native'); + static const asymmetricModeLabel = "رمزنگاری غیر متقارن (طولانی‌تر و امن‌تر)"; + + final TextEditingController _msgController = TextEditingController(); + Color get primaryColor => Theme.of(context).primaryColor; + Color get backgroundColor => const Color(0xFFF5F7FA); + + final ScrollController _scrollController = ScrollController(); + final ValueNotifier> _messageNotifier = ValueNotifier([]); + + List get messages => _messageNotifier.value; + set messages(List val) => _messageNotifier.value = val; + + List> _simCards = []; + Map? _selectedSim; + bool _loadingSims = true; + String displayName = ""; + String _selectedSecurityLevel = 'normal'; + Map? contactInfo; + StreamSubscription? _messageSubscription; + String? _dismissedBannerText; + bool _isLoading = false; + Timer? _debounceTimer; + + int _offset = 0; + static const int _limit = 25; + static const int _liveMessageGraceMs = 15000; + bool _hasMore = true; + + int _compareMessages(ChatModel a, ChatModel b) { + final dateComp = b.date.compareTo(a.date); + if (dateComp != 0) return dateComp; + + final idComp = (b.id ?? -1).compareTo(a.id ?? -1); + if (idComp != 0) return idComp; + + final packetComp = (_packetKey(b.packetId, b.packetMode) ?? '') + .compareTo(_packetKey(a.packetId, a.packetMode) ?? ''); + if (packetComp != 0) return packetComp; + + final isMeComp = (b.isMe ? 1 : 0).compareTo(a.isMe ? 1 : 0); + if (isMeComp != 0) return isMeComp; + + final bodyComp = (b.rawBody ?? b.body).compareTo(a.rawBody ?? a.body); + if (bodyComp != 0) return bodyComp; + + return b.status.index.compareTo(a.status.index); + } + + int _messageQuality(ChatModel message) { + var score = 0; + if (message.id != null) score += 40; + if (_packetKey(message.packetId, message.packetMode) != null) score += 8; + if ((message.rawBody?.isNotEmpty ?? false)) score += 3; + if ((message.rawViewBody?.isNotEmpty ?? false)) score += 2; + if ((message.encryptedPayload?.isNotEmpty ?? false)) score += 4; + if (message.isSecure) score += 3; + if (!message.isPendingMultipart) score += 6; + if (message.status == MessageStatus.sent || + message.status == MessageStatus.received) { + score += 2; + } + if (message.status == MessageStatus.sending) score -= 2; + if (message.status == MessageStatus.failed) score -= 1; + if (_isSecurePlaceholderBody(message.body)) score -= 1; + return score; + } + + void _publishMessages(List items) { + final sorted = List.from(items)..sort(_compareMessages); + _messageNotifier.value = sorted; + } + + String? _packetKey(String? packetId, [String? packetMode]) { + if (packetId == null || packetId.isEmpty) return null; + final mode = + (packetMode == null || packetMode.isEmpty) ? 'UNK' : packetMode; + return '$mode::$packetId'; + } + + ChatModel _cloneMessage(ChatModel source) { + return ChatModel( + id: source.id, + localId: source.localId, + body: source.body, + rawBody: source.rawBody, + rawViewBody: source.rawViewBody, + encryptedPayload: source.encryptedPayload, + statusLabel: source.statusLabel, + packetId: source.packetId, + packetMode: source.packetMode, + rawPacketId: source.rawPacketId, + date: source.date, + isMe: source.isMe, + status: source.status, + isSecure: source.isSecure, + canRetryDecryption: source.canRetryDecryption, + isPendingMultipart: source.isPendingMultipart, + isRead: source.isRead, + ); + } + + String _fallbackMessageKey(ChatModel message) { + return 'fallback::${message.isMe ? 1 : 0}::${message.date}::${message.body.hashCode}'; + } + + String? _normalizedPayloadSignature(String? payload) { + final normalized = (payload ?? '').replaceAll(RegExp(r'\s+'), '').trim(); + return normalized.isEmpty ? null : normalized; + } + + String? _contentSignature(ChatModel message) { + final rawSignature = (message.rawBody ?? '').trim(); + final bodySignature = message.body.trim(); + final contentSignature = + rawSignature.isNotEmpty ? rawSignature : bodySignature; + if (contentSignature.isEmpty || + _isSecurePlaceholderBody(contentSignature) || + _isProgressBody(contentSignature)) { + return null; + } + return contentSignature; + } + + int _timeBucket(int date, [int bucketMs = 5000]) { + if (date <= 0) return 0; + return date ~/ bucketMs; + } + + List _messageAliases(ChatModel message) { + final aliases = {}; + if (message.localId != null && message.localId!.isNotEmpty) { + aliases.add('local::${message.localId}'); + } + if (message.id != null) { + aliases.add('db::${message.id}'); + } + + final packetKey = _packetKey(message.packetId, message.packetMode); + if (packetKey != null) { + aliases.add('packet::$packetKey'); + } + + final payload = _normalizedPayloadSignature(message.encryptedPayload); + if (payload != null) { + final mode = (message.packetMode ?? 'SEC').trim(); + aliases.add('payload::$mode::${message.isMe ? 1 : 0}::$payload'); + aliases.add('payload::$mode::$payload'); + } + + final rawBody = (message.rawBody ?? '').trim(); + if (rawBody.isNotEmpty) { + aliases.add('raw::${message.isMe ? 1 : 0}::$rawBody'); + final parsed = ProtocolHelper.parseMessage(rawBody); + final rawPayload = + _normalizedPayloadSignature(parsed['payload'] as String?); + final rawType = parsed['type'] as String? ?? 'plain'; + if (rawPayload != null) { + final mode = (message.packetMode ?? + (rawType == 'asym' || rawType == 'afrag' ? 'AE' : 'SYM')) + .trim(); + aliases.add('payload::$mode::${message.isMe ? 1 : 0}::$rawPayload'); + aliases.add('payload::$mode::$rawPayload'); + } + } + + final content = _contentSignature(message); + if (content != null) { + aliases.add( + 'body::${message.isMe ? 1 : 0}::${_timeBucket(message.date)}::$content'); + } + + return aliases.toList(growable: false); + } + + bool _hasAliasOverlap(Set a, Set b) { + for (final key in a) { + if (b.contains(key)) return true; + } + return false; + } + + bool _isProgressBody(String body) { + return body.contains('در حال دریافت قطعات') || + body.contains('در حال ارسال قطعات') || + body.contains('باقی قطعات پیام نرسیده‌اند'); + } + + String _pickPreferredBody(String primaryBody, String secondaryBody) { + final primary = primaryBody.trim(); + final secondary = secondaryBody.trim(); + if (primary.isEmpty) return secondaryBody; + if (secondary.isEmpty) return primaryBody; + + final primaryProgress = _isProgressBody(primaryBody); + final secondaryProgress = _isProgressBody(secondaryBody); + if (primaryProgress != secondaryProgress) { + return primaryProgress ? secondaryBody : primaryBody; + } + + final primaryPlaceholder = _isSecurePlaceholderBody(primaryBody); + final secondaryPlaceholder = _isSecurePlaceholderBody(secondaryBody); + if (primaryPlaceholder != secondaryPlaceholder) { + return primaryPlaceholder ? secondaryBody : primaryBody; + } + + return primary.length >= secondary.length ? primaryBody : secondaryBody; + } + + String? _pickPreferredString(String? primary, String? secondary) { + final a = (primary ?? '').trim(); + final b = (secondary ?? '').trim(); + if (a.isEmpty) return b.isEmpty ? null : secondary; + if (b.isEmpty) return primary; + return a.length >= b.length ? primary : secondary; + } + + MessageStatus _pickPreferredStatus(ChatModel primary, ChatModel secondary) { + final primaryFinal = primary.status == MessageStatus.sent || + primary.status == MessageStatus.received; + final secondaryFinal = secondary.status == MessageStatus.sent || + secondary.status == MessageStatus.received; + if (primaryFinal != secondaryFinal) { + return primaryFinal ? primary.status : secondary.status; + } + if (primary.status == MessageStatus.failed && + secondary.status != MessageStatus.failed) { + return secondary.status; + } + if (secondary.status == MessageStatus.failed && + primary.status != MessageStatus.failed) { + return primary.status; + } + if (primary.status == MessageStatus.sending && + secondary.status != MessageStatus.sending) { + return secondary.status; + } + return primary.status; + } + + ChatModel _mergeModels( + ChatModel existing, + ChatModel candidate, { + bool preferCandidate = false, + }) { + final candidateQuality = _messageQuality(candidate); + final existingQuality = _messageQuality(existing); + final useCandidateAsPrimary = preferCandidate || + candidateQuality > existingQuality || + (candidateQuality == existingQuality && + _compareMessages(candidate, existing) < 0); + + final primary = useCandidateAsPrimary ? candidate : existing; + final secondary = useCandidateAsPrimary ? existing : candidate; + + final merged = ChatModel( + id: primary.id ?? secondary.id, + localId: primary.localId ?? secondary.localId, + body: _pickPreferredBody(primary.body, secondary.body), + rawBody: _pickPreferredString(primary.rawBody, secondary.rawBody), + rawViewBody: + _pickPreferredString(primary.rawViewBody, secondary.rawViewBody), + encryptedPayload: _pickPreferredString( + primary.encryptedPayload, secondary.encryptedPayload), + statusLabel: + _pickPreferredString(primary.statusLabel, secondary.statusLabel), + packetId: _pickPreferredString(primary.packetId, secondary.packetId), + packetMode: + _pickPreferredString(primary.packetMode, secondary.packetMode), + rawPacketId: + _pickPreferredString(primary.rawPacketId, secondary.rawPacketId), + date: primary.date == 0 + ? secondary.date + : (secondary.date == 0 + ? primary.date + : min(primary.date, secondary.date)), + isMe: primary.isMe, + status: _pickPreferredStatus(primary, secondary), + isSecure: primary.isSecure || + secondary.isSecure || + (primary.packetMode ?? secondary.packetMode) != null || + (primary.encryptedPayload ?? secondary.encryptedPayload) != null, + canRetryDecryption: + primary.canRetryDecryption || secondary.canRetryDecryption, + isPendingMultipart: + primary.isPendingMultipart || secondary.isPendingMultipart, + isRead: primary.isRead && secondary.isRead, + ); + + if (!_isProgressBody(merged.body)) { + merged.isPendingMultipart = false; + if (merged.statusLabel != null && + (merged.status == MessageStatus.sent || + merged.status == MessageStatus.received) && + !_isSecurePlaceholderBody(merged.body)) { + merged.statusLabel = null; + } + } + + if (merged.isSecure || + merged.packetMode != null || + (merged.rawBody?.isNotEmpty ?? false)) { + _enrichSecureModel(merged); + } else { + merged.rawViewBody ??= _buildRawViewBody( + body: merged.body, + rawBody: merged.rawBody, + encryptedPayload: merged.encryptedPayload, + packetMode: merged.packetMode, + isSecure: merged.isSecure, + ); + } + + return merged; + } + + List _reconcileCandidates(List<_MessageCandidate> candidates) { + final mergedMessages = []; + final aliasSets = >[]; + + for (final entry in candidates) { + final prepared = _cloneMessage(entry.message); + if (prepared.isSecure || + prepared.packetMode != null || + (prepared.rawBody?.isNotEmpty ?? false)) { + _enrichSecureModel(prepared); + } else { + prepared.rawViewBody ??= _buildRawViewBody( + body: prepared.body, + rawBody: prepared.rawBody, + encryptedPayload: prepared.encryptedPayload, + packetMode: prepared.packetMode, + isSecure: prepared.isSecure, + ); + } + + final workingAliases = _messageAliases(prepared).toSet(); + final matches = []; + for (var i = 0; i < aliasSets.length; i++) { + if (_hasAliasOverlap(aliasSets[i], workingAliases)) { + matches.add(i); + } + } + + if (matches.isEmpty) { + mergedMessages.add(prepared); + aliasSets.add( + workingAliases.isEmpty + ? {_fallbackMessageKey(prepared)} + : workingAliases, + ); + continue; + } + + var combined = prepared; + for (final index in matches.reversed) { + combined = _mergeModels( + mergedMessages[index], + combined, + preferCandidate: entry.preferCandidate, + ); + mergedMessages.removeAt(index); + aliasSets.removeAt(index); + } + + final combinedAliases = _messageAliases(combined).toSet() + ..addAll(workingAliases); + mergedMessages.add(combined); + aliasSets.add( + combinedAliases.isEmpty + ? {_fallbackMessageKey(combined)} + : combinedAliases, + ); + } + + mergedMessages.sort(_compareMessages); + return mergedMessages; + } + + void _replaceMessagesWithCandidates(List<_MessageCandidate> candidates) { + _publishMessages(_reconcileCandidates(candidates)); + } + + String? _findOutgoingDraftLocalId(ChatModel candidate) { + if (!candidate.isMe) return null; + + ChatModel? best; + var bestDelta = 1 << 30; + for (final message in messages) { + if (message.localId == null || + !message.isMe || + message.id != null || + (message.status != MessageStatus.sending && + message.status != MessageStatus.failed && + !message.isPendingMultipart)) { + continue; + } + + if (candidate.packetMode != null && + message.packetMode != null && + candidate.packetMode != message.packetMode) { + continue; + } + + final delta = (candidate.date - message.date).abs(); + if (delta > 30000 || delta >= bestDelta) continue; + + best = message; + bestDelta = delta; + } + return best?.localId; + } + + bool _shouldKeepTransientMessageDuringReload(ChatModel message) { + if (message.id != null) return false; + final ageMs = DateTime.now().millisecondsSinceEpoch - message.date; + if (ageMs <= _liveMessageGraceMs) return true; + if (message.status == MessageStatus.failed || + message.status == MessageStatus.sending || + message.isPendingMultipart) { + return true; + } + return message.isMe; + } + + bool _shouldPreferInMemoryMessage(ChatModel message) { + return message.id == null && + ((DateTime.now().millisecondsSinceEpoch - message.date) <= + _liveMessageGraceMs || + message.status == MessageStatus.failed || + message.status == MessageStatus.sending || + message.isPendingMultipart || + message.isMe); + } + + String? _buildRawViewBody({ + required String body, + String? rawBody, + String? encryptedPayload, + String? packetMode, + bool isSecure = false, + }) { + // If it's a secure message, we want to show the underlying protocol string + if (encryptedPayload != null && encryptedPayload.isNotEmpty) { + switch (packetMode) { + case 'AE': + return '@S:AE|$encryptedPayload'; + case 'SYM': + default: + return '@S:SYM|$encryptedPayload'; + } + } + + // Fallback to the original raw SMS body if available + if (rawBody != null && rawBody.isNotEmpty && rawBody != body) { + return rawBody; + } + + return null; + } + + void _debouncedLoadMessages() { + _debounceTimer?.cancel(); + _debounceTimer = Timer(const Duration(milliseconds: 400), () { + if (mounted) loadMessages(); + }); + } + + @override + void initState() { + super.initState(); + displayName = ContactHelper.getName(widget.address); + SecureMessagingService.instance.currentChatPhone = + ContactHelper.normalizePhone(widget.address); + _scrollController.addListener(_onScroll); + _fetchSimCards(); + _initMessageStreamListener(); + _syncAndLoad(); + DatabaseHelper.instance.markAsRead(widget.address); + } + + void _onScroll() { + if (!_scrollController.hasClients) return; + final pos = _scrollController.position; + if (pos.pixels >= pos.maxScrollExtent - 150 && !_isLoading && _hasMore) { + loadMessages(isLoadMore: true); + } + } + + @override + void dispose() { + if (SecureMessagingService.instance.currentChatPhone == + ContactHelper.normalizePhone(widget.address)) { + SecureMessagingService.instance.currentChatPhone = null; + } + _scrollController.dispose(); + _messageNotifier.dispose(); + _messageSubscription?.cancel(); + _msgController.dispose(); + _debounceTimer?.cancel(); + super.dispose(); + } + + void _initMessageStreamListener() { + _messageSubscription = + SecureMessagingService.instance.messageStream.listen((data) { + final normalizedTarget = ContactHelper.normalizePhone(widget.address); + final normalizedIncoming = + ContactHelper.normalizePhone(data['phone'] as String); + + if (normalizedIncoming == normalizedTarget) { + // Immediate UI feedback for security state + final result = data['result'] as Map?; + if (result != null) { + final isSecure = result['isSecure'] == true; + final body = data['body'] as String?; + + if (isSecure && body != null) { + // Trigger a load immediately to reflect state changes + } + } + + final originalBody = data['originalBody'] as String? ?? ''; + final body = data['body'] as String? ?? ''; + final packetId = data['packetId'] as String?; + final packetMode = data['packetMode'] as String?; + final eventDate = + data['date'] as int? ?? DateTime.now().millisecondsSinceEpoch; + final isMultipartPending = data['isMultipartPending'] as bool? ?? false; + final isMultipartComplete = + data['isMultipartComplete'] as bool? ?? false; + final receivedParts = data['receivedParts'] as int? ?? 0; + final totalPartsFromEvent = data['totalParts'] as int? ?? 0; + final isMeEvent = data['isMe'] as bool? ?? false; + + if (body == 'REFRESH') { + _debouncedLoadMessages(); + return; + } + + if (ProtocolHelper.parseMessage(originalBody)['type'] == 'plain' && + _looksLikeProtocolFragment(originalBody)) { + _debouncedLoadMessages(); + return; + } + + final bool isIntermediateFragment = + body.contains('در حال دریافت قطعات') || + body.contains('در حال ارسال قطعات') || + body.contains('باقی قطعات پیام نرسیده‌اند'); + + if (isIntermediateFragment) { + if (!mounted) return; + if (isMultipartPending && packetId != null) { + final liveBody = body; + final liveStatus = totalPartsFromEvent > 0 && receivedParts > 0 + ? '${isMeEvent ? 'ارسال' : 'دریافت'} زنده: $receivedParts از $totalPartsFromEvent قطعه' + : '${isMeEvent ? 'ارسال' : 'دریافت'} قطعات در حال انجام است'; + final pendingMessage = ChatModel( + localId: isMeEvent + ? _findOutgoingDraftLocalId(ChatModel( + body: liveBody, + date: eventDate, + isMe: true, + status: MessageStatus.sending, + )) + : null, + body: liveBody, + rawBody: originalBody, + rawViewBody: _buildRawViewBody( + body: liveBody, + rawBody: originalBody, + packetMode: packetMode, + isSecure: true, + ), + packetId: packetId, + packetMode: packetMode, + statusLabel: liveStatus, + date: eventDate, + isMe: isMeEvent, + status: + isMeEvent ? MessageStatus.sending : MessageStatus.received, + isSecure: true, + isPendingMultipart: true, + ); + _replaceMessagesWithCandidates([ + ...messages.map((m) => _MessageCandidate(m)), + _MessageCandidate(pendingMessage, preferCandidate: true), + ]); + } + return; + } + + if (!mounted) return; + + final payloadMarker = _extractPayloadFromProcessedBody(body); + final cleanBody = payloadMarker != null + ? body.substring(0, body.indexOf(' ::PAYLOAD::')) + : body; + final incomingMessage = ChatModel( + body: cleanBody, + rawBody: originalBody, + rawViewBody: _buildRawViewBody( + body: cleanBody, + rawBody: originalBody, + encryptedPayload: payloadMarker, + packetMode: packetMode, + isSecure: isMultipartComplete || + ProtocolHelper.parseMessage(originalBody)['type'] != 'plain', + ), + encryptedPayload: payloadMarker, + packetId: packetId, + packetMode: packetMode, + date: eventDate, + isMe: isMeEvent, + status: isMeEvent ? MessageStatus.sent : MessageStatus.received, + isSecure: isMultipartComplete || + ProtocolHelper.parseMessage(originalBody)['type'] != 'plain', + canRetryDecryption: payloadMarker != null, + isPendingMultipart: false, + statusLabel: payloadMarker != null + ? 'پیام کامل شد؛ برای بازگشایی کلید را وارد کنید' + : null, + ); + if (incomingMessage.isSecure || packetMode != null) { + _enrichSecureModel(incomingMessage); + } + incomingMessage.localId ??= _findOutgoingDraftLocalId(incomingMessage); + _replaceMessagesWithCandidates([ + ...messages.map((m) => _MessageCandidate(m)), + _MessageCandidate(incomingMessage, preferCandidate: true), + ]); + } + }); + } + + Future _fetchSimCards() async { + if (!await Permission.phone.request().isGranted) { + if (mounted) setState(() => _loadingSims = false); + return; + } + try { + final List result = await platform.invokeMethod('getSimCards'); + final cleanList = result.map((e) { + final rawMap = e as Map; + return rawMap.map((key, value) => MapEntry(key.toString(), value)); + }).toList(); + if (!mounted) return; + setState(() { + _simCards = cleanList; + if (_simCards.isNotEmpty) _selectedSim = _simCards.first; + _loadingSims = false; + }); + } catch (_) { + if (mounted) setState(() => _loadingSims = false); + } + } + + bool _isSecurePlaceholderBody(String body) { + if (body.contains(' ::PAYLOAD::')) return true; + + return body.startsWith('پیام امن') || + body.startsWith('بازگشایی') || + body.startsWith('پیام رمزنگاری غیر متقارن'); + } + + bool _looksLikeProtocolFragment(String body) { + final normalized = body.trimLeft().toUpperCase(); + return normalized.startsWith('@S:AF|') || + normalized.startsWith('@S:SFRA|') || + normalized.startsWith('@G:AF|') || + normalized.startsWith('@G:SFRA|'); + } + + void _enrichSecureModel(ChatModel msg) { + final originalBody = msg.body; + final payloadFromProcessed = _extractPayloadFromProcessedBody(originalBody); + if (payloadFromProcessed != null) { + msg.body = + originalBody.substring(0, originalBody.indexOf(' ::PAYLOAD::')); + } + + final protocolParsed = + ProtocolHelper.parseMessage(msg.rawBody ?? originalBody); + final protocolPayload = protocolParsed['payload'] as String?; + final protocolPacketId = protocolParsed['packetId'] as String?; + final protocolType = protocolParsed['type'] as String?; + + msg.encryptedPayload = payloadFromProcessed ?? + msg.encryptedPayload ?? + (protocolPayload?.trim().isNotEmpty == true + ? protocolPayload!.trim() + : null); + + if ((msg.packetId == null || msg.packetId!.isEmpty) && + protocolPacketId != null && + protocolPacketId.isNotEmpty) { + msg.packetId = protocolPacketId; + } + + if ((msg.packetMode == null || msg.packetMode!.isEmpty) && + protocolType != null) { + if (protocolType == 'sym' || protocolType == 'sfra') { + msg.packetMode = 'SYM'; + } else if (protocolType == 'asym' || protocolType == 'afrag') { + msg.packetMode = 'AE'; + } + } + + msg.rawViewBody = _buildRawViewBody( + body: msg.body, + rawBody: msg.rawBody, + encryptedPayload: msg.encryptedPayload, + packetMode: msg.packetMode, + isSecure: true, + ); + msg.canRetryDecryption = !msg.isMe && _isSecurePlaceholderBody(msg.body); + } + + String? _extractPayloadFromProcessedBody(String body) { + const separator = ' ::PAYLOAD::'; + final splitIndex = body.lastIndexOf(separator); + if (splitIndex == -1) return null; + final payload = body.substring(splitIndex + separator.length).trim(); + return payload.isEmpty ? null : payload; + } + + String _securityLabel(String level) { + switch (level) { + case 'symmetric': + return 'رمزنگاری متقارن'; + case 'asymmetric': + return asymmetricModeLabel; + default: + return 'ارسال عادی'; + } + } + + String _securityDescription(String level) { + switch (level) { + case 'symmetric': + return 'سریع‌تر برای گفتگوهای مشترک با کلید ثابت'; + case 'asymmetric': + return 'امن‌تر برای تبادل کلید و پیام‌های حساس'; + default: + return 'پیامک معمولی بدون لایه امنیتی اضافه'; + } + } + + IconData _securityIcon(String level) { + switch (level) { + case 'symmetric': + return Icons.key_rounded; + case 'asymmetric': + return Icons.verified_user_rounded; + default: + return Icons.chat_bubble_outline_rounded; + } + } + + Color _securityAccent(String level) { + switch (level) { + case 'symmetric': + return const Color(0xFF2E7D32); + case 'asymmetric': + return const Color(0xFF1565C0); + default: + return const Color(0xFF607D8B); + } + } + + ({String text, Color color}) _securityModeBadge(String level) { + final secureState = contactInfo?['secure_state'] as String? ?? 'none'; + final verification = + contactInfo?['verification_state'] as String? ?? 'unverified'; + final hasPeerKey = + (contactInfo?['peer_public_key'] as String?)?.isNotEmpty == true; + final hasSharedKey = + (contactInfo?['ecc_shared_key'] as String?)?.isNotEmpty == true; + final hasSymmetricKey = + (contactInfo?['symmetric_key'] as String?)?.isNotEmpty == true; + + switch (level) { + case 'symmetric': + return hasSymmetricKey + ? (text: 'آماده', color: const Color(0xFF2E7D32)) + : (text: 'نیاز به کلید', color: const Color(0xFFEF6C00)); + case 'asymmetric': + if (secureState == 'handshake_failed' || verification == 'changed') { + return (text: 'نیاز به بازیابی', color: const Color(0xFFC62828)); + } + if (secureState == 'handshake_pending') { + return (text: 'در حال تبادل', color: const Color(0xFF1565C0)); + } + if (hasPeerKey && + hasSharedKey && + verification == 'verified' && + secureState == 'ready') { + return (text: 'آماده', color: const Color(0xFF2E7D32)); + } + if (hasPeerKey && hasSharedKey) { + return (text: 'نیاز به تایید', color: const Color(0xFFEF6C00)); + } + return (text: 'نیاز به ایجاد', color: const Color(0xFFEF6C00)); + default: + return (text: 'همیشه آماده', color: const Color(0xFF607D8B)); + } + } + + Future _showSecurityModeSheet() async { + final selected = await showModalBottomSheet( + context: context, + backgroundColor: Colors.transparent, + builder: (context) { + final levels = ['normal', 'symmetric', 'asymmetric']; + return Container( + decoration: BoxDecoration( + color: AppTheme.darkCard, + borderRadius: const BorderRadius.vertical(top: Radius.circular(28)), + border: Border.all( + color: Colors.white.withValues(alpha: 0.1), width: 0.5), + ), + padding: const EdgeInsets.fromLTRB(18, 18, 18, 24), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Container( + width: 42, + height: 4, + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.2), + borderRadius: BorderRadius.circular(999), + ), + ), + ), + const SizedBox(height: 16), + const Text( + 'روش رمزنگاری', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.white), + ), + const SizedBox(height: 6), + const Text( + 'برای این پیام، حالت مناسب را انتخاب کنید.', + style: TextStyle(color: Colors.white60, height: 1.4), + ), + const SizedBox(height: 16), + ...levels.map((level) { + final isSelected = _selectedSecurityLevel == level; + final accent = _securityAccent(level); + final badge = _securityModeBadge(level); + return Padding( + padding: const EdgeInsets.only(bottom: 10), + child: InkWell( + borderRadius: BorderRadius.circular(18), + onTap: () => Navigator.of(context).pop(level), + child: AnimatedContainer( + duration: const Duration(milliseconds: 180), + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: isSelected + ? accent.withValues(alpha: 0.15) + : Colors.white.withValues(alpha: 0.03), + borderRadius: BorderRadius.circular(18), + border: Border.all( + color: isSelected + ? accent.withValues(alpha: 0.6) + : Colors.white.withValues(alpha: 0.1), + width: isSelected ? 1.6 : 1, + ), + ), + child: Row( + children: [ + Container( + width: 42, + height: 42, + decoration: BoxDecoration( + color: accent.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(14), + ), + child: Icon(_securityIcon(level), color: accent), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + _securityLabel(level), + style: const TextStyle( + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + ), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 4, + ), + decoration: BoxDecoration( + color: + badge.color.withValues(alpha: 0.10), + borderRadius: + BorderRadius.circular(999), + ), + child: Text( + badge.text, + style: TextStyle( + color: badge.color, + fontSize: 11, + fontWeight: FontWeight.w700, + ), + ), + ), + ], + ), + const SizedBox(height: 4), + Text( + _securityDescription(level), + style: const TextStyle( + color: Colors.white38, fontSize: 12), + ), + ], + ), + ), + const SizedBox(width: 8), + Icon( + isSelected + ? Icons.radio_button_checked_rounded + : Icons.radio_button_off_rounded, + color: + isSelected ? accent : const Color(0xFF97A6B5), + ), + ], + ), + ), + ), + ); + }), + ], + ), + ); + }, + ); + + if (selected != null && mounted) { + setState(() => _selectedSecurityLevel = selected); + } + } + + String _securityStatusText() { + final state = contactInfo?['secure_state'] as String? ?? 'none'; + final verification = + contactInfo?['verification_state'] as String? ?? 'unverified'; + final mode = contactInfo?['mode'] as String? ?? 'normal'; + + if (state == 'handshake_pending') { + return 'در حال تبادل کلید عمومی...'; + } + if (state == 'handshake_failed') { + return 'تبادل کلید ناموفق بود؛ دوباره تلاش کنید'; + } + if (mode == 'asymmetric' && + (contactInfo?['peer_public_key'] as String?)?.isNotEmpty == true) { + if (verification == 'changed') { + return 'کلید مخاطب تغییر کرده است؛ اثر انگشت را دوباره تطبیق دهید'; + } + return verification == 'verified' && state == 'ready' + ? 'ارتباط امن شد و کانال ECC آماده است' + : 'کلید عمومی دریافت شده؛ برای فعال شدن ECC اثر انگشت را تایید کنید'; + } + if (mode == 'symmetric' && + (contactInfo?['symmetric_key'] as String?)?.isNotEmpty == true) { + return 'رمزنگاری متقارن آماده است'; + } + return 'حالت عادی'; + } + + bool get _isAsymmetricReadyNow { + final mode = contactInfo?['mode'] as String? ?? 'normal'; + final secureState = contactInfo?['secure_state'] as String? ?? 'none'; + final verification = + contactInfo?['verification_state'] as String? ?? 'unverified'; + final hasPeerKey = + (contactInfo?['peer_public_key'] as String?)?.isNotEmpty == true; + final hasSharedKey = + (contactInfo?['ecc_shared_key'] as String?)?.isNotEmpty == true; + return mode == 'asymmetric' && + hasPeerKey && + hasSharedKey && + secureState == 'ready' && + verification == 'verified'; + } + + Future _startAsymmetricHandshake({bool recovery = false}) async { + final result = await SecureMessagingService.instance + .startAsymmetricHandshake(widget.address); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text( + recovery + ? 'بازیابی ارتباط امن شروع شد. ${result['notice']}' + : (result['notice'] as String), + ), + )); + await loadMessages(); + } + + Future _endAsymmetricSecurity() async { + await SecureMessagingService.instance + .resetAsymmetricSecurity(widget.address); + if (!mounted) return; + setState(() { + _dismissedBannerText = null; + }); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('ارتباط امن برای این مخاطب پایان یافت.'), + ), + ); + await loadMessages(); + } + + Widget _buildAsymmetricActions() { + if (_selectedSecurityLevel != 'asymmetric') { + return const SizedBox.shrink(); + } + + final secureState = contactInfo?['secure_state'] as String? ?? 'none'; + final verification = + contactInfo?['verification_state'] as String? ?? 'unverified'; + final hasPeerKey = + (contactInfo?['peer_public_key'] as String?)?.isNotEmpty == true; + final hasSharedKey = + (contactInfo?['ecc_shared_key'] as String?)?.isNotEmpty == true; + final needsVerification = hasPeerKey && + hasSharedKey && + verification != 'verified' && + secureState != 'handshake_pending'; + final needsCreate = !needsVerification && + !_isAsymmetricReadyNow && + secureState != 'handshake_pending' && + verification != 'changed'; + final canRecover = _isAsymmetricReadyNow || + secureState == 'handshake_failed' || + secureState == 'pending_verification' || + verification == 'changed'; + final canEnd = secureState == 'handshake_pending' || + secureState == 'handshake_failed' || + secureState == 'pending_verification' || + (contactInfo?['mode'] as String? ?? 'normal') == 'asymmetric' || + hasPeerKey; + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), + child: AppTheme.glassWrapper( + child: Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _isAsymmetricReadyNow + ? 'ارتباط امن تایید شده است. حالا می‌توانید پیام‌های ECC بفرستید.' + : secureState == 'handshake_pending' + ? 'در حال تبادل کلیدهای عمومی هستیم. بعد از دریافت پاسخ، اثر انگشت مخاطب را تایید کنید.' + : verification == 'changed' + ? 'کلید مخاطب تغییر کرده است. تا زمان تایید اثر انگشت جدید، ارسال ECC غیرفعال می‌ماند.' + : needsVerification + ? 'کلید عمومی مخاطب دریافت شده است. تا زمان تایید اثر انگشت، ارسال ECC غیرفعال می‌ماند.' + : 'برای شروع ارتباط نامتقارن، ابتدا تبادل کلید را انجام دهید.', + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.white), + ), + const SizedBox(height: 14), + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + if (needsCreate) + ElevatedButton.icon( + onPressed: () => _startAsymmetricHandshake(), + style: ElevatedButton.styleFrom( + backgroundColor: + Colors.blueAccent.withValues(alpha: 0.8), + foregroundColor: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12)), + ), + icon: const Icon(Icons.security, size: 18), + label: const Text('ایجاد ارتباط امن'), + ), + if (secureState == 'handshake_pending') + OutlinedButton.icon( + onPressed: null, + style: OutlinedButton.styleFrom( + foregroundColor: Colors.white60, + side: const BorderSide(color: Colors.white24), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12)), + ), + icon: const SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator( + strokeWidth: 2, color: Colors.white60), + ), + label: const Text('در حال تبادل کلید'), + ), + if (hasPeerKey) + OutlinedButton.icon( + onPressed: _showFingerprintSheet, + style: OutlinedButton.styleFrom( + foregroundColor: Colors.white, + side: const BorderSide(color: Colors.white30), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12)), + ), + icon: const Icon(Icons.verified_user_outlined, size: 18), + label: Text(verification == 'verified' + ? 'اثر انگشت' + : 'تایید اثر انگشت'), + ), + if (canRecover) + OutlinedButton.icon( + onPressed: () => + _startAsymmetricHandshake(recovery: true), + style: OutlinedButton.styleFrom( + foregroundColor: Colors.white, + side: const BorderSide(color: Colors.white30), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12)), + ), + icon: const Icon(Icons.refresh_rounded, size: 18), + label: const Text('بازیابی ارتباط امن'), + ), + if (canEnd) + TextButton.icon( + onPressed: _endAsymmetricSecurity, + style: TextButton.styleFrom( + foregroundColor: + Colors.redAccent.withValues(alpha: 0.7)), + icon: const Icon(Icons.cancel_outlined, size: 18), + label: const Text('پایان ارتباط'), + ), + ], + ), + ], + ), + ), + ), + ); + } + + Future _syncAndLoad() async { + if (_isLoading) return; + _isLoading = true; + + try { + final inbox = await telephony.getInboxSms(columns: [ + SmsColumn.ID, + SmsColumn.ADDRESS, + SmsColumn.BODY, + SmsColumn.DATE, + SmsColumn.TYPE + ], filter: SmsFilter.where(SmsColumn.ADDRESS).equals(widget.address)); + final sent = await telephony.getSentSms(columns: [ + SmsColumn.ID, + SmsColumn.ADDRESS, + SmsColumn.BODY, + SmsColumn.DATE, + SmsColumn.TYPE + ], filter: SmsFilter.where(SmsColumn.ADDRESS).equals(widget.address)); + + final List> toCache = []; + for (final sms in [...inbox, ...sent]) { + toCache.add({ + 'sms_id': sms.id, + 'address': ContactHelper.normalizePhone(sms.address ?? ''), + 'body': sms.body ?? '', + 'date': sms.date ?? 0, + 'type': sms.type?.index ?? 0, + 'is_me': sms.type != SmsType.MESSAGE_TYPE_INBOX ? 1 : 0, + }); + } + + if (toCache.isNotEmpty) { + await DatabaseHelper.instance.batchInsertSms(toCache); + } + } catch (e) { + debugPrint('Sync error: $e'); + } finally { + _isLoading = false; + loadMessages(); + } + } + + bool _needsReload = false; + + Future loadMessages({bool isLoadMore = false}) async { + if (_isLoading) { + if (!isLoadMore) _needsReload = true; + return; + } + if (isLoadMore && !_hasMore) return; + + _isLoading = true; + _needsReload = false; + if (!isLoadMore) { + _hasMore = true; + } + + try { + final cInfo = await DatabaseHelper.instance.getContact(widget.address); + final totalSmsCount = await DatabaseHelper.instance.getSmsCount( + widget.address, + ); + if (mounted) setState(() => contactInfo = cInfo); + + final previousOffset = _offset; + final fetchOffset = isLoadMore ? previousOffset : 0; + final rawSms = await DatabaseHelper.instance + .getPaginatedSms(widget.address, _limit, fetchOffset); + + // 1. Process Database SMS + final List processed = await compute( + (data) => MessageProcessor.processSmsList( + data['raw'] as List>, + data['address'] as String, + ), + {'raw': rawSms, 'address': widget.address}, + ); + + // 2. Perform Unified Reconciliation + final currentMessages = List.from(messages); + final baseMessages = isLoadMore + ? currentMessages + : currentMessages + .where(_shouldKeepTransientMessageDuringReload) + .toList(growable: false); + final candidates = <_MessageCandidate>[ + ...baseMessages.map( + (m) => _MessageCandidate( + m, + preferCandidate: _shouldPreferInMemoryMessage(m), + ), + ), + ]; + + // Add Database Messages + for (final msg in processed) { + if (msg.isSecure) { + final pBody = + await SecureMessagingService.instance.processIncomingSms( + widget.address, + msg.body, + broadcast: false, + isMe: msg.isMe, + isScan: false, + ); + if (pBody != null && pBody != msg.body) { + msg.body = pBody; + } + _enrichSecureModel(msg); + } + candidates.add(_MessageCandidate(msg)); + } + + // Merge Pending Fragments from Cache + final pendingPacketRows = await SecureMessagingService.instance + .getPendingPacketsForPhone(widget.address); + for (final row in pendingPacketRows) { + final pId = row['msg_id'] as String; + final pMode = row['packet_mode'] as String? ?? 'SYM'; + candidates.add( + _MessageCandidate( + ChatModel( + body: 'در حال دریافت قطعات...', + statusLabel: + '(${row['received_parts']}/${row['total_parts']}) دریافت قطعات', + packetId: pId, + packetMode: pMode, + date: row['first_seen'] as int? ?? 0, + isMe: (row['isMe'] as int? ?? 0) == 1, + status: MessageStatus.received, + isSecure: true, + isPendingMultipart: true, + ), + ), + ); + } + + // 3. Finalize List + final List updatedList = _reconcileCandidates(candidates); + + final nextOffset = isLoadMore + ? previousOffset + rawSms.length + : max(previousOffset, rawSms.length); + _offset = min(totalSmsCount, nextOffset); + _hasMore = _offset < totalSmsCount; + + _publishMessages(updatedList); + } finally { + _isLoading = false; + if (_needsReload) loadMessages(); + } + } + + Future _openContactInfo() async { + if (!await FlutterContacts.requestPermission(readonly: true) || !mounted) { + return; + } + + showDialog( + context: context, + barrierDismissible: false, + builder: (_) => const Center(child: CircularProgressIndicator()), + ); + + try { + final contacts = await FlutterContacts.getContacts( + withProperties: true, withPhoto: false); + final currentPhoneNormalized = + ContactHelper.normalizePhone(widget.address); + String? contactId; + + for (final contact in contacts) { + for (final phone in contact.phones) { + if (ContactHelper.normalizePhone(phone.number) == + currentPhoneNormalized) { + contactId = contact.id; + break; + } + } + if (contactId != null) break; + } + + if (mounted) Navigator.pop(context); + + if (contactId != null) { + await FlutterContacts.openExternalView(contactId); + } else { + await FlutterContacts.openExternalInsert( + Contact(phones: [Phone(widget.address)])); + } + if (mounted) { + setState(() { + displayName = ContactHelper.getName(widget.address); + }); + } + } catch (_) { + if (mounted && Navigator.canPop(context)) Navigator.pop(context); + } + } + + Future _showFingerprintSheet() async { + final securityContext = await SecureMessagingService.instance + .getSecurityContext(widget.address); + if (!mounted || securityContext == null) return; + + showModalBottomSheet( + context: context, + backgroundColor: Colors.transparent, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + ), + builder: (context) { + final peerFingerprint = securityContext['peerFingerprint'] as String?; + final verificationState = + securityContext['verificationState'] as String? ?? 'unverified'; + final stateText = verificationState == 'changed' + ? 'وضعیت: کلید مخاطب تغییر کرده است' + : verificationState == 'verified' + ? 'وضعیت: تایید شده' + : 'وضعیت: هنوز تایید نشده'; + final stateColor = verificationState == 'changed' + ? Colors.red.shade700 + : verificationState == 'verified' + ? Colors.green.shade700 + : Colors.orange.shade400; + return Container( + decoration: BoxDecoration( + color: AppTheme.darkCard, + borderRadius: const BorderRadius.vertical(top: Radius.circular(24)), + border: Border.all( + color: Colors.white.withValues(alpha: 0.1), width: 0.5), + ), + padding: const EdgeInsets.fromLTRB(20, 20, 20, 32), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text('تایید هویت و اثر انگشت کلید', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.white)), + const SizedBox(height: 12), + Text('کلید شما:\n${securityContext['localFingerprint']}', + style: const TextStyle(color: Colors.white70)), + const SizedBox(height: 12), + Text( + peerFingerprint == null + ? 'هنوز کلید عمومی مخاطب دریافت نشده است.' + : 'کلید مخاطب:\n$peerFingerprint', + style: const TextStyle(color: Colors.white70)), + const SizedBox(height: 12), + const Text( + 'برای جلوگیری از MITM، این اثر انگشت را با تماس تلفنی یا یک کانال امن دیگر با مخاطب تطبیق دهید.', + style: TextStyle(height: 1.5, color: Colors.white60), + ), + const SizedBox(height: 12), + Text( + stateText, + style: TextStyle( + color: stateColor, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 16), + ElevatedButton( + onPressed: peerFingerprint == null + ? null + : () async { + await SecureMessagingService.instance + .markFingerprintVerified(widget.address); + if (!mounted) return; + Navigator.of(this.context).pop(); + ScaffoldMessenger.of(this.context).showSnackBar( + const SnackBar( + content: Text( + 'اثر انگشت کلید برای این مخاطب تایید شد.')), + ); + loadMessages(); + }, + child: Text(verificationState == 'changed' + ? 'تایید اثر انگشت جدید' + : 'تایید اثر انگشت'), + ), + ], + ), + ); + }, + ); + } + + void _deleteSmsNative(int messageId) { + showDialog( + context: context, + builder: (ctx) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: const Text('حذف پیام'), + content: const Text('آیا از حذف این پیام مطمئن هستید؟'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx), child: const Text('لغو')), + ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, foregroundColor: Colors.white), + onPressed: () async { + Navigator.pop(ctx); + try { + await nativeChannel + .invokeMethod('deleteSms', {'id': messageId.toString()}); + if (!mounted) return; + messages.removeWhere((m) => m.id == messageId); + _publishMessages(messages); + Future.delayed(const Duration(seconds: 1), loadMessages); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('درخواست حذف ارسال شد'))); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text('خطا: $e'))); + } + }, + child: const Text('حذف'), + ), + ], + ), + ); + } + + Future sendMessage() async { + final text = _msgController.text.trim(); + if (text.isEmpty) return; + + if (_selectedSecurityLevel == 'symmetric') { + _showKeyEntryAndSend(text); + return; + } + + if (_selectedSecurityLevel == 'asymmetric' && !_isAsymmetricReadyNow) { + final secureState = contactInfo?['secure_state'] as String? ?? 'none'; + final verification = + contactInfo?['verification_state'] as String? ?? 'unverified'; + final hasPeerKey = + (contactInfo?['peer_public_key'] as String?)?.isNotEmpty == true; + final hasSharedKey = + (contactInfo?['ecc_shared_key'] as String?)?.isNotEmpty == true; + final notice = verification == 'changed' + ? 'کلید مخاطب تغییر کرده است؛ ابتدا اثر انگشت جدید را تایید کنید.' + : (hasPeerKey && hasSharedKey) + ? 'کلید مخاطب دریافت شده اما هنوز تایید نشده است؛ ابتدا اثر انگشت را تایید کنید.' + : secureState == 'handshake_pending' + ? 'تبادل کلید هنوز کامل نشده است.' + : 'ابتدا روی «ایجاد ارتباط امن» بزنید تا تبادل کلید انجام شود.'; + if (!mounted) return; + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text(notice))); + return; + } + + await _executeSendMessage(text, securityLevel: _selectedSecurityLevel); + } + + void _showKeyEntryAndSend(String text) { + final keyController = + TextEditingController(text: contactInfo?['symmetric_key'] ?? ''); + showDialog( + context: context, + builder: (ctx) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: const Text('رمزنگاری متقارن'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('کلید متقارن این پیام را وارد یا تایید کنید:'), + const SizedBox(height: 10), + TextField( + controller: keyController, + decoration: const InputDecoration( + hintText: 'کلید متقارن', + border: OutlineInputBorder(), + ), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx), child: const Text('لغو')), + ElevatedButton( + onPressed: () { + if (keyController.text.trim().isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('لطفاً کلید را وارد کنید'))); + return; + } + Navigator.pop(ctx); + _executeSendMessage(text, + securityLevel: 'symmetric', + symmetricKey: keyController.text.trim()); + }, + child: const Text('ارسال'), + ), + ], + ), + ); + } + + Future _executeSendMessage(String text, + {required String securityLevel, String? symmetricKey}) async { + final earlyPacketId = + Random().nextInt(0xFFFFFFFF).toRadixString(16).padLeft(10, '0'); + final tempTimestamp = DateTime.now().millisecondsSinceEpoch; + final draftLocalId = + 'draft::$tempTimestamp::${Random().nextInt(1 << 32).toRadixString(16)}'; + + final tempMsg = ChatModel( + localId: draftLocalId, + body: text, + date: tempTimestamp, + isMe: true, + status: MessageStatus.sending, + isSecure: securityLevel != 'normal', + packetId: securityLevel == 'normal' ? null : earlyPacketId, + ); + messages.insert(0, tempMsg); + _publishMessages(messages); + _msgController.clear(); + + try { + if (symmetricKey != null) { + tempMsg.rawBody = await SecureMessagingService.instance + .getEncryptedPreview(text, symmetricKey); + } + + final result = await SecureMessagingService.instance.sendMessage( + widget.address, + text, + securityLevel: securityLevel, + symmetricKey: symmetricKey, + forcedPacketId: securityLevel == 'normal' ? null : earlyPacketId, + localTimestamp: tempTimestamp, + ); + + if (!mounted) return; + if (result['sentText'] == true) { + tempMsg.packetId = result['packetId'] as String?; + tempMsg.packetMode = result['packetMode'] as String?; + tempMsg.rawBody ??= result['protocolBody'] as String?; + tempMsg.rawViewBody ??= tempMsg.rawBody; + tempMsg.encryptedPayload ??= result['encryptedPayload'] as String?; + tempMsg.isPendingMultipart = result['notice'] == 'sent_fragmented'; + tempMsg.status = MessageStatus.sent; + if (result['notice'] == 'sent') { + tempMsg.statusLabel = null; + } else { + tempMsg.statusLabel = 'ارسال کامل شد'; + } + _replaceMessagesWithCandidates([ + ...messages.map((m) => _MessageCandidate(m)), + _MessageCandidate(tempMsg, preferCandidate: true), + ]); + Future.delayed(const Duration(milliseconds: 800), loadMessages); + } else { + messages.remove(tempMsg); + _msgController.text = text; + _msgController.selection = TextSelection.fromPosition( + TextPosition(offset: _msgController.text.length)); + _publishMessages(messages); + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text(result['notice'] as String))); + loadMessages(); + } + } catch (e) { + if (!mounted) return; + setState(() { + tempMsg.status = MessageStatus.failed; + tempMsg.statusLabel = 'خطا در ارسال'; + }); + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text('خطا در ارسال: $e'))); + } + } + + Future _handleRetryDecryption(ChatModel msg) async { + final source = msg.rawBody ?? msg.body; + final payload = + await SecureMessagingService.instance.resolvePayloadForRetry( + source, + phone: widget.address, + hintedPayload: msg.body.contains(' ::PAYLOAD::') + ? msg.body.split(' ::PAYLOAD::')[1] + : msg.encryptedPayload, + ); + if (!mounted) return; + if (payload == null) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('payload پیام پیدا نشد.'))); + return; + } + + final keyController = TextEditingController(); + showDialog( + context: context, + builder: (ctx) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: const Text('بازگشایی دستی پیام'), + content: TextField( + controller: keyController, + decoration: const InputDecoration( + hintText: 'کلید متقارن', + border: OutlineInputBorder(), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx), child: const Text('لغو')), + ElevatedButton( + onPressed: () async { + if (keyController.text.trim().isEmpty) return; + Navigator.pop(ctx); + final messenger = ScaffoldMessenger.of(context); + final decrypted = + await SecureMessagingService.instance.decryptWithKey( + source, + keyController.text.trim(), + phone: widget.address, + hintedPayload: payload, + ); + if (!mounted) return; + if (decrypted != null) { + final isGroup = msg.rawBody?.contains('@G:') == true || + msg.body.contains('@G:') == true || + (msg.rawBody != null && + ProtocolHelper.parseMessage(msg.rawBody!)['isGroup'] == + true); + + if (isGroup) { + final groups = await DatabaseHelper.instance + .getGroupsContainingPhone(widget.address); + for (final g in groups) { + await DatabaseHelper.instance.updateGroupKey( + g['id'] as int, keyController.text.trim()); + } + } else { + await DatabaseHelper.instance.updateContactSecurity( + widget.address, + symmetricKey: keyController.text.trim(), + mode: 'symmetric', + state: 'ready', + ); + } + + setState(() { + msg.body = decrypted; + msg.encryptedPayload = payload; + msg.rawViewBody = _buildRawViewBody( + body: decrypted, + rawBody: msg.rawBody, + encryptedPayload: payload, + packetMode: msg.packetMode ?? 'SYM', + isSecure: true, + ); + msg.canRetryDecryption = false; + msg.statusLabel = null; + msg.isSecure = true; + msg.isPendingMultipart = false; + }); + messenger.showSnackBar( + const SnackBar(content: Text('بازگشایی موفقیت‌آمیز بود.'))); + loadMessages(); + } else { + messenger.showSnackBar(const SnackBar( + content: Text( + 'بازگشایی ناموفق بود. کلید اشتباه است یا دیتا مخدوش شده است.'))); + } + }, + child: const Text('بازگشایی'), + ), + ], + ), + ); + } + + Future _makePhoneCall() async { + try { + await nativeChannel.invokeMethod('makeCall', {'phone': widget.address}); + } catch (_) { + if (!mounted) return; + ScaffoldMessenger.of(context) + .showSnackBar(const SnackBar(content: Text('خطا در برقراری تماس'))); + } + } + + Widget _buildSecurityBanner() { + final status = _securityStatusText(); + if (status.isEmpty || status == _dismissedBannerText) { + return const SizedBox.shrink(); + } + + final mode = contactInfo?['mode'] as String? ?? 'normal'; + final secureState = contactInfo?['secure_state'] as String? ?? 'none'; + final verification = + contactInfo?['verification_state'] as String? ?? 'unverified'; + final isAsym = + mode == 'asymmetric' || _selectedSecurityLevel == 'asymmetric'; + final hasSecurityAlert = + secureState == 'handshake_failed' || verification == 'changed'; + final hasSecureConnection = isAsym && _isAsymmetricReadyNow; + final bg = hasSecurityAlert + ? Colors.red.withValues(alpha: 0.8) + : (hasSecureConnection + ? Colors.green.withValues(alpha: 0.8) + : Colors.blue.withValues(alpha: 0.8)); + final border = Colors.white.withValues(alpha: 0.2); + const iconColor = Colors.white; + const textColor = Colors.white; + + return AnimatedSwitcher( + duration: const Duration(milliseconds: 400), + transitionBuilder: (Widget child, Animation animation) { + return FadeTransition( + opacity: animation, + child: SlideTransition( + position: Tween( + begin: const Offset(0, -0.5), + end: Offset.zero, + ).animate(animation), + child: child, + ), + ); + }, + child: Container( + key: ValueKey(status), + margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), + child: ClipRRect( + borderRadius: BorderRadius.circular(16), + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + decoration: BoxDecoration( + color: bg.withValues(alpha: 0.2), + borderRadius: BorderRadius.circular(16), + border: Border.all(color: border, width: 0.5), + ), + child: Row( + children: [ + Icon( + hasSecurityAlert + ? Icons.warning_amber_rounded + : (hasSecureConnection + ? Icons.verified_user_rounded + : Icons.info_outline_rounded), + color: iconColor, + size: 20, + ), + const SizedBox(width: 12), + Expanded( + child: Text( + status, + style: const TextStyle( + color: textColor, + fontSize: 13, + fontWeight: FontWeight.w600, + ), + ), + ), + IconButton( + onPressed: () => + setState(() => _dismissedBannerText = status), + icon: const Icon(Icons.close, + color: Colors.white60, size: 18), + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + ), + ], + ), + ), + ), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppTheme.darkBg, + extendBodyBehindAppBar: true, + resizeToAvoidBottomInset: true, + appBar: PreferredSize( + preferredSize: const Size.fromHeight(kToolbarHeight + 8), + child: AppTheme.glassWrapper( + radius: 0, + sigma: 18, + child: AppBar( + backgroundColor: Colors.transparent, + elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () => Navigator.of(context).pop(), + ), + title: InkWell( + onTap: _openContactInfo, + overlayColor: WidgetStateProperty.all(Colors.transparent), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Hero( + tag: 'avatar_${displayName}_ind', + child: Container( + width: 38, + height: 38, + decoration: BoxDecoration( + shape: BoxShape.circle, + gradient: LinearGradient( + colors: [ + Theme.of(context).primaryColor, + Theme.of(context) + .primaryColor + .withValues(alpha: 0.7), + ], + ), + ), + child: Center( + child: Text( + displayName.isNotEmpty ? displayName[0] : '?', + style: const TextStyle( + color: Colors.white, + fontSize: 14, + fontWeight: FontWeight.bold), + ), + ), + ), + ), + const SizedBox(width: 10), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + displayName, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: Colors.white), + ), + if (displayName != widget.address) + Text( + widget.address, + style: const TextStyle( + fontSize: 11, color: Colors.white70), + ), + ], + ), + ], + ), + ), + actions: [ + IconButton( + icon: const Icon(Icons.verified_user_outlined, + color: Colors.white, size: 22), + onPressed: _showFingerprintSheet, + ), + IconButton( + icon: const Icon(Icons.call_outlined, + color: Colors.white, size: 22), + onPressed: _makePhoneCall, + ), + ], + ), + ), + ), + body: Stack( + children: [ + Positioned.fill(child: CustomPaint(painter: MeshBackgroundPainter())), + Column( + children: [ + SizedBox( + height: + MediaQuery.of(context).padding.top + kToolbarHeight + 8), + _buildSecurityBanner(), + Expanded( + child: ValueListenableBuilder>( + valueListenable: _messageNotifier, + builder: (context, messages, child) { + if (messages.isEmpty) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.mark_chat_unread_outlined, + size: 60, + color: Colors.white.withValues(alpha: 0.1)), + const SizedBox(height: 10), + const Text('آغاز گفتگو...', + style: TextStyle( + color: Colors.white38, fontSize: 13)), + ], + ), + ); + } + return ListView.builder( + key: const PageStorageKey('chat_list_view'), + controller: _scrollController, + reverse: true, + padding: const EdgeInsets.symmetric( + horizontal: 10, vertical: 20), + itemCount: messages.length + (_hasMore ? 1 : 0), + itemBuilder: (context, index) { + if (index == messages.length) { + return const Center( + child: Padding( + padding: EdgeInsets.all(12.0), + child: CircularProgressIndicator(strokeWidth: 2), + ), + ); + } + final msg = messages[index]; + return GestureDetector( + onLongPress: () { + if (msg.id != null) { + _deleteSmsNative(msg.id!); + } + }, + child: MessageBubble( + key: ValueKey( + msg.localId ?? + _packetKey(msg.packetId, msg.packetMode) ?? + msg.id?.toString() ?? + 'temp_${msg.date}', + ), + body: msg.body, + rawBody: msg.rawViewBody ?? msg.rawBody, + statusLabel: msg.statusLabel, + date: msg.date, + isMe: msg.isMe, + status: msg.status, + isSecure: msg.isSecure, + canRetryDecryption: msg.canRetryDecryption, + onRetryDecryption: () => + _handleRetryDecryption(msg), + packetMode: msg.packetMode, + isPendingMultipart: msg.isPendingMultipart, + ), + ); + }, + ); + }, + ), + ), + AppTheme.glassWrapper( + radius: 0, + sigma: 15, + child: Container( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 12), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.03), + border: Border( + top: BorderSide( + color: Colors.white.withValues(alpha: 0.08), + width: 0.5), + ), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!_loadingSims && _simCards.length > 1) + SizedBox( + height: 35, + child: ListView.builder( + scrollDirection: Axis.horizontal, + itemCount: _simCards.length, + itemBuilder: (context, index) { + final sim = _simCards[index]; + final isSelected = _selectedSim == sim; + return Padding( + padding: const EdgeInsets.only(right: 8), + child: ChoiceChip( + label: Text(sim['displayName']?.toString() ?? + 'SIM ${index + 1}'), + selected: isSelected, + onSelected: (_) => + setState(() => _selectedSim = sim), + ), + ); + }, + ), + ), + const SizedBox(height: 8), + Row( + children: [ + InkWell( + borderRadius: BorderRadius.circular(18), + onTap: _showSecurityModeSheet, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 14, vertical: 12), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.05), + borderRadius: BorderRadius.circular(18), + border: Border.all( + color: Colors.white.withValues(alpha: 0.1), + width: 0.5), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: _securityAccent( + _selectedSecurityLevel) + .withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(10), + ), + child: Icon( + _securityIcon(_selectedSecurityLevel), + size: 16, + color: _securityAccent( + _selectedSecurityLevel), + ), + ), + const SizedBox(width: 10), + Text( + _securityLabel(_selectedSecurityLevel), + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Colors.white), + ), + const SizedBox(width: 8), + const Icon(Icons.expand_more_rounded, + size: 18, color: Colors.white70), + ], + ), + ), + ), + ], + ), + _buildAsymmetricActions(), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + child: TextField( + controller: _msgController, + minLines: 1, + maxLines: 4, + style: const TextStyle(color: Colors.white), + decoration: InputDecoration( + hintText: 'پیام خود را بنویسید...', + hintStyle: + const TextStyle(color: Colors.white30), + filled: true, + fillColor: Colors.white.withValues(alpha: 0.05), + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, vertical: 12), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(20), + borderSide: BorderSide.none, + ), + ), + ), + ), + const SizedBox(width: 10), + FloatingActionButton( + heroTag: 'send_${widget.address}', + mini: true, + elevation: 4, + backgroundColor: Theme.of(context).primaryColor, + onPressed: _selectedSecurityLevel == 'asymmetric' && + !_isAsymmetricReadyNow + ? null + : sendMessage, + child: const Icon(Icons.send_rounded, + color: Colors.white, size: 20), + ), + ], + ), + ], + ), + ), + ), + ], + ), + ], + ), + ); + } +} diff --git a/lib/screens/compose_screen.dart b/lib/screens/compose_screen.dart new file mode 100644 index 0000000..755bcf0 --- /dev/null +++ b/lib/screens/compose_screen.dart @@ -0,0 +1,773 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:another_telephony/telephony.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:flutter_contacts/flutter_contacts.dart'; +import '../utils/secure_messaging_service.dart'; +import '../utils/database_helper.dart'; +import '../utils/contact_helper.dart'; +import '../utils/secure_crypto_helper.dart'; +import '../utils/app_theme.dart'; +import 'chat_screen.dart'; + +class ComposeScreen extends StatefulWidget { + const ComposeScreen({super.key}); + + @override + State createState() => _ComposeScreenState(); +} + +class _ComposeScreenState extends State { + final Telephony telephony = Telephony.instance; + static const platform = MethodChannel('com.example.saba/sim_cards'); + static const asymmetricModeLabel = 'رمزنگاری غیر متقارن (طولانی‌تر و امن‌تر)'; + + final _phoneController = TextEditingController(); + final _msgController = TextEditingController(); + final _keyController = TextEditingController(); + final _groupNameController = TextEditingController(); + + final List> _selectedContacts = []; + + // --- کش داخلی (لیست سبک مخاطبین) --- + // به جای Map، از کلاس Contact استفاده می‌کنیم که فقط ID و Name دارد + List _contactsCache = []; + + List> _simCards = []; + Map? _selectedSim; + bool _loadingSims = true; + bool isSending = false; + String _selectedSecurityLevel = 'normal'; + + Color get primaryColor => Theme.of(context).primaryColor; + final Color backgroundColor = const Color(0xFFF5F7FA); + + @override + void initState() { + super.initState(); + _fetchSimCards(); + // لود کردن لیست سبک در شروع + _loadLightContacts(); + } + + // دریافت لیست سبک (نام و آیدی) - بسیار سریع + Future _loadLightContacts() async { + try { + final contacts = await ContactHelper.getContactsLight(); + if (mounted) { + setState(() { + _contactsCache = contacts; + }); + } + } catch (e) { + print("Error loading light contacts: $e"); + } + } + + // دکمه آپدیت: هم لیست جستجو را آپدیت می‌کند، هم دیتابیس را + Future _forceSyncContacts({bool silent = false}) async { + if (!silent) { + showDialog( + context: context, + barrierDismissible: false, + builder: (_) => const Center(child: CircularProgressIndicator()), + ); + } + + // 1. آپدیت لیست جستجو (سریع) + await _loadLightContacts(); + + // 2. آپدیت دیتابیس برای نمایش نام در صفحه اصلی (سنگین) + await ContactHelper.syncWithDevice(); + + if (!silent && mounted) { + Navigator.pop(context); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("✅ مخاطبین بروزرسانی شدند"))); + } + } + + Future _fetchSimCards() async { + if (!await Permission.phone.request().isGranted) { + setState(() => _loadingSims = false); + return; + } + try { + final List result = await platform.invokeMethod('getSimCards'); + List> cleanList = result.map((e) { + final Map rawMap = e as Map; + return rawMap.map((key, value) => MapEntry(key.toString(), value)); + }).toList(); + + setState(() { + _simCards = cleanList; + if (_simCards.isNotEmpty) _selectedSim = _simCards[0]; + _loadingSims = false; + }); + } catch (e) { + setState(() => _loadingSims = false); + } + } + + void _openContactSearch() async { + if (!await FlutterContacts.requestPermission(readonly: true)) return; + + // اگر لیست خالی بود، سعی کن دوباره بگیری + if (_contactsCache.isEmpty) { + await _loadLightContacts(); + } + + if (_contactsCache.isEmpty) { + if (mounted) { + ScaffoldMessenger.of(context) + .showSnackBar(const SnackBar(content: Text("مخاطبی یافت نشد"))); + } + return; + } + + // باز کردن سرچ با لیست سبک + final result = await showSearch?>( + context: context, + delegate: ContactsSearchDelegate(_contactsCache), + ); + + if (result != null) { + setState(() { + // نرمال‌سازی شماره قبل از افزودن + final normalizedPhone = ContactHelper.normalizePhone(result['phone']!); + + final exists = _selectedContacts.any((c) => + ContactHelper.normalizePhone(c['phone']!) == normalizedPhone); + if (!exists) { + result['phone'] = normalizedPhone; + _selectedContacts.add(result); + } + + if (_selectedContacts.length == 1) { + _phoneController.text = _selectedContacts[0]['phone']!; + } else { + _phoneController.clear(); + } + }); + } + } + + void _removeContact(int index) { + setState(() { + _selectedContacts.removeAt(index); + if (_selectedContacts.length == 1) { + _phoneController.text = _selectedContacts[0]['phone']!; + } else if (_selectedContacts.isEmpty) { + _phoneController.clear(); + } + }); + } + + String _securityLabel(String level) { + switch (level) { + case 'symmetric': + return 'رمزنگاری متقارن'; + case 'asymmetric': + return asymmetricModeLabel; + default: + return 'ارسال عادی'; + } + } + + Widget _buildSecurityModeCard() { + const options = ['normal', 'symmetric', 'asymmetric']; + + return AppTheme.glassWrapper( + radius: 18, + child: Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.03), + borderRadius: BorderRadius.circular(18), + border: Border.all(color: Colors.white.withValues(alpha: 0.1), width: 0.5), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'سطح امنیت', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white), + ), + const SizedBox(height: 12), + Wrap( + spacing: 8, + runSpacing: 8, + children: options.map((level) { + return ChoiceChip( + label: Text(_securityLabel(level)), + selected: _selectedSecurityLevel == level, + onSelected: (_) { + setState(() { + _selectedSecurityLevel = level; + }); + }, + selectedColor: primaryColor, + backgroundColor: Colors.white.withValues(alpha: 0.05), + labelStyle: TextStyle( + color: _selectedSecurityLevel == level + ? Colors.white + : Colors.white70, + fontWeight: FontWeight.w600, + ), + ); + }).toList(), + ), + const SizedBox(height: 12), + Text( + _selectedSecurityLevel == 'asymmetric' + ? 'در حالت $asymmetricModeLabel برنامه در صورت نیاز ابتدا تبادل کلید را از طریق پیامک انجام می‌دهد و سپس پیام اصلی را می‌فرستد.' + : _selectedSecurityLevel == 'symmetric' + ? 'در این حالت باید کلید مشترک یکسانی در دو طرف وارد شده باشد.' + : 'در این حالت پیام بدون رمزنگاری اضافه ارسال می‌شود.', + style: const TextStyle( + color: Colors.white60, + fontSize: 12, + height: 1.5, + ), + ), + ], + ), + ), + ); + } + + Future _sendMessage() async { + bool isGroupMode = _selectedContacts.length > 1; + + if (isGroupMode) { + if (_groupNameController.text.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("لطفاً نام گروه را وارد کنید"))); + return; + } + if (_msgController.text.isEmpty) { + ScaffoldMessenger.of(context) + .showSnackBar(const SnackBar(content: Text("متن پیام خالی است"))); + return; + } + + int groupId = await DatabaseHelper.instance + .createGroup(_groupNameController.text, _selectedContacts); + + String finalMsg = _msgController.text; + if (_keyController.text.isNotEmpty) { + final crypto = SecureCryptoHelper(); + finalMsg = await crypto.encryptSymmetric(_msgController.text, _keyController.text); + finalMsg = "@G:SYM|" + finalMsg; // Prefix for Group Symmetric + } + + setState(() => isSending = true); + + int? subId = + _selectedSim != null ? _selectedSim!['subscriptionId'] as int : null; + + for (var member in _selectedContacts) { + try { + String phone = ContactHelper.normalizePhone(member['phone']!); + if (subId != null) { + await telephony.sendSms( + to: phone, message: finalMsg, subscriptionId: subId); + } else { + await telephony.sendSms(to: phone, message: finalMsg); + } + } catch (_) {} + } + + await DatabaseHelper.instance.saveGroupMessage( + groupId, finalMsg, DateTime.now().millisecondsSinceEpoch); + + setState(() => isSending = false); + if (mounted) Navigator.pop(context, true); + return; + } + + String rawPhone = _phoneController.text; + if (rawPhone.isEmpty && _selectedContacts.isNotEmpty) { + rawPhone = _selectedContacts[0]['phone']!; + } + + if (rawPhone.isEmpty || _msgController.text.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("شماره و متن الزامی است"))); + return; + } + + final normalizedPhone = ContactHelper.normalizePhone(rawPhone); + final messageText = _msgController.text.trim(); + final symmetricKey = _keyController.text.trim(); + + if (_selectedSecurityLevel == 'symmetric' && symmetricKey.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('برای رمزنگاری متقارن، کلید لازم است')), + ); + return; + } + + setState(() => isSending = true); + + try { + final result = await SecureMessagingService.instance.sendMessage( + normalizedPhone, + messageText, + securityLevel: _selectedSecurityLevel, + symmetricKey: _selectedSecurityLevel == 'symmetric' ? symmetricKey : null, + ); + + if (!mounted) return; + + final sentText = result['sentText'] == true; + final notice = result['notice'] as String? ?? ''; + final snackText = sentText + ? (notice == 'sent_fragmented' ? 'پیام چندبخشی ارسال شد' : 'پیام ارسال شد') + : notice; + + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(snackText))); + setState(() => isSending = false); + + if (sentText) { + Future.delayed(const Duration(milliseconds: 500), () { + if (mounted) { + Navigator.pushReplacement( + context, + MaterialPageRoute( + builder: (_) => ChatScreen(address: normalizedPhone), + ), + result: true, + ); + } + }); + } + return; + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('خطا: $e')), + ); + setState(() => isSending = false); + return; + } + } + + @override + Widget build(BuildContext context) { + bool isGroupMode = _selectedContacts.length > 1; + + return Scaffold( + backgroundColor: AppTheme.darkBg, + extendBodyBehindAppBar: true, + appBar: PreferredSize( + preferredSize: const Size.fromHeight(kToolbarHeight + 8), + child: AppTheme.glassWrapper( + radius: 0, + sigma: 18, + child: AppBar( + backgroundColor: Colors.transparent, + elevation: 0, + centerTitle: true, + title: Text(isGroupMode ? "ساخت گروه جدید" : "پیام جدید", + style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.white)), + foregroundColor: Colors.white, + ), + ), + ), + body: Stack( + children: [ + Positioned.fill(child: CustomPaint(painter: MeshBackgroundPainter())), + SingleChildScrollView( + padding: EdgeInsets.fromLTRB(20, MediaQuery.of(context).padding.top + kToolbarHeight + 20, 20, 40), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (!_loadingSims && _simCards.length > 1) + Container( + margin: const EdgeInsets.only(bottom: 20), + height: 40, + child: ListView.builder( + scrollDirection: Axis.horizontal, + itemCount: _simCards.length, + itemBuilder: (context, index) { + final sim = _simCards[index]; + final isSelected = _selectedSim == sim; + return Padding( + padding: const EdgeInsets.only(right: 10), + child: ChoiceChip( + label: Text("${sim['carrierName']} (Slot ${sim['slotIndex'] + 1})"), + selected: isSelected, + onSelected: (selected) => setState(() => _selectedSim = sim), + selectedColor: primaryColor, + labelStyle: TextStyle( + color: isSelected ? Colors.white : Colors.white70, + fontSize: 13), + backgroundColor: Colors.white.withValues(alpha: 0.05), + ), + ); + }, + ), + ), + + // --- بخش گیرندگان --- + AppTheme.glassWrapper( + radius: 20, + sigma: 10, + child: Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.03), + border: Border.all(color: Colors.white.withValues(alpha: 0.1), width: 0.5), + borderRadius: BorderRadius.circular(20), + ), + child: Column( + children: [ + if (_selectedContacts.isNotEmpty) + Container( + width: double.infinity, + margin: const EdgeInsets.only(bottom: 12), + child: Wrap( + spacing: 8, + runSpacing: 8, + children: _selectedContacts.asMap().entries.map((entry) { + return Chip( + avatar: CircleAvatar( + backgroundColor: primaryColor.withValues(alpha: 0.8), + child: Text( + entry.value['name']!.isNotEmpty ? entry.value['name']![0] : "?", + style: const TextStyle(color: Colors.white, fontSize: 12)), + ), + label: Text(entry.value['name']!, style: const TextStyle(color: Colors.white, fontSize: 13)), + deleteIcon: const Icon(Icons.close, size: 16, color: Colors.white70), + onDeleted: () => _removeContact(entry.key), + backgroundColor: Colors.white.withValues(alpha: 0.1), + side: BorderSide.none, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + ); + }).toList(), + ), + ), + if (isGroupMode) + Padding( + padding: const EdgeInsets.only(bottom: 12), + child: TextField( + controller: _groupNameController, + style: const TextStyle(color: Colors.white), + decoration: InputDecoration( + labelText: "نام گروه", + labelStyle: const TextStyle(color: Colors.white60), + prefixIcon: const Icon(Icons.groups_rounded, color: Colors.white70), + filled: true, + fillColor: Colors.white.withValues(alpha: 0.05), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + ), + ), + ), + Row( + children: [ + Expanded( + child: TextField( + controller: _phoneController, + keyboardType: TextInputType.phone, + enabled: !isGroupMode && _selectedContacts.isEmpty, + style: const TextStyle(color: Colors.white), + decoration: InputDecoration( + labelText: "شماره گیرنده", + labelStyle: const TextStyle(color: Colors.white60), + prefixIcon: const Icon(Icons.phone_iphone_rounded, color: Colors.white70), + filled: true, + fillColor: Colors.white.withValues(alpha: 0.05), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + ), + ), + ), + const SizedBox(width: 8), + _buildSmallButton(Icons.sync_rounded, Colors.orangeAccent, () => _forceSyncContacts(silent: false)), + const SizedBox(width: 8), + _buildSmallButton(Icons.person_add_rounded, primaryColor, _openContactSearch), + ], + ), + ], + ), + ), + ), + + const SizedBox(height: 18), + + // --- بخش تنظیمات امنیتی --- + if (!isGroupMode) ...[ + _buildSecurityModeCard(), + const SizedBox(height: 18), + ], + + if (isGroupMode || _selectedSecurityLevel == 'symmetric') + AppTheme.glassWrapper( + radius: 18, + child: Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.03), + borderRadius: BorderRadius.circular(18), + border: Border.all(color: Colors.white.withValues(alpha: 0.1), width: 0.5), + ), + child: TextField( + controller: _keyController, + style: const TextStyle(color: Colors.white), + decoration: InputDecoration( + hintText: isGroupMode ? 'کلید گروه (اختیاری)' : 'کلید رمزنگاری متقارن', + hintStyle: const TextStyle(color: Colors.white30), + icon: const Icon(Icons.vpn_key_rounded, color: Colors.orangeAccent), + border: InputBorder.none, + helperText: isGroupMode + ? 'پیام به‌صورت متقارن برای همه اعضا رمز می‌شود.' + : 'کلید باید در هر دو سمت یکسان باشد.', + helperStyle: const TextStyle(color: Colors.white38, fontSize: 11), + ), + ), + ), + ), + + if (_selectedSecurityLevel == 'asymmetric' && !isGroupMode) + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.indigo.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(18), + border: Border.all(color: Colors.indigo.withValues(alpha: 0.2)), + ), + child: const Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(Icons.shield_rounded, color: Colors.indigoAccent, size: 20), + SizedBox(width: 12), + Expanded( + child: Text( + 'در حالت رمزنگاری غیر متقارن، تبادل کلید خودکار انجام می‌شود. پیام‌های طولانی به‌صورت چندبخشی ارسال می‌شوند.', + style: TextStyle(color: Colors.white70, fontSize: 12, height: 1.5), + ), + ), + ], + ), + ), + + const SizedBox(height: 18), + + // --- بخش متن پیام --- + AppTheme.glassWrapper( + radius: 20, + child: Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.03), + borderRadius: BorderRadius.circular(20), + border: Border.all(color: Colors.white.withValues(alpha: 0.1), width: 0.5), + ), + child: TextField( + controller: _msgController, + maxLength: 600, + maxLines: 6, + minLines: 4, + style: const TextStyle(color: Colors.white), + decoration: const InputDecoration( + hintText: "متن پیام خود را بنویسید...", + hintStyle: TextStyle(color: Colors.white30), + border: InputBorder.none, + counterStyle: TextStyle(color: Colors.white38), + helperText: "استفاده از پروتکل چندبخشی در صورت نیاز.", + helperStyle: TextStyle(color: Colors.white38, fontSize: 11), + ), + ), + ), + ), + + const SizedBox(height: 32), + + // --- دکمه ارسال --- + Container( + height: 56, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(18), + gradient: LinearGradient( + colors: [primaryColor, primaryColor.withValues(alpha: 0.8)], + ), + boxShadow: [ + BoxShadow( + color: primaryColor.withValues(alpha: 0.3), + blurRadius: 15, + offset: const Offset(0, 5), + ), + ], + ), + child: ElevatedButton.icon( + icon: isSending + ? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2)) + : const Icon(Icons.send_rounded, size: 20), + label: Text(isSending ? "در حال ارسال..." : "ارسال پیام", + style: const TextStyle(fontSize: 17, fontWeight: FontWeight.bold)), + onPressed: isSending ? null : _sendMessage, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.transparent, + foregroundColor: Colors.white, + shadowColor: Colors.transparent, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)), + ), + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildSmallButton(IconData icon, Color color, VoidCallback onTap) { + return Container( + decoration: BoxDecoration( + color: color.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(14), + ), + child: IconButton( + icon: Icon(icon, color: color, size: 22), + onPressed: onTap, + splashRadius: 24, + ), + ); + } +} + +// --- Delegate جدید: ورودی List --- +class ContactsSearchDelegate extends SearchDelegate?> { + final List contacts; // لیست سبک + + ContactsSearchDelegate(this.contacts); + + @override + String? get searchFieldLabel => 'جستجو نام مخاطب...'; + + @override + List? buildActions(BuildContext context) { + return [ + if (query.isNotEmpty) + IconButton(icon: const Icon(Icons.clear), onPressed: () => query = ''), + ]; + } + + @override + Widget? buildLeading(BuildContext context) { + return IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () => close(context, null), + ); + } + + @override + Widget buildResults(BuildContext context) => _buildList(context); + @override + Widget buildSuggestions(BuildContext context) => _buildList(context); + + Widget _buildList(BuildContext context) { + if (contacts.isEmpty) return const Center(child: Text("مخاطبی یافت نشد.")); + + final filtered = query.isEmpty + ? contacts + : contacts.where((c) { + final name = c.displayName.toLowerCase(); + final q = query.toLowerCase(); + return name.contains(q); + }).toList(); + + // بررسی اینکه آیا کوئری شبیه شماره تلفن است + final bool isQueryNumeric = query.length >= 3 && RegExp(r'^[0-9+\-*#]+$').hasMatch(query); + + if (filtered.isEmpty && !isQueryNumeric) + return const Center(child: Text("نتیجه‌ای یافت نشد.")); + + return ListView.separated( + itemCount: filtered.length + (isQueryNumeric ? 1 : 0), + separatorBuilder: (ctx, i) => const Divider(height: 1), + itemBuilder: (context, index) { + if (isQueryNumeric && index == 0) { + return ListTile( + leading: const CircleAvatar( + backgroundColor: Colors.green, + child: Icon(Icons.phone, color: Colors.white), + ), + title: Text("افزودن شماره دستی: $query", + style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.green)), + subtitle: const Text("استفاده از این شماره"), + onTap: () => close(context, {'name': query, 'phone': query}), + ); + } + + final contact = filtered[isQueryNumeric ? index - 1 : index]; + return ListTile( + leading: CircleAvatar( + backgroundColor: Colors.indigo.shade100, + child: Text( + contact.displayName.isNotEmpty ? contact.displayName[0] : "?", + style: TextStyle(color: Colors.indigo.shade900)), + ), + title: Text(contact.displayName, + style: const TextStyle(fontWeight: FontWeight.bold)), + subtitle: + const Text("برای انتخاب کلیک کنید"), // شماره هنوز معلوم نیست + onTap: () => _onContactSelect(context, contact.id), + ); + }, + ); + } + + // --- دریافت شماره فقط زمان کلیک --- + Future _onContactSelect(BuildContext context, String contactId) async { + showDialog( + context: context, + barrierDismissible: false, + builder: (_) => const Center(child: CircularProgressIndicator())); + try { + // اینجا شماره را از گوشی می‌گیریم + final fullContact = await ContactHelper.getFullContact(contactId); + if (context.mounted) Navigator.pop(context); + + if (fullContact == null || fullContact.phones.isEmpty) { + if (context.mounted) + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("این مخاطب شماره تلفن ندارد"))); + return; + } + + if (fullContact.phones.length == 1) { + close(context, { + 'name': fullContact.displayName, + 'phone': fullContact.phones.first.number + }); + } else { + _showPhoneSelection(context, fullContact); + } + } catch (e) { + if (context.mounted) Navigator.pop(context); + } + } + + void _showPhoneSelection(BuildContext context, Contact contact) { + showDialog( + context: context, + builder: (_) => SimpleDialog( + title: Text("انتخاب شماره ${contact.displayName}"), + children: contact.phones + .map((p) => SimpleDialogOption( + onPressed: () { + Navigator.pop(context); + close(context, + {'name': contact.displayName, 'phone': p.number}); + }, + child: Text(p.number), + )) + .toList(), + ), + ); + } +} diff --git a/lib/screens/group_chat_screen.dart b/lib/screens/group_chat_screen.dart new file mode 100644 index 0000000..7fdb9d6 --- /dev/null +++ b/lib/screens/group_chat_screen.dart @@ -0,0 +1,931 @@ +import 'dart:async'; +import 'dart:ui'; +import 'package:another_telephony/telephony.dart'; +import '../utils/app_theme.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_contacts/flutter_contacts.dart'; +import 'package:permission_handler/permission_handler.dart'; + +import '../utils/contact_helper.dart'; +import '../utils/database_helper.dart'; +import '../utils/protocol_helper.dart'; +import '../utils/secure_crypto_helper.dart'; +import '../utils/secure_messaging_service.dart'; +import '../models/chat_model.dart'; +import '../widgets/message_bubble.dart'; + +class MeshBackgroundPainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + final paint = Paint()..maskFilter = const MaskFilter.blur(BlurStyle.normal, 80); + + // Warm accent for groups + paint.color = const Color(0xFFFFF3E0).withValues(alpha: 0.35); + canvas.drawCircle(Offset(size.width * 0.8, size.height * 0.1), 160, paint); + + paint.color = const Color(0xFFF3E5F5).withValues(alpha: 0.35); + canvas.drawCircle(Offset(size.width * 0.2, size.height * 0.8), 200, paint); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} + +class GroupMessageModel { + int? id; + String body; + String? rawBody; + int date; + bool isMe; + MessageStatus status; + String? senderPhone; + String? senderName; + bool isSecure; + bool canRetryDecryption; + String? packetId; + String? packetMode; + bool isPendingMultipart; + + GroupMessageModel({ + this.id, + required this.body, + this.rawBody, + required this.date, + required this.isMe, + required this.status, + this.senderPhone, + this.senderName, + this.isSecure = false, + this.canRetryDecryption = false, + this.packetId, + this.packetMode, + this.isPendingMultipart = false, + }); +} + +class GroupChatScreen extends StatefulWidget { + final int groupId; + final String groupName; + + const GroupChatScreen({ + super.key, + required this.groupId, + required this.groupName, + }); + + @override + State createState() => _GroupChatScreenState(); +} + +class _GroupChatScreenState extends State { + final Telephony telephony = Telephony.instance; + static const platform = MethodChannel('com.example.saba/sim_cards'); + + final TextEditingController _msgController = TextEditingController(); + final TextEditingController _keyController = TextEditingController(); + final ScrollController _scrollController = ScrollController(); + + Color get primaryColor => Theme.of(context).primaryColor; + final Color backgroundColor = const Color(0xFFF5F7FA); + + List messages = []; + List> members = []; + List> _simCards = []; + Map? _selectedSim; + StreamSubscription? _msgSub; + + bool _loadingSims = true; + String currentGroupName = ''; + + @override + void initState() { + super.initState(); + currentGroupName = widget.groupName; + SecureMessagingService.instance.currentChatPhone = 'group_${widget.groupId}'; + DatabaseHelper.instance.markGroupAsRead(widget.groupId); + _fetchSimCards(); + _loadGroupKeyAndData(); + _scrollController.addListener(_onScroll); + _msgSub = SecureMessagingService.instance.messageStream.listen((data) { + if (data['phone'] == 'group_${widget.groupId}') { + if (!mounted) return; + final body = data['body'] as String? ?? ''; + final packetId = data['packetId'] as String?; + final isMultipartComplete = data['isMultipartComplete'] as bool? ?? false; + final isMeEvent = data['isMe'] as bool? ?? false; + + if (body == 'REFRESH') { + _loadData(); + return; + } + + if (packetId != null) { + setState(() { + final idx = messages.indexWhere((m) => m.packetId == packetId); + if (idx != -1) { + messages[idx].body = body; + messages[idx].isPendingMultipart = !isMultipartComplete; + if (isMultipartComplete) { + messages[idx].status = isMeEvent ? MessageStatus.sent : MessageStatus.received; + } + } else { + // If it's a new fragmented message or just completed but not in list + _loadData(); + } + }); + } else { + _loadData(); + } + } + }); + _keyController.addListener(() { + if (mounted) _onKeyChanged(); + }); + } + + void _onScroll() { + if (!_scrollController.hasClients) return; + // Group chat might need pagination in the future, + // for now we just monitor the state to prevent jumps. + } + + @override + void dispose() { + if (SecureMessagingService.instance.currentChatPhone == 'group_${widget.groupId}') { + SecureMessagingService.instance.currentChatPhone = null; + } + _msgSub?.cancel(); + _msgController.dispose(); + _keyController.dispose(); + _scrollController.dispose(); + super.dispose(); + } + + Future _loadGroupKeyAndData() async { + final groups = await DatabaseHelper.instance.getGroups(); + final group = groups.cast?>().firstWhere( + (g) => g?['id'] == widget.groupId, + orElse: () => null, + ); + if (group != null && (group['group_key'] as String?)?.isNotEmpty == true) { + _keyController.text = group['group_key'] as String; + } + await _loadData(); + } + + void _onKeyChanged() { + DatabaseHelper.instance.updateGroupKey(widget.groupId, _keyController.text); + _loadData(); + } + + bool _isSecurePlaceholderBody(String body) { + return body.startsWith('پیام امن گروهی') || + body.startsWith('بازگشایی پیام امن گروهی') || + body.contains(' ::PAYLOAD::'); + } + + String? _extractPayload(String body) { + const separator = ' ::PAYLOAD::'; + final splitIndex = body.lastIndexOf(separator); + if (splitIndex == -1) return null; + final payload = body.substring(splitIndex + separator.length).trim(); + return payload.isEmpty ? null : payload; + } + + Future _handleRetryDecryption(GroupMessageModel msg) async { + String? payload = _extractPayload(msg.body); + if (payload == null && msg.rawBody != null) { + payload = ProtocolHelper.parseMessage(msg.rawBody!)['payload'] as String?; + } + if (payload == null) return; + + final keyController = TextEditingController(text: _keyController.text.trim()); + showDialog( + context: context, + builder: (ctx) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: const Text('بازگشایی دستی پیام گروه'), + content: TextField( + controller: keyController, + decoration: const InputDecoration( + hintText: 'کلید گروه', + border: OutlineInputBorder(), + ), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('لغو')), + ElevatedButton( + onPressed: () async { + if (keyController.text.trim().isEmpty) return; + final decrypted = await SecureMessagingService.instance.decryptWithKey( + payload!, + keyController.text.trim(), + ); + if (!mounted) return; + Navigator.pop(ctx); + if (decrypted != null) { + _keyController.text = keyController.text.trim(); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('پیام گروهی بازگشایی شد.')), + ); + _loadData(); + } else { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('کلید گروه نادرست است.')), + ); + } + }, + child: const Text('بازگشایی'), + ), + ], + ), + ); + } + + Future> _resolveGroupMessageState(String rawBody, + {bool isMe = false, bool dbIsSecure = false}) async { + final parsed = ProtocolHelper.parseMessage(rawBody); + final type = parsed['type'] as String; + final key = _keyController.text.trim(); + + String body = rawBody; + bool isSecure = dbIsSecure || type != 'plain' || rawBody.contains(' ::PAYLOAD::'); + bool canRetryDecryption = false; + + if (type == 'sym' && parsed['isGroup'] == true) { + final payload = parsed['payload'] as String?; + if (payload != null && key.isNotEmpty) { + final decrypted = await SecureMessagingService.instance.decryptWithKey(payload, key); + if (decrypted != null) { + body = decrypted; + } else { + final label = isMe ? 'ارسال شده' : 'دریافت شد'; + body = 'بازگشایی پیام امن گروهی $label ناموفق بود. کلید گروه را بررسی کنید. ::PAYLOAD::$payload'; + canRetryDecryption = true; + } + } else if (payload != null) { + final label = isMe ? 'ارسال شده' : 'دریافت شد'; + body = 'پیام امن گروهی $label. برای مشاهده، کلید گروه را وارد کنید. ::PAYLOAD::$payload'; + canRetryDecryption = true; + } + } else if (type == 'sfra' && parsed['isGroup'] == true) { + body = 'در حال دریافت قطعات... (${parsed['partNo']}/${parsed['totalParts']})'; + isSecure = true; + } else if (rawBody.contains(' ::PAYLOAD::')) { + canRetryDecryption = true; + } + + return { + 'body': body, + 'isSecure': isSecure, + 'canRetryDecryption': canRetryDecryption, + 'packetId': parsed['packetId'], + 'packetMode': type == 'plain' ? null : (type == 'afrag' ? 'AE' : 'SYM'), + 'isPendingMultipart': type == 'sfra' || type == 'afrag', + }; + } + + Future _fetchSimCards() async { + if (!await Permission.phone.request().isGranted) { + if (mounted) setState(() => _loadingSims = false); + return; + } + try { + final List result = await platform.invokeMethod('getSimCards'); + final cleanList = result.map((e) { + final rawMap = e as Map; + return rawMap.map((key, value) => MapEntry(key.toString(), value)); + }).toList(); + if (!mounted) return; + setState(() { + _simCards = cleanList; + if (_simCards.isNotEmpty) _selectedSim = _simCards.first; + _loadingSims = false; + }); + } catch (_) { + if (mounted) setState(() => _loadingSims = false); + } + } + + bool _isLoading = false; + bool _needsReload = false; + + Future _loadData() async { + if (_isLoading) { + _needsReload = true; + return; + } + _isLoading = true; + _needsReload = false; + + try { + final dbMessages = await DatabaseHelper.instance.getGroupMessages(widget.groupId); + final dbMembers = await DatabaseHelper.instance.getGroupMembers(widget.groupId); + + final uiMessages = []; + for (final m in dbMessages) { + final raw = m['body'] as String; + final senderPhone = m['sender_phone'] as String?; + final senderName = senderPhone != null ? ContactHelper.getName(senderPhone) : 'من'; + final dbIsSecure = (m['is_secure'] as int? ?? 0) == 1; + final resolved = await _resolveGroupMessageState(raw, isMe: senderPhone == null, dbIsSecure: dbIsSecure); + + uiMessages.add(GroupMessageModel( + id: m['id'] as int?, + body: resolved['body'] as String, + rawBody: raw, + date: m['date'] as int, + isMe: senderPhone == null, + status: MessageStatus.received, + senderPhone: senderPhone, + senderName: senderName, + isSecure: resolved['isSecure'] as bool, + canRetryDecryption: + resolved['canRetryDecryption'] as bool || _isSecurePlaceholderBody(resolved['body'] as String), + packetId: resolved['packetId'] as String?, + packetMode: resolved['packetMode'] as String?, + isPendingMultipart: resolved['isPendingMultipart'] as bool? ?? false, + )); + } + + if (mounted) { + setState(() { + messages = uiMessages; + members = dbMembers; + }); + } + } finally { + _isLoading = false; + if (_needsReload) _loadData(); + } + } + + void _deleteMessage(int messageId) { + showDialog( + context: context, + builder: (ctx) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: const Text('حذف پیام'), + content: const Text('آیا مطمئن هستید؟'), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('لغو')), + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: Colors.red, foregroundColor: Colors.white), + onPressed: () async { + Navigator.pop(ctx); + await DatabaseHelper.instance.deleteGroupMessage(messageId); + _loadData(); + }, + child: const Text('حذف'), + ), + ], + ), + ); + } + + void _editGroupName() { + final nameController = TextEditingController(text: currentGroupName); + showDialog( + context: context, + builder: (ctx) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: const Text('تغییر نام گروه'), + content: TextField( + controller: nameController, + decoration: InputDecoration( + labelText: 'نام جدید', + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)), + ), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('لغو')), + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: primaryColor, foregroundColor: Colors.white), + onPressed: () async { + if (nameController.text.trim().isEmpty) return; + await DatabaseHelper.instance.updateGroupName(widget.groupId, nameController.text.trim()); + if (!mounted) return; + setState(() => currentGroupName = nameController.text.trim()); + Navigator.pop(ctx); + }, + child: const Text('ذخیره'), + ), + ], + ), + ); + } + + void _showGroupInfo() { + showDialog( + context: context, + builder: (context) { + return StatefulBuilder( + builder: (context, setStateDialog) { + return AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('مدیریت اعضا', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + IconButton( + icon: Container( + padding: const EdgeInsets.all(4), + decoration: BoxDecoration( + color: primaryColor.withValues(alpha: 0.1), + shape: BoxShape.circle, + ), + child: Icon(Icons.person_add, color: primaryColor, size: 20), + ), + onPressed: () { + Navigator.pop(context); + _addNewMember(); + }, + ), + ], + ), + content: SizedBox( + width: double.maxFinite, + child: members.isEmpty + ? const Center(child: Text('هیچ عضوی وجود ندارد', style: TextStyle(color: Colors.grey))) + : ListView.separated( + shrinkWrap: true, + itemCount: members.length, + separatorBuilder: (_, __) => const Divider(), + itemBuilder: (_, index) { + final member = members[index]; + return ListTile( + contentPadding: EdgeInsets.zero, + leading: CircleAvatar( + backgroundColor: Colors.orange.shade100, + child: Text( + (member['name'] as String)[0], + style: TextStyle(color: Colors.orange.shade900), + ), + ), + title: Text( + member['name'] as String, + style: const TextStyle(fontWeight: FontWeight.bold), + ), + subtitle: Text(member['phone'] as String), + trailing: IconButton( + icon: const Icon(Icons.delete_outline, color: Colors.red), + onPressed: () async { + await DatabaseHelper.instance.removeGroupMember( + widget.groupId, + member['phone'] as String, + ); + final newMembers = await DatabaseHelper.instance.getGroupMembers(widget.groupId); + if (!mounted) return; + setState(() => members = newMembers); + setStateDialog(() {}); + }, + ), + ); + }, + ), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('بستن')), + ], + ); + }, + ); + }, + ); + } + + Future _addNewMember() async { + showDialog( + context: context, + barrierDismissible: false, + builder: (_) => const Center(child: CircularProgressIndicator()), + ); + final contacts = await ContactHelper.getContactsLight(); + if (mounted) Navigator.pop(context); + + if (contacts.isEmpty) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('مخاطبی یافت نشد'))); + } + return; + } + + if (!mounted) return; + final result = await showSearch?>( + context: context, + delegate: ContactsSearchDelegate(contacts), + ); + + if (result == null) return; + final added = await DatabaseHelper.instance.addMemberToGroup( + widget.groupId, + result['name']!, + result['phone']!, + ); + if (!mounted) return; + + if (added) { + await _loadData(); + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('عضو جدید اضافه شد'))); + } else { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('این عضو قبلاً در گروه وجود دارد')), + ); + } + } + + Future _sendGroupMessage() async { + final text = _msgController.text.trim(); + final key = _keyController.text.trim(); + if (text.isEmpty) return; + + String? rawBody; + if (key.isNotEmpty) { + final crypto = SecureCryptoHelper(); + rawBody = '@G:SYM|${await crypto.encryptSymmetric(text, key)}'; + } + + final tempMsg = GroupMessageModel( + body: text, + rawBody: rawBody, + date: DateTime.now().millisecondsSinceEpoch, + isMe: true, + status: MessageStatus.sending, + senderName: 'من', + isSecure: key.isNotEmpty, + ); + + setState(() { + messages.insert(0, tempMsg); + _msgController.clear(); + }); + + try { + final groupMemberPhones = members.map((m) => m['phone'] as String).toList(); + await SecureMessagingService.instance.sendGroupSecureMessage( + widget.groupId, + groupMemberPhones, + text, + key, + ); + + if (!mounted) return; + setState(() => tempMsg.status = MessageStatus.sent); + Future.delayed(const Duration(milliseconds: 1200), _loadData); + } catch (_) { + if (!mounted) return; + setState(() => tempMsg.status = MessageStatus.failed); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppTheme.darkBg, + extendBodyBehindAppBar: true, + resizeToAvoidBottomInset: true, + appBar: PreferredSize( + preferredSize: const Size.fromHeight(kToolbarHeight + 8), + child: AppTheme.glassWrapper( + radius: 0, + sigma: 18, + child: AppBar( + backgroundColor: Colors.transparent, + elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () => Navigator.of(context).pop(), + ), + title: InkWell( + onTap: _editGroupName, + overlayColor: WidgetStateProperty.all(Colors.transparent), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Hero( + tag: 'avatar_${currentGroupName}_group', + child: Container( + width: 38, + height: 38, + decoration: const BoxDecoration( + shape: BoxShape.circle, + gradient: LinearGradient( + colors: [Colors.orange, Colors.orangeAccent], + ), + ), + child: const Center( + child: Icon(Icons.groups, color: Colors.white, size: 22), + ), + ), + ), + const SizedBox(width: 10), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(currentGroupName, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white)), + Text('${members.length} عضو', style: const TextStyle(fontSize: 11, color: Colors.white70)), + ], + ), + const SizedBox(width: 6), + const Icon(Icons.edit_outlined, size: 14, color: Colors.white70), + ], + ), + ), + actions: [ + IconButton( + icon: const Icon(Icons.group_outlined, color: Colors.white), + tooltip: 'مدیریت اعضا', + onPressed: _showGroupInfo, + ), + ], + ), + ), + ), + body: Stack( + children: [ + Positioned.fill(child: CustomPaint(painter: MeshBackgroundPainter())), + Column( + children: [ + SizedBox(height: MediaQuery.of(context).padding.top + kToolbarHeight + 8), + Expanded( + child: messages.isEmpty + ? Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.mark_chat_unread_outlined, size: 60, color: Colors.grey[300]), + const SizedBox(height: 10), + Text('پیامی ارسال نشده است', style: TextStyle(color: Colors.grey[500])), + ], + ), + ) + : ListView.builder( + key: const PageStorageKey('group_chat_list'), + controller: _scrollController, + reverse: true, + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20), + itemCount: messages.length, + itemBuilder: (context, index) { + final msg = messages[index]; + return GestureDetector( + onLongPress: () { + if (msg.id != null) { + _deleteMessage(msg.id!); + } + }, + child: Column( + crossAxisAlignment: msg.isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start, + children: [ + if (!msg.isMe && msg.senderName != null) + Padding( + padding: const EdgeInsets.only(left: 12, bottom: 4), + child: Text( + msg.senderName!, + style: const TextStyle( + fontSize: 10, + color: Colors.indigo, + fontWeight: FontWeight.bold, + ), + ), + ), + MessageBubble( + body: msg.body, + rawBody: msg.rawBody, + date: msg.date, + isMe: msg.isMe, + status: msg.status, + isSecure: msg.isSecure, + canRetryDecryption: msg.canRetryDecryption, + onRetryDecryption: () => _handleRetryDecryption(msg), + packetMode: msg.packetMode, + isPendingMultipart: msg.isPendingMultipart, + ), + ], + ), + ); + }, + ), + ), + AppTheme.glassWrapper( + radius: 0, + sigma: 15, + child: Container( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 24), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.03), + border: Border( + top: BorderSide(color: Colors.white.withValues(alpha: 0.08), width: 0.5), + ), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (!_loadingSims && _simCards.length > 1) + SizedOverflowBox( + size: const Size.fromHeight(35), + child: ListView.builder( + scrollDirection: Axis.horizontal, + itemCount: _simCards.length, + itemBuilder: (context, index) { + final sim = _simCards[index]; + return Padding( + padding: const EdgeInsets.only(right: 8), + child: ChoiceChip( + label: Text(sim['displayName']?.toString() ?? 'SIM ${index + 1}'), + selected: _selectedSim == sim, + onSelected: (_) => setState(() => _selectedSim = sim), + ), + ); + }, + ), + ), + const SizedBox(height: 12), + Row( + children: [ + Expanded( + child: TextField( + controller: _keyController, + style: const TextStyle(color: Colors.white, fontSize: 13), + decoration: InputDecoration( + hintText: 'کلید امنیتی گروه (اختیاری)', + hintStyle: const TextStyle(color: Colors.white30), + prefixIcon: const Icon(Icons.vpn_key_rounded, size: 18, color: Colors.orangeAccent), + filled: true, + fillColor: Colors.white.withValues(alpha: 0.05), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 0), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide.none, + ), + ), + ), + ), + ], + ), + const SizedBox(height: 12), + Row( + children: [ + Expanded( + child: TextField( + controller: _msgController, + minLines: 1, + maxLines: 4, + style: const TextStyle(color: Colors.white), + decoration: InputDecoration( + hintText: 'پیام گروهی...', + hintStyle: const TextStyle(color: Colors.white30), + filled: true, + fillColor: Colors.white.withValues(alpha: 0.05), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(20), + borderSide: BorderSide.none, + ), + ), + ), + ), + const SizedBox(width: 12), + Container( + height: 48, + width: 48, + decoration: BoxDecoration( + shape: BoxShape.circle, + gradient: const LinearGradient( + colors: [Colors.indigo, Colors.indigoAccent], + ), + boxShadow: [ + BoxShadow( + color: Colors.indigo.withValues(alpha: 0.3), + blurRadius: 12, + spreadRadius: 1, + ), + ], + ), + child: IconButton( + icon: const Icon(Icons.send_rounded, color: Colors.white, size: 22), + onPressed: _sendGroupMessage, + ), + ), + ], + ), + ], + ), + ), + ), + ], + ), + ], + ), + ); + } +} + +class ContactsSearchDelegate extends SearchDelegate?> { + final List contacts; + + ContactsSearchDelegate(this.contacts); + + @override + String? get searchFieldLabel => 'جست‌وجو نام مخاطب...'; + + @override + List? buildActions(BuildContext context) { + return [ + if (query.isNotEmpty) + IconButton( + icon: const Icon(Icons.clear), + onPressed: () => query = '', + ), + ]; + } + + @override + Widget? buildLeading(BuildContext context) { + return IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () => close(context, null), + ); + } + + @override + Widget buildResults(BuildContext context) => _buildList(context); + + @override + Widget buildSuggestions(BuildContext context) => _buildList(context); + + Widget _buildList(BuildContext context) { + final filtered = query.isEmpty + ? contacts + : contacts.where((c) => c.displayName.toLowerCase().contains(query.toLowerCase())).toList(); + + if (filtered.isEmpty) { + return const Center(child: Text('نتیجه‌ای یافت نشد.')); + } + + return ListView.builder( + itemCount: filtered.length, + itemBuilder: (context, index) { + final contact = filtered[index]; + return ListTile( + leading: CircleAvatar( + backgroundColor: Colors.indigo.shade100, + child: Text( + contact.displayName.isNotEmpty ? contact.displayName[0] : '?', + style: TextStyle(color: Colors.indigo.shade900), + ), + ), + title: Text(contact.displayName), + onTap: () => _onContactSelect(context, contact.id), + ); + }, + ); + } + + Future _onContactSelect(BuildContext context, String contactId) async { + showDialog( + context: context, + barrierDismissible: false, + builder: (_) => const Center(child: CircularProgressIndicator()), + ); + try { + final fullContact = await ContactHelper.getFullContact(contactId); + if (context.mounted) Navigator.pop(context); + if (fullContact == null || fullContact.phones.isEmpty) return; + + if (fullContact.phones.length == 1) { + close(context, { + 'name': fullContact.displayName, + 'phone': fullContact.phones.first.number, + }); + } else { + _showPhoneSelection(context, fullContact); + } + } catch (_) { + if (context.mounted) Navigator.pop(context); + } + } + + void _showPhoneSelection(BuildContext context, Contact contact) { + showDialog( + context: context, + builder: (_) => SimpleDialog( + title: Text(contact.displayName), + children: contact.phones + .map( + (p) => SimpleDialogOption( + onPressed: () { + Navigator.pop(context); + close(context, { + 'name': contact.displayName, + 'phone': p.number, + }); + }, + child: Text(p.number), + ), + ) + .toList(), + ), + ); + } +} diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart new file mode 100644 index 0000000..0f5ebc0 --- /dev/null +++ b/lib/screens/home_screen.dart @@ -0,0 +1,771 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:another_telephony/telephony.dart'; +import '../utils/contact_helper.dart'; +import '../utils/database_helper.dart'; +import 'chat_screen.dart'; +import 'group_chat_screen.dart'; +import 'compose_screen.dart'; +import 'settings_screen.dart'; +import '../utils/secure_messaging_service.dart'; +import '../utils/protocol_helper.dart'; +import '../utils/notification_helper.dart'; +import 'package:flutter_contacts/flutter_contacts.dart'; +import '../utils/app_theme.dart'; + +class HomeScreen extends StatefulWidget { + const HomeScreen({super.key}); + @override + State createState() => _HomeScreenState(); +} + +class _HomeScreenState extends State + with SingleTickerProviderStateMixin { + late TabController _tabController; + List> conversations = []; + List> groups = []; + List contacts = []; + final TextEditingController _contactSearchController = + TextEditingController(); + bool isLoading = true; + bool isLoadingContacts = false; + final Telephony telephony = Telephony.instance; + Map unreadCounts = {}; + Map groupUnreadCounts = {}; + + // رنگ‌های تم حرفه‌ای + Color get primaryColor => Theme.of(context).primaryColor; + Color get secondaryColor => Theme.of(context).colorScheme.secondary; + final Color backgroundColor = AppTheme.darkBg; + + @override + void initState() { + super.initState(); + _tabController = TabController(length: 3, vsync: this); + _tabController.addListener(() { + if (mounted) setState(() {}); + if (_tabController.index == 2 && contacts.isEmpty) { + _loadContacts(); + } + }); + // Delay heavy initialization until transition finishes (800ms) + // This makes the logo transition buttery smooth (60fps) + Future.delayed(const Duration(milliseconds: 900), () { + if (mounted) initApp(); + }); + _initMessageStreamListener(); + } + + StreamSubscription? _messageSubscription; + StreamSubscription? _notificationSubscription; + + void _initMessageStreamListener() { + _messageSubscription = + SecureMessagingService.instance.messageStream.listen((data) { + Future.delayed(const Duration(milliseconds: 500), () { + if (mounted) loadData(); + }); + }); + + _notificationSubscription = + NotificationHelper.instance.notificationStream.listen((payload) { + if (!mounted) return; + if (payload.startsWith('group_')) { + final groupId = int.tryParse(payload.replaceFirst('group_', '')); + if (groupId != null) { + // Find group name + String name = "گروه"; + for (var g in groups) { + if (g['id'] == groupId) { + name = g['name']; + break; + } + } + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => + GroupChatScreen(groupId: groupId, groupName: name), + ), + ).then((_) => loadData()); + } + } else { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => ChatScreen(address: payload), + ), + ).then((_) => loadData()); + } + }); + } + + @override + void dispose() { + _tabController.dispose(); + _contactSearchController.dispose(); + _messageSubscription?.cancel(); + _notificationSubscription?.cancel(); + super.dispose(); + } + + void initApp() { + loadMessages(); + // همگام‌سازی نام مخاطبین در پس‌زمینه + Future.delayed(const Duration(seconds: 1), () async { + // ابتدا از کش محلی لود میکنیم برای سرعت + await ContactHelper.loadFromLocalCache(); + if (mounted) setState(() {}); + + // سپس با دستگاه سینک میکنیم برای آپدیت نام‌های جدید + await ContactHelper.syncWithDevice(); + if (mounted) setState(() {}); + }); + } + + void loadData() async { + setState(() => isLoading = true); + await loadMessages(); + final g = await DatabaseHelper.instance.getGroups(); + final counts = {}; + for (final group in g) { + counts[group['id']] = + await DatabaseHelper.instance.getGroupUnreadCount(group['id']); + } + if (_tabController.index == 2 || contacts.isNotEmpty) { + await _loadContacts(); + } + if (mounted) { + setState(() { + groups = g; + groupUnreadCounts = counts; + isLoading = false; + }); + } + } + + Future _loadContacts() async { + if (isLoadingContacts) return; + setState(() => isLoadingContacts = true); + try { + final c = await ContactHelper.getContactsLight(); + if (mounted) { + setState(() { + contacts = c; + isLoadingContacts = false; + }); + } + } catch (e) { + if (mounted) setState(() => isLoadingContacts = false); + } + } + + Future _startChatFromContact(Contact contact) async { + showDialog( + context: context, + barrierDismissible: false, + builder: (_) => const Center(child: CircularProgressIndicator()), + ); + + try { + final full = await ContactHelper.getFullContact(contact.id); + if (mounted) Navigator.pop(context); + + if (full == null || full.phones.isEmpty) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("این مخاطب شماره تلفن ندارد")), + ); + } + return; + } + + String phone = full.phones.first.number; + if (full.phones.length > 1) { + if (!mounted) return; + final selected = await showDialog( + context: context, + builder: (ctx) => SimpleDialog( + title: Text("انتخاب شماره ${full.displayName}"), + children: full.phones + .map((p) => SimpleDialogOption( + onPressed: () => Navigator.pop(ctx, p.number), + child: Text(p.number), + )) + .toList(), + ), + ); + if (selected == null) return; + phone = selected; + } + + if (mounted) { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => ChatScreen(address: phone), + ), + ).then((_) => loadData()); + } + } catch (e) { + if (mounted) Navigator.pop(context); + } + } + + Future loadMessages() async { + try { + // Fetch from local cache for instant updates + final localRows = await DatabaseHelper.instance.getConversations(); + + final installDate = + await SecureMessagingService.instance.getInstallDate(); + + // Filter by install date + List> filtered = localRows.where((m) { + if (installDate == null) return true; + final date = m['date'] as int? ?? 0; + return date >= installDate; + }).toList(); + + // Fetch unread counts + final counts = {}; + for (final msg in filtered) { + final addr = msg['address'] as String?; + if (addr != null) { + counts[addr] = await DatabaseHelper.instance.getUnreadCount(addr); + } + } + + if (mounted) { + setState(() { + conversations = filtered; + unreadCounts = counts; + isLoading = false; + }); + } + } catch (e) { + debugPrint("[SABA] Error in local loadMessages: $e"); + if (mounted) setState(() => isLoading = false); + } + } + + void _deleteGroup(int groupId) { + showDialog( + context: context, + builder: (ctx) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: const Text("حذف گروه"), + content: const Text("آیا از حذف این گروه مطمئنید؟"), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx), child: const Text("لغو")), + ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, foregroundColor: Colors.white), + onPressed: () async { + Navigator.pop(ctx); + await DatabaseHelper.instance.deleteGroup(groupId); + if (!mounted) return; + loadData(); + ScaffoldMessenger.of(context) + .showSnackBar(const SnackBar(content: Text("گروه حذف شد"))); + }, + child: const Text("حذف"), + ), + ], + ), + ); + } + + void _deleteIndividualChat(String address) { + showDialog( + context: context, + builder: (ctx) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: const Text("حذف گفتگو"), + content: const Text( + "به دلیل محدودیت‌های اندروید، حذف پیامک‌های سیستمی فقط توسط برنامه پیش‌فرض پیامک امکان‌پذیر است."), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx), child: const Text("باشه")), + ], + ), + ); + } + + Future _addContactToDevice(String phone) async { + if (!await FlutterContacts.requestPermission()) return; + try { + final contact = Contact(phones: [Phone(phone)]); + await FlutterContacts.openExternalInsert(contact); + if (!mounted) return; + loadData(); // همگام‌سازی مجدد بعد از افزودن + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text("خطا در افزودن مخاطب: $e")), + ); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: backgroundColor, + appBar: PreferredSize( + preferredSize: const Size.fromHeight(85), + child: AppTheme.glassWrapper( + radius: 0, + sigma: 18, + child: AppBar( + backgroundColor: Colors.transparent, + elevation: 0, + centerTitle: true, + title: Padding( + padding: const EdgeInsets.only(top: 15), + child: Hero( + tag: 'app_logo', + child: GestureDetector( + onTap: () { + if (mounted) setState(() {}); + }, + child: const Image( + image: AssetImage('صبا بالا.png'), + height: 42, + fit: BoxFit.contain, + ), + ), + ), + ), + actions: [ + IconButton( + icon: const Icon(Icons.settings_outlined, + color: Colors.white, size: 22), + onPressed: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const SettingsScreen()), + ).then((_) => loadData()), + ), + IconButton( + icon: const Icon(Icons.refresh_rounded, + color: Colors.white, size: 22), + onPressed: loadData, + ), + const SizedBox(width: 8), + ], + bottom: PreferredSize( + preferredSize: const Size.fromHeight(50), + child: Container( + color: Colors.transparent, // Let glass show through + child: TabBar( + controller: _tabController, + labelColor: primaryColor, + unselectedLabelColor: Colors.grey, + indicatorColor: primaryColor, + indicatorWeight: 3, + labelStyle: const TextStyle( + fontWeight: FontWeight.bold, fontSize: 16), + dividerColor: Colors.transparent, + tabs: const [ + Tab(text: "گفتگوها"), + Tab(text: "گروه‌ها"), + Tab(text: "مخاطبین"), + ], + ), + ), + ), + ), + ), + ), + body: TabBarView( + controller: _tabController, + children: [ + // --- لیست گفتگوها --- + isLoading + ? Center(child: CircularProgressIndicator(color: primaryColor)) + : conversations.isEmpty + ? _buildEmptyState("هیچ گفتگویی وجود ندارد") + : ListView.builder( + padding: const EdgeInsets.only(top: 10, bottom: 80), + itemCount: conversations.length, + itemBuilder: (context, index) { + final msg = conversations[index]; + final addr = msg['address'] as String? ?? ""; + final displayName = ContactHelper.getName(addr); + final body = msg['body'] as String? ?? ""; + final parsed = ProtocolHelper.parseMessage(body); + final isSecure = parsed['type'] != 'plain'; + final displayText = + isSecure ? "🔒 پیام امن (رمزگذاری شده)" : body; + + return _buildChatCard( + index: index, + title: displayName, + subtitle: displayText, + isEncrypted: isSecure, + unreadCount: unreadCounts[addr] ?? 0, + avatarText: + displayName.isNotEmpty ? displayName[0] : "?", + colorSeed: index, + showAddButton: ContactHelper.isRawNumber(displayName), + onAddContact: () => _addContactToDevice(addr), + onTap: () => Navigator.push( + context, + MaterialPageRoute( + builder: (_) => + ChatScreen(address: addr))) + .then((_) => loadData()), + onLongPress: () => _deleteIndividualChat(addr), + ); + }, + ), + + // --- لیست گروه‌ها --- + groups.isEmpty + ? _buildEmptyState("گروهی ساخته نشده است") + : ListView.builder( + padding: const EdgeInsets.only(top: 10, bottom: 80), + itemCount: groups.length, + itemBuilder: (context, index) { + final group = groups[index]; + return _buildChatCard( + index: index, + title: group['name'], + subtitle: "پیام گروهی", + isEncrypted: false, + isGroup: true, + unreadCount: groupUnreadCounts[group['id']] ?? 0, + avatarText: "#", + colorSeed: index + 5, + onTap: () => Navigator.push( + context, + MaterialPageRoute( + builder: (_) => GroupChatScreen( + groupId: group['id'], + groupName: group['name']))), + onLongPress: () => _deleteGroup(group['id']), + ); + }, + ), + + // --- لیست مخاطبین --- + Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), + child: AppTheme.glassWrapper( + radius: 12, + sigma: 5, + child: TextField( + controller: _contactSearchController, + onChanged: (val) => setState(() {}), + style: const TextStyle(color: Colors.white), + decoration: InputDecoration( + hintText: "جستجو در مخاطبین...", + hintStyle: const TextStyle(color: Colors.white60), + prefixIcon: + const Icon(Icons.search, color: Colors.white70), + filled: true, + fillColor: Colors.white.withValues(alpha: 0.05), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide.none), + contentPadding: const EdgeInsets.symmetric(vertical: 0), + ), + ), + ), + ), + Expanded( + child: isLoadingContacts && contacts.isEmpty + ? Center( + child: CircularProgressIndicator(color: primaryColor)) + : contacts.isEmpty + ? _buildEmptyState("مخاطبی یافت نشد") + : Builder(builder: (context) { + final query = _contactSearchController.text + .trim() + .toLowerCase(); + final filtered = query.isEmpty + ? contacts + : contacts.where((c) { + final name = c.displayName.toLowerCase(); + return name.contains(query); + }).toList(); + + if (filtered.isEmpty) { + return _buildEmptyState("نتیجه‌ای یافت نشد"); + } + + return ListView.builder( + padding: const EdgeInsets.only(bottom: 80), + itemCount: filtered.length, + itemBuilder: (context, index) { + final contact = filtered[index]; + final displayName = contact.displayName; + return _buildChatCard( + index: index, + title: displayName, + subtitle: "شروع گفتگوی جدید", + isEncrypted: false, + avatarText: displayName.isNotEmpty + ? displayName[0] + : "?", + colorSeed: index, + onTap: () => _startChatFromContact(contact), + onLongPress: () {}, + ); + }, + ); + }), + ), + ], + ), + ], + ), + floatingActionButton: FloatingActionButton.extended( + backgroundColor: primaryColor, + icon: Icon(_tabController.index == 0 ? Icons.edit : Icons.group_add, + color: Colors.white), + label: Text(_tabController.index == 0 ? "پیام جدید" : "گروه جدید", + style: const TextStyle( + color: Colors.white, fontWeight: FontWeight.bold)), + onPressed: () => Navigator.push(context, + MaterialPageRoute(builder: (_) => const ComposeScreen())) + .then((res) { + if (res == true) loadData(); + }), + ), + ); + } + + Widget _buildEmptyState(String text) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.chat_bubble_outline, size: 80, color: Colors.grey[400]), + const SizedBox(height: 16), + Text(text, style: TextStyle(color: Colors.grey[600], fontSize: 18)), + ], + ), + ); + } + + Widget _buildChatCard({ + required int index, + required String title, + required String subtitle, + required bool isEncrypted, + required String avatarText, + required int colorSeed, + int unreadCount = 0, + bool isGroup = false, + bool showAddButton = false, + VoidCallback? onAddContact, + required VoidCallback onTap, + required VoidCallback onLongPress, + }) { + final List avatarColors = [ + Colors.blueAccent, + Colors.teal, + Colors.deepPurple, + Colors.indigo, + Colors.orangeAccent, + Colors.pinkAccent, + Colors.cyan + ]; + final avatarBg = + isGroup ? Colors.orange : avatarColors[colorSeed % avatarColors.length]; + + // Slide and Fade animation for that premium staggered feel + return TweenAnimationBuilder( + duration: const Duration(milliseconds: 450), + tween: Tween(begin: 0.0, end: 1.0), + curve: Curves.easeOutQuart, + // Delay based on index for the staggered effect + builder: (context, value, child) { + return Opacity( + opacity: value, + child: Transform.translate( + offset: Offset(30 * (1 - value), 0), + child: child, + ), + ); + }, + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), + decoration: BoxDecoration( + color: AppTheme.darkCard, + borderRadius: BorderRadius.circular(18), + border: Border.all( + color: Colors.white.withValues(alpha: 0.05), width: 0.5), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.4), + spreadRadius: 1, + blurRadius: 12, + offset: const Offset(0, 6), + ), + ], + ), + child: Material( + color: Colors.transparent, + borderRadius: BorderRadius.circular(18), + child: InkWell( + borderRadius: BorderRadius.circular(18), + onTap: onTap, + onLongPress: onLongPress, + child: Padding( + padding: const EdgeInsets.all(14.0), + child: Row( + children: [ + Hero( + tag: 'avatar_${title}_${isGroup ? 'group' : 'ind'}', + child: Stack( + clipBehavior: Clip.none, + children: [ + Container( + width: 52, + height: 52, + decoration: BoxDecoration( + gradient: LinearGradient( + colors: [ + avatarBg, + avatarBg.withValues(alpha: 0.6), + ], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + shape: BoxShape.circle, + boxShadow: [ + BoxShadow( + color: avatarBg.withValues(alpha: 0.3), + blurRadius: 8, + spreadRadius: 1, + ), + ], + ), + child: Center( + child: isGroup + ? const Icon(Icons.groups, + color: Colors.white, size: 28) + : Text( + avatarText, + style: const TextStyle( + color: Colors.white, + fontSize: 18, + fontWeight: FontWeight.bold), + ), + ), + ), + if (unreadCount > 0) + Positioned( + top: -4, + left: -4, + child: Container( + constraints: const BoxConstraints( + minWidth: 22, + minHeight: 22, + ), + padding: + const EdgeInsets.symmetric(horizontal: 6), + decoration: BoxDecoration( + color: const Color(0xFFFF5A5F), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: AppTheme.darkCard, + width: 2, + ), + boxShadow: [ + BoxShadow( + color: const Color(0xFFFF5A5F) + .withValues(alpha: 0.35), + blurRadius: 10, + spreadRadius: 1, + ), + ], + ), + child: Center( + child: Text( + unreadCount > 99 + ? '99+' + : unreadCount.toString(), + style: const TextStyle( + color: Colors.white, + fontSize: 11, + fontWeight: FontWeight.w800, + ), + textAlign: TextAlign.center, + ), + ), + ), + ), + ], + ), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: TextStyle( + fontWeight: unreadCount > 0 + ? FontWeight.w900 + : FontWeight.bold, + fontSize: 17, + color: Colors.white, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + textDirection: TextDirection.ltr, + textAlign: TextAlign.right, + ), + const SizedBox(height: 4), + Row( + children: [ + if (isEncrypted) + Padding( + padding: const EdgeInsets.only(left: 4), + child: Icon(Icons.lock, + size: 14, color: primaryColor), + ), + Expanded( + child: Text( + subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: unreadCount > 0 + ? Colors.white.withValues(alpha: 0.9) + : Colors.white.withValues(alpha: 0.6), + fontSize: 13, + fontWeight: unreadCount > 0 + ? FontWeight.w600 + : FontWeight.w400, + ), + ), + ), + ], + ), + ], + ), + ), + if (showAddButton) + IconButton( + icon: + Icon(Icons.person_add_outlined, color: primaryColor), + onPressed: onAddContact, + tooltip: "افزودن به مخاطبین", + ), + Icon(Icons.chevron_right, color: Colors.grey[300]), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart new file mode 100644 index 0000000..79362f7 --- /dev/null +++ b/lib/screens/settings_screen.dart @@ -0,0 +1,803 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../main.dart'; + +import '../utils/app_lock_service.dart'; +import '../utils/contact_helper.dart'; +import '../utils/secure_messaging_service.dart'; +import '../utils/app_theme.dart'; +import 'splash_screen.dart'; + +enum _AppLockDialogMode { enable, change, disable } + +String? _validateAppLockPasscode(String value) { + final normalized = value.trim(); + if (normalized.isEmpty) { + return 'رمز را وارد کنید.'; + } + if (!RegExp(r'^\d{4,8}$').hasMatch(normalized)) { + return 'رمز باید ۴ تا ۸ رقم باشد.'; + } + return null; +} + +class SettingsScreen extends StatefulWidget { + const SettingsScreen({super.key}); + + @override + State createState() => _SettingsScreenState(); +} + +class _SettingsScreenState extends State { + bool _isResetting = false; + static const _platform = + MethodChannel('com.example.saba_secure_sms/sms_role'); + bool _isCurrentlyDefault = false; + bool _isAppLockEnabled = false; + bool _isAppLockLoading = true; + + @override + void initState() { + super.initState(); + _checkDefaultStatus(); + _loadAppLockStatus(); + } + + Future _checkDefaultStatus() async { + try { + final bool isDefault = await _platform.invokeMethod('isDefaultSmsApp'); + if (mounted) setState(() => _isCurrentlyDefault = isDefault); + } catch (_) {} + } + + Future _changeDefaultApp() async { + try { + if (_isCurrentlyDefault) { + // If already default, open settings to allow unsetting + await _platform.invokeMethod('openDefaultAppsSettings'); + } else { + // If not default, request it + await _platform.invokeMethod('requestDefaultSmsApp'); + } + // Re-check after returning + _checkDefaultStatus(); + } catch (_) {} + } + + Future _confirmReset() async { + final confirmed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + title: const Text('ریست کامل برنامه'), + content: const Text( + 'با این کار تمام کلیدها، گروه‌ها، پیام‌های ذخیره‌شده، کش بازگشایی و تنظیمات امنیتی حذف می‌شوند و برنامه مثل نصب تازه می‌شود. ادامه می‌دهید؟', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx, false), + child: const Text('لغو'), + ), + ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, + foregroundColor: Colors.white, + ), + onPressed: () => Navigator.pop(ctx, true), + child: const Text('ریست کامل'), + ), + ], + ), + ); + + if (confirmed != true || !mounted) return; + + setState(() => _isResetting = true); + await SecureMessagingService.instance.resetForFreshInstall(); + await AppLockService.instance.clear(); + ContactHelper.clearCache(); + if (!mounted) return; + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (_) => const SplashScreen()), + (route) => false, + ); + } + + Future _loadAppLockStatus() async { + await AppLockService.instance.init(); + if (!mounted) return; + setState(() { + _isAppLockEnabled = AppLockService.instance.isEnabled; + _isAppLockLoading = false; + }); + } + + Future _showEnableAppLockDialog() async { + final enabled = await showDialog( + context: context, + builder: (_) => const _AppLockDialog(mode: _AppLockDialogMode.enable), + ); + + if (enabled == true) { + await _loadAppLockStatus(); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('رمز برنامه با موفقیت فعال شد.'), + ), + ); + } + } + + Future _showChangeAppLockDialog() async { + final changed = await showDialog( + context: context, + builder: (_) => const _AppLockDialog(mode: _AppLockDialogMode.change), + ); + + if (changed == true && mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('رمز برنامه با موفقیت تغییر کرد.'), + ), + ); + } + } + + Future _showDisableAppLockDialog() async { + final disabled = await showDialog( + context: context, + builder: (_) => const _AppLockDialog(mode: _AppLockDialogMode.disable), + ); + + if (disabled == true) { + await _loadAppLockStatus(); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('رمز برنامه غیرفعال شد.'), + ), + ); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppTheme.darkBg, + appBar: AppBar( + title: const Text('تنظیمات'), + backgroundColor: Colors.transparent, + elevation: 0, + ), + body: Stack( + children: [ + Positioned.fill(child: CustomPaint(painter: MeshBackgroundPainter())), + SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + _buildSettingSection( + icon: Icons.sms_rounded, + iconColor: Colors.blueAccent, + title: 'برنامه پیش‌فرض پیامک', + content: _isCurrentlyDefault + ? 'صبا در حال حاضر برنامه پیش‌فرض پیامک گوشی شماست.' + : 'صبا برنامه پیش‌فرض نیست. برای استفاده از تمام امکانات امنیتی، صبا را به عنوان گزینه پیش‌فرض انتخاب کنید.', + action: SizedBox( + width: double.infinity, + child: OutlinedButton.icon( + onPressed: _changeDefaultApp, + style: OutlinedButton.styleFrom( + foregroundColor: _isCurrentlyDefault + ? Colors.white70 + : Colors.blueAccent, + side: BorderSide( + color: _isCurrentlyDefault + ? Colors.white24 + : Colors.blueAccent), + padding: const EdgeInsets.symmetric(vertical: 14), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14)), + ), + icon: Icon(_isCurrentlyDefault + ? Icons.settings_applications + : Icons.check_circle_outline), + label: Text(_isCurrentlyDefault + ? 'تغییر در تنظیمات سیستمی' + : 'انتخاب به عنوان پیش‌فرض'), + ), + ), + ), + const SizedBox(height: 16), + _buildSettingSection( + icon: Icons.palette_rounded, + iconColor: Colors.purpleAccent, + title: 'رنگ‌بندی برنامه', + content: + 'رنگ مورد علاقه‌ی خود را برای محیط برنامه انتخاب کنید:', + action: SizedBox( + height: 55, + child: ListView( + scrollDirection: Axis.horizontal, + children: [ + _buildColorItem(const Color(0xFF7000FF), 'بنفش'), + _buildColorItem(const Color(0xFF00D2FF), 'آبی'), + _buildColorItem(const Color(0xFF00FFD1), 'فیروزه‌ای'), + _buildColorItem(const Color(0xFF4CAF50), 'سبز'), + _buildColorItem(const Color(0xFFFF9800), 'نارنجی'), + _buildColorItem(const Color(0xFFE91E63), 'صورتی'), + _buildColorItem(const Color(0xFFF44336), 'قرمز'), + ], + ), + ), + ), + const SizedBox(height: 16), + _buildSettingSection( + icon: Icons.lock_outline_rounded, + iconColor: Colors.amberAccent, + title: 'قفل برنامه', + content: _isAppLockEnabled + ? 'رمز برنامه فعال است. از این به بعد، هر بار ورود یا بازگشت به اپ نیاز به وارد کردن رمز خواهد داشت.' + : 'اگر این گزینه را فعال کنید، بدون وارد کردن رمز هیچ‌کس نمی‌تواند وارد برنامه شود.', + action: _isAppLockLoading + ? const Center(child: CircularProgressIndicator()) + : Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.05), + borderRadius: BorderRadius.circular(14), + border: Border.all( + color: _isAppLockEnabled + ? Colors.greenAccent + .withValues(alpha: 0.25) + : Colors.white12, + ), + ), + child: Row( + children: [ + Icon( + _isAppLockEnabled + ? Icons.verified_user_rounded + : Icons.lock_open_rounded, + color: _isAppLockEnabled + ? Colors.greenAccent + : Colors.white60, + ), + const SizedBox(width: 12), + Expanded( + child: Text( + _isAppLockEnabled + ? 'رمز برنامه فعال است' + : 'رمز برنامه غیرفعال است', + style: const TextStyle( + color: Colors.white, + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + ), + const SizedBox(height: 14), + SizedBox( + width: double.infinity, + child: ElevatedButton.icon( + onPressed: _isAppLockEnabled + ? _showChangeAppLockDialog + : _showEnableAppLockDialog, + style: ElevatedButton.styleFrom( + padding: const EdgeInsets.symmetric( + vertical: 14, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + ), + ), + icon: Icon( + _isAppLockEnabled + ? Icons.password_rounded + : Icons.lock_rounded, + ), + label: Text( + _isAppLockEnabled + ? 'تغییر رمز برنامه' + : 'فعال‌سازی رمز برنامه', + ), + ), + ), + if (_isAppLockEnabled) ...[ + const SizedBox(height: 10), + SizedBox( + width: double.infinity, + child: OutlinedButton.icon( + onPressed: _showDisableAppLockDialog, + style: OutlinedButton.styleFrom( + foregroundColor: Colors.redAccent, + side: const BorderSide( + color: Colors.redAccent, + ), + padding: const EdgeInsets.symmetric( + vertical: 14, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + ), + ), + icon: const Icon(Icons.lock_reset_rounded), + label: + const Text('غیرفعال‌سازی رمز برنامه'), + ), + ), + ], + ], + ), + ), + const SizedBox(height: 16), + _buildSettingSection( + icon: Icons.security_rounded, + iconColor: Colors.cyanAccent, + title: 'حریم خصوصی و استتار', + content: + 'با فعال‌سازی این گزینه، آیکون و نام برنامه در لیست برنامه‌های گوشی به "ماشین حساب" تغییر می‌کند تا امنیت شما حفظ شود.', + action: FutureBuilder( + future: _platform + .invokeMethod('getStealthMode') + .then((v) => v ?? false), + builder: (context, snapshot) { + final isStealth = snapshot.data ?? false; + return Container( + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.05), + borderRadius: BorderRadius.circular(12), + ), + child: SwitchListTile( + title: const Text('حالت استتار (ماشین حساب)', + style: TextStyle( + fontSize: 14, color: Colors.white)), + subtitle: Text( + isStealth + ? 'فعال (برنامه مخفی است)' + : 'غیرفعال', + style: const TextStyle( + fontSize: 12, color: Colors.white60)), + value: isStealth, + contentPadding: + const EdgeInsets.symmetric(horizontal: 12), + secondary: const Icon(Icons.calculate_outlined, + color: Colors.white70), + activeThumbColor: Colors.cyanAccent, + onChanged: (bool value) async { + final confirmed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + backgroundColor: AppTheme.darkCard, + title: Text( + value + ? 'فعال‌سازی حالت مخفی' + : 'خروج از حالت مخفی', + style: + const TextStyle(color: Colors.white)), + content: Text( + value + ? 'با تایید این گزینه، برنامه بسته شده و آیکون آن به ماشین حساب تغییر می‌کند.' + : 'با تایید این گزینه، آیکون اصلی صبا باز می‌گردد.', + style: const TextStyle( + color: Colors.white70)), + actions: [ + TextButton( + onPressed: () => + Navigator.pop(ctx, false), + child: const Text('لغو')), + ElevatedButton( + onPressed: () => + Navigator.pop(ctx, true), + child: const Text('تایید')), + ], + ), + ); + if (confirmed == true) { + await _platform.invokeMethod( + 'setStealthMode', {'enabled': value}); + } + }, + ), + ); + }, + ), + ), + const SizedBox(height: 32), + Center( + child: TextButton.icon( + onPressed: _isResetting ? null : _confirmReset, + style: TextButton.styleFrom( + foregroundColor: + Colors.redAccent.withValues(alpha: 0.8)), + icon: const Icon(Icons.dangerous_outlined), + label: const Text('ریست کامل و حذف تمام داده‌ها', + style: TextStyle(fontWeight: FontWeight.bold)), + ), + ), + const SizedBox(height: 40), + ], + ), + ), + ), + ], + ), + ); + } + + Widget _buildSettingSection({ + required IconData icon, + required Color iconColor, + required String title, + required String content, + required Widget action, + }) { + return AppTheme.glassWrapper( + child: Padding( + padding: const EdgeInsets.all(20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(icon, color: iconColor), + const SizedBox(width: 12), + Text( + title, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.white), + ), + ], + ), + const SizedBox(height: 12), + Text( + content, + style: const TextStyle( + height: 1.5, color: Colors.white70, fontSize: 13), + ), + const SizedBox(height: 20), + action, + ], + ), + ), + ); + } + + Widget _buildColorItem(Color color, String label) { + final bool isSelected = themeNotifier.value.toARGB32() == color.toARGB32(); + return GestureDetector( + onTap: () async { + themeNotifier.value = color; + final prefs = await SharedPreferences.getInstance(); + await prefs.setInt('primary_color_value', color.toARGB32()); + setState(() {}); // Refresh local UI for selection check + }, + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 8), + padding: const EdgeInsets.all(3), + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all( + color: isSelected ? color : Colors.transparent, + width: 2, + ), + ), + child: Container( + width: 38, + height: 38, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + boxShadow: [ + BoxShadow( + color: color.withValues(alpha: 0.4), + blurRadius: 4, + offset: const Offset(0, 2), + ), + ], + ), + child: isSelected + ? const Icon(Icons.check, color: Colors.white, size: 20) + : null, + ), + ), + ); + } +} + +class _AppLockDialog extends StatefulWidget { + const _AppLockDialog({required this.mode}); + + final _AppLockDialogMode mode; + + @override + State<_AppLockDialog> createState() => _AppLockDialogState(); +} + +class _AppLockDialogState extends State<_AppLockDialog> { + final TextEditingController _currentController = TextEditingController(); + final TextEditingController _nextController = TextEditingController(); + final TextEditingController _confirmController = TextEditingController(); + + bool _isSubmitting = false; + String? _errorText; + + bool get _isEnableMode => widget.mode == _AppLockDialogMode.enable; + bool get _isChangeMode => widget.mode == _AppLockDialogMode.change; + bool get _isDisableMode => widget.mode == _AppLockDialogMode.disable; + + @override + void dispose() { + _currentController.dispose(); + _nextController.dispose(); + _confirmController.dispose(); + super.dispose(); + } + + Future _close([bool result = false]) async { + FocusManager.instance.primaryFocus?.unfocus(); + await Future.delayed(const Duration(milliseconds: 40)); + if (!mounted) return; + Navigator.of(context).pop(result); + } + + Future _submit() async { + if (_isSubmitting) return; + + if (_isEnableMode) { + final nextError = _validateAppLockPasscode(_nextController.text); + if (nextError != null) { + setState(() => _errorText = nextError); + return; + } + if (_nextController.text.trim() != _confirmController.text.trim()) { + setState(() => _errorText = 'تکرار رمز با رمز اصلی یکسان نیست.'); + return; + } + } + + if (_isChangeMode) { + final currentError = _validateAppLockPasscode(_currentController.text); + final nextError = _validateAppLockPasscode(_nextController.text); + if (currentError != null) { + setState(() => _errorText = 'رمز فعلی معتبر نیست.'); + return; + } + if (nextError != null) { + setState(() => _errorText = nextError); + return; + } + if (_nextController.text.trim() != _confirmController.text.trim()) { + setState(() => _errorText = 'تکرار رمز جدید با رمز جدید یکسان نیست.'); + return; + } + } + + if (_isDisableMode) { + final currentError = _validateAppLockPasscode(_currentController.text); + if (currentError != null) { + setState(() => _errorText = 'رمز فعلی را درست وارد کنید.'); + return; + } + } + + setState(() { + _isSubmitting = true; + _errorText = null; + }); + + if (_isEnableMode) { + await AppLockService.instance.setPasscode(_nextController.text.trim()); + await _close(true); + return; + } + + if (_isChangeMode) { + final updated = await AppLockService.instance.changePasscode( + currentPasscode: _currentController.text.trim(), + newPasscode: _nextController.text.trim(), + ); + if (!mounted) return; + if (!updated) { + setState(() { + _isSubmitting = false; + _errorText = 'رمز فعلی درست نیست.'; + }); + return; + } + await _close(true); + return; + } + + final removed = await AppLockService.instance + .disablePasscode(_currentController.text.trim()); + if (!mounted) return; + if (!removed) { + setState(() { + _isSubmitting = false; + _errorText = 'رمز فعلی درست نیست.'; + }); + return; + } + await _close(true); + } + + String get _title { + switch (widget.mode) { + case _AppLockDialogMode.enable: + return 'فعال‌سازی رمز برنامه'; + case _AppLockDialogMode.change: + return 'تغییر رمز برنامه'; + case _AppLockDialogMode.disable: + return 'غیرفعال‌سازی رمز برنامه'; + } + } + + String get _primaryActionLabel { + switch (widget.mode) { + case _AppLockDialogMode.enable: + return _isSubmitting ? 'در حال ذخیره...' : 'فعال‌سازی'; + case _AppLockDialogMode.change: + return _isSubmitting ? 'در حال ذخیره...' : 'ذخیره تغییرات'; + case _AppLockDialogMode.disable: + return _isSubmitting ? 'در حال بررسی...' : 'حذف رمز'; + } + } + + Widget _buildPasscodeField({ + required TextEditingController controller, + required String label, + ValueChanged? onSubmitted, + }) { + return TextField( + controller: controller, + keyboardType: TextInputType.number, + obscureText: true, + obscuringCharacter: '•', + textInputAction: TextInputAction.done, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, + LengthLimitingTextInputFormatter(8), + ], + onSubmitted: onSubmitted, + decoration: InputDecoration( + labelText: label, + hintText: '۴ تا ۸ رقم', + filled: true, + fillColor: Colors.white.withValues(alpha: 0.06), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(14), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + backgroundColor: AppTheme.darkCard, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20), + ), + title: Text( + _title, + style: const TextStyle(color: Colors.white), + ), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (_isEnableMode) + const Text( + 'یک رمز ۴ تا ۸ رقمی انتخاب کنید. از این به بعد، برای ورود یا بازگشت به برنامه باید همین رمز وارد شود.', + style: TextStyle(color: Colors.white70, height: 1.6), + ), + if (_isDisableMode) + const Text( + 'برای حذف قفل برنامه، رمز فعلی را وارد کنید.', + style: TextStyle(color: Colors.white70, height: 1.6), + ), + if (_isEnableMode || _isDisableMode) const SizedBox(height: 16), + if (_isChangeMode) ...[ + _buildPasscodeField( + controller: _currentController, + label: 'رمز فعلی', + ), + const SizedBox(height: 12), + _buildPasscodeField( + controller: _nextController, + label: 'رمز جدید', + ), + const SizedBox(height: 12), + _buildPasscodeField( + controller: _confirmController, + label: 'تکرار رمز جدید', + onSubmitted: (_) => _submit(), + ), + ], + if (_isEnableMode) ...[ + _buildPasscodeField( + controller: _nextController, + label: 'رمز جدید', + ), + const SizedBox(height: 12), + _buildPasscodeField( + controller: _confirmController, + label: 'تکرار رمز', + onSubmitted: (_) => _submit(), + ), + ], + if (_isDisableMode) + _buildPasscodeField( + controller: _currentController, + label: 'رمز فعلی', + onSubmitted: (_) => _submit(), + ), + if (_errorText != null) ...[ + const SizedBox(height: 12), + Text( + _errorText!, + style: const TextStyle(color: Colors.redAccent), + ), + ], + ], + ), + actions: [ + TextButton( + onPressed: _isSubmitting ? null : _close, + child: const Text('لغو'), + ), + ElevatedButton( + style: _isDisableMode + ? ElevatedButton.styleFrom( + backgroundColor: Colors.redAccent, + foregroundColor: Colors.white, + ) + : null, + onPressed: _isSubmitting ? null : _submit, + child: Text(_primaryActionLabel), + ), + ], + ); + } +} + +class MeshBackgroundPainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + final Paint paint1 = Paint() + ..shader = RadialGradient( + colors: [ + const Color(0xFF7000FF).withValues(alpha: 0.12), + const Color(0xFF7000FF).withValues(alpha: 0.0), + ], + ).createShader(Rect.fromCircle( + center: Offset(size.width * 0.2, size.height * 0.15), radius: 300)); + + canvas.drawCircle( + Offset(size.width * 0.2, size.height * 0.15), 300, paint1); + + final Paint paint2 = Paint() + ..shader = RadialGradient( + colors: [ + const Color(0xFF00D2FF).withValues(alpha: 0.1), + const Color(0xFF00D2FF).withValues(alpha: 0.0), + ], + ).createShader(Rect.fromCircle( + center: Offset(size.width * 0.8, size.height * 0.8), radius: 400)); + + canvas.drawCircle(Offset(size.width * 0.8, size.height * 0.8), 400, paint2); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} diff --git a/lib/screens/splash_screen.dart b/lib/screens/splash_screen.dart new file mode 100644 index 0000000..cd71544 --- /dev/null +++ b/lib/screens/splash_screen.dart @@ -0,0 +1,438 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:permission_handler/permission_handler.dart'; + +import 'home_screen.dart'; +import '../utils/secure_messaging_service.dart'; + +class SplashScreen extends StatefulWidget { + const SplashScreen({super.key}); + + @override + State createState() => _SplashScreenState(); +} + +class _SplashScreenState extends State + with TickerProviderStateMixin { + static const _platform = + MethodChannel('com.example.saba_secure_sms/sms_role'); + String _statusText = "در حال بررسی مجوزها..."; + String? _startupError; + + late AnimationController _animationController; + late AnimationController _loaderController; + late Animation _scaleAnimation; + late Animation _fadeAnimation; + + @override + void initState() { + super.initState(); + _animationController = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 1500), + ); + + _scaleAnimation = Tween(begin: 0.6, end: 1.0).animate( + CurvedAnimation(parent: _animationController, curve: Curves.elasticOut), + ); + + _fadeAnimation = Tween(begin: 0.0, end: 1.0).animate( + CurvedAnimation( + parent: _animationController, + curve: const Interval(0.0, 0.5, curve: Curves.easeIn)), + ); + + _loaderController = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 1800), + )..repeat(); + + _animationController.forward(); + _checkPermissions(); + } + + @override + void dispose() { + _animationController.dispose(); + _loaderController.dispose(); + super.dispose(); + } + + Future _checkPermissions() async { + // کمی تاخیر برای اینکه انیمیشن دیده شود + await Future.delayed(const Duration(seconds: 2)); + + // ... rest of permission logic remains the same ... + Map statuses = await [ + Permission.sms, + Permission.phone, + Permission.contacts, + Permission.notification, + ].request(); + + if (statuses[Permission.sms]!.isGranted && + statuses[Permission.phone]!.isGranted && + statuses[Permission.contacts]!.isGranted) { + await _checkAndRequestDefaultSms(); + + if (mounted) { + setState(() { + _statusText = "آماده‌سازی امن صبا..."; + _startupError = null; + }); + } + await _initializeSecureLayer(); + } else { + if (mounted) { + showDialog( + context: context, + barrierDismissible: false, + builder: (context) => AlertDialog( + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + title: const Text("مجوزهای مورد نیاز"), + content: const Text( + "صبا برای پیام‌رسانی امن به دسترسی پیامک و مخاطبین نیاز دارد."), + actions: [ + TextButton( + onPressed: () => openAppSettings(), + child: const Text("تنظیمات"), + ), + TextButton( + onPressed: () { + Navigator.pop(context); + _checkPermissions(); + }, + child: const Text("تلاش مجدد"), + ), + ], + ), + ); + } + } + } + + Future _initializeSecureLayer() async { + try { + await SecureMessagingService.instance.init(); + // تاخیر کوتاه برای نمایش حالت 'آماده' + await Future.delayed(const Duration(milliseconds: 800)); + _goToHome(); + } catch (e) { + if (!mounted) return; + setState(() { + _startupError = e.toString(); + _statusText = "خطا در راه‌اندازی لایه امنیتی"; + }); + } + } + + Future _checkAndRequestDefaultSms() async { + try { + final bool isDefault = await _platform.invokeMethod('isDefaultSmsApp'); + if (!isDefault) { + await _platform.invokeMethod('requestDefaultSmsApp'); + await Future.delayed(const Duration(seconds: 1)); + } + } catch (_) {} + } + + void _goToHome() { + if (mounted) { + Navigator.pushReplacement( + context, + PageRouteBuilder( + transitionDuration: const Duration(milliseconds: 800), + pageBuilder: (context, animation, secondaryAnimation) => + const HomeScreen(), + transitionsBuilder: (context, animation, secondaryAnimation, child) { + return FadeTransition(opacity: animation, child: child); + }, + ), + ); + } + } + + Widget _buildSecurityLoader() { + return AnimatedBuilder( + animation: _loaderController, + builder: (context, child) { + final t = _loaderController.value; + final scanProgress = Curves.easeInOut.transform(t); + final pulses = [ + (t + 0.08) % 1.0, + (t + 0.58) % 1.0, + ]; + + return SizedBox( + width: 180, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + width: 120, + height: 120, + child: Stack( + alignment: Alignment.center, + children: [ + for (final pulse in pulses) + Transform.scale( + scale: 0.78 + (pulse * 0.72), + child: Opacity( + opacity: (1 - pulse) * 0.22, + child: Container( + width: 88, + height: 88, + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all( + color: Colors.white, + width: 1.2, + ), + ), + ), + ), + ), + Container( + width: 92, + height: 92, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(28), + gradient: LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Colors.white.withValues(alpha: 0.18), + Colors.white.withValues(alpha: 0.06), + ], + ), + border: Border.all( + color: Colors.white.withValues(alpha: 0.22), + width: 1, + ), + boxShadow: [ + BoxShadow( + color: + const Color(0xFF8EC5FF).withValues(alpha: 0.18), + blurRadius: 20, + spreadRadius: 1, + ), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(28), + child: Stack( + alignment: Alignment.center, + children: [ + Positioned( + top: 10 + (scanProgress * 50), + child: Container( + width: 78, + height: 18, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(18), + gradient: LinearGradient( + colors: [ + Colors.transparent, + Colors.white.withValues(alpha: 0.0), + const Color(0xFF7FD8FF) + .withValues(alpha: 0.34), + Colors.white.withValues(alpha: 0.0), + Colors.transparent, + ], + ), + ), + ), + ), + Container( + width: 60, + height: 60, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.white.withValues(alpha: 0.1), + ), + ), + const Icon( + Icons.verified_user_rounded, + color: Colors.white, + size: 34, + ), + ], + ), + ), + ), + Positioned( + bottom: 2, + child: Row( + children: List.generate(4, (index) { + final wave = 0.5 + + 0.5 * + math.sin( + ((t + (index * 0.16)) * 2 * math.pi), + ); + final height = 10 + (wave * 18); + return Container( + width: 9, + height: height, + margin: const EdgeInsets.symmetric(horizontal: 3), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(10), + gradient: const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + Colors.white, + Color(0xFF7FD8FF), + ], + ), + ), + ); + }), + ), + ), + ], + ), + ), + const SizedBox(height: 16), + Container( + width: 150, + height: 8, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(99), + color: Colors.white.withValues(alpha: 0.12), + ), + child: Stack( + children: [ + AnimatedAlign( + duration: const Duration(milliseconds: 120), + alignment: Alignment(-1 + (scanProgress * 2), 0), + child: Container( + width: 52, + height: 8, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(99), + gradient: const LinearGradient( + colors: [ + Color(0xFF7FD8FF), + Color(0xFFFFFFFF), + ], + ), + ), + ), + ), + ], + ), + ), + ], + ), + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Container( + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Theme.of(context).primaryColor, const Color(0xFF1A237E)], + ), + ), + child: Stack( + children: [ + // Background subtle patterns could go here + Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + AnimatedBuilder( + animation: _animationController, + builder: (context, child) { + return Opacity( + opacity: _fadeAnimation.value, + child: Transform.scale( + scale: _scaleAnimation.value, + child: Hero( + tag: 'app_logo', + child: SizedBox( + width: 200, + height: 200, + child: Image.asset('صبا بالا.png'), + ), + ), + ), + ); + }, + ), + const SizedBox(height: 40), + const Text( + "صبا", + style: TextStyle( + fontSize: 32, + fontWeight: FontWeight.bold, + color: Colors.white, + letterSpacing: 1.2, + ), + ), + const Text( + "پیام‌رسان امن و پیشرفته", + style: TextStyle( + fontSize: 16, + color: Colors.white70, + fontWeight: FontWeight.w300, + ), + ), + const SizedBox(height: 60), + if (_startupError == null) _buildSecurityLoader(), + if (_startupError != null) + ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.white, + foregroundColor: Colors.blue.shade900, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(15)), + ), + onPressed: () { + setState(() { + _startupError = null; + _statusText = "در حال اتصال..."; + }); + _checkPermissions(); + }, + child: const Text("تلاش مجدد"), + ), + const SizedBox(height: 20), + Text( + _statusText, + style: const TextStyle(color: Colors.white60, fontSize: 13), + ), + ], + ), + ), + const Positioned( + bottom: 40, + left: 0, + right: 0, + child: Center( + child: Text( + "SABA SECURE MESSENGER", + style: TextStyle( + color: Colors.white24, + fontSize: 12, + letterSpacing: 2, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/utils/app_lock_service.dart b/lib/utils/app_lock_service.dart new file mode 100644 index 0000000..fc55e75 --- /dev/null +++ b/lib/utils/app_lock_service.dart @@ -0,0 +1,158 @@ +import 'dart:convert'; +import 'dart:math'; + +import 'package:cryptography/cryptography.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; + +class AppLockService extends ChangeNotifier { + AppLockService._(); + + static final AppLockService instance = AppLockService._(); + + static const _enabledKey = 'app_lock_enabled_v1'; + static const _saltKey = 'app_lock_salt_v1'; + static const _hashKey = 'app_lock_hash_v1'; + static const _pbkdf2Iterations = 120000; + + final FlutterSecureStorage _storage = const FlutterSecureStorage(); + final Pbkdf2 _kdf = Pbkdf2( + macAlgorithm: Hmac.sha256(), + iterations: _pbkdf2Iterations, + bits: 256, + ); + + bool _initialized = false; + bool _enabled = false; + bool _locked = false; + + bool get initialized => _initialized; + bool get isEnabled => _enabled; + bool get isLocked => _enabled && _locked; + + Future init() async { + if (_initialized) return; + await _reloadFromStorage(lockIfEnabled: true); + } + + Future refresh() async { + await _reloadFromStorage(lockIfEnabled: false); + } + + Future setPasscode(String passcode) async { + final normalized = _normalizePasscode(passcode); + final salt = _generateSalt(); + final hash = await _derivePasscodeHash(normalized, salt); + + await _storage.write(key: _saltKey, value: salt); + await _storage.write(key: _hashKey, value: hash); + await _storage.write(key: _enabledKey, value: '1'); + + _enabled = true; + _locked = false; + _initialized = true; + notifyListeners(); + } + + Future verifyPasscode(String passcode) async { + final isValid = await _matchesStoredPasscode(passcode); + if (!isValid) return false; + + _enabled = true; + _locked = false; + _initialized = true; + notifyListeners(); + return true; + } + + Future changePasscode({ + required String currentPasscode, + required String newPasscode, + }) async { + final isCurrentValid = await _matchesStoredPasscode(currentPasscode); + if (!isCurrentValid) return false; + + await setPasscode(newPasscode); + return true; + } + + Future disablePasscode(String currentPasscode) async { + final isCurrentValid = await _matchesStoredPasscode(currentPasscode); + if (!isCurrentValid) return false; + + await clear(); + return true; + } + + Future clear() async { + await _storage.delete(key: _enabledKey); + await _storage.delete(key: _saltKey); + await _storage.delete(key: _hashKey); + + _enabled = false; + _locked = false; + _initialized = true; + notifyListeners(); + } + + void lock() { + if (!_enabled || _locked) return; + _locked = true; + notifyListeners(); + } + + Future _reloadFromStorage({required bool lockIfEnabled}) async { + try { + final enabledValue = await _storage.read(key: _enabledKey); + _enabled = enabledValue == '1'; + _locked = _enabled && lockIfEnabled ? true : (_enabled && _locked); + } catch (e) { + debugPrint('[APP_LOCK] Failed to load state: $e'); + _enabled = false; + _locked = false; + } + + if (!_enabled) { + _locked = false; + } + + _initialized = true; + notifyListeners(); + } + + Future _matchesStoredPasscode(String passcode) async { + try { + final normalized = _normalizePasscode(passcode); + final salt = await _storage.read(key: _saltKey); + final storedHash = await _storage.read(key: _hashKey); + final enabledValue = await _storage.read(key: _enabledKey); + + if (enabledValue != '1' || salt == null || storedHash == null) { + return false; + } + + final computedHash = await _derivePasscodeHash(normalized, salt); + return computedHash == storedHash; + } catch (e) { + debugPrint('[APP_LOCK] Failed to verify passcode: $e'); + return false; + } + } + + Future _derivePasscodeHash(String passcode, String salt) async { + final secretKey = await _kdf.deriveKey( + secretKey: SecretKey(utf8.encode(passcode)), + nonce: utf8.encode(salt), + ); + final bytes = await secretKey.extractBytes(); + return base64UrlEncode(bytes); + } + + String _generateSalt() { + final random = Random.secure(); + final bytes = List.generate(16, (_) => random.nextInt(256)); + return base64UrlEncode(bytes); + } + + String _normalizePasscode(String input) => input.trim(); +} diff --git a/lib/utils/app_theme.dart b/lib/utils/app_theme.dart new file mode 100644 index 0000000..c0ef9d4 --- /dev/null +++ b/lib/utils/app_theme.dart @@ -0,0 +1,91 @@ +import 'dart:ui'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; + +class AppTheme { + // --- Neo-Dark Color Palette --- + static const Color darkBg = Color(0xFF050505); + static const Color darkCard = Color(0xFF121212); + static const Color accentPurple = Color(0xFF7000FF); + static const Color accentBlue = Color(0xFF00D2FF); + static const Color accentCyan = Color(0xFF00FFD1); + + static const Color secureGradientStart = Color(0xFF6A11CB); + static const Color secureGradientEnd = Color(0xFF2575FC); + + static const Color glassWhite = Color(0x1AFFFFFF); + static const Color glassBorder = Color(0x33FFFFFF); + + // --- Glassmorphism Styles --- + static BoxDecoration glassDecoration({double radius = 16}) { + return BoxDecoration( + color: glassWhite, + borderRadius: BorderRadius.circular(radius), + border: Border.all(color: glassBorder, width: 0.5), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.2), + blurRadius: 10, + spreadRadius: -2, + ), + ], + ); + } + + static Widget glassWrapper({ + required Widget child, + double radius = 16, + double sigma = 10, + }) { + return ClipRRect( + borderRadius: BorderRadius.circular(radius), + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: sigma, sigmaY: sigma), + child: Container( + decoration: glassDecoration(radius: radius), + child: child, + ), + ), + ); + } + + // --- Theme Data --- + static ThemeData neoDarkTheme(Color seedColor) { + return ThemeData( + useMaterial3: true, + brightness: Brightness.dark, + scaffoldBackgroundColor: darkBg, + primaryColor: seedColor, + colorScheme: ColorScheme.fromSeed( + seedColor: seedColor, + brightness: Brightness.dark, + surface: darkCard, + onSurface: Colors.white, + ), + textTheme: GoogleFonts.interTextTheme(ThemeData.dark().textTheme).copyWith( + displayLarge: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + color: Colors.white, + ), + titleMedium: GoogleFonts.inter( + fontWeight: FontWeight.w600, + color: Colors.white70, + ), + ), + appBarTheme: const AppBarTheme( + backgroundColor: Colors.transparent, + elevation: 0, + centerTitle: true, + titleTextStyle: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), + ), + cardTheme: CardThemeData( + color: darkCard, + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + side: const BorderSide(color: glassBorder, width: 0.5), + ), + ), + ); + } +} diff --git a/lib/utils/contact_helper.dart b/lib/utils/contact_helper.dart new file mode 100644 index 0000000..67b3dcd --- /dev/null +++ b/lib/utils/contact_helper.dart @@ -0,0 +1,88 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_contacts/flutter_contacts.dart'; +import 'database_helper.dart'; +import 'phone_helper.dart'; + +class ContactHelper { + static final Map _memoryCache = {}; + + static void clearCache() { + _memoryCache.clear(); + } + + // بارگذاری نام‌ها از دیتابیس برای نمایش در لیست چت‌ها (Home Screen) + static Future loadFromLocalCache() async { + try { + final cachedData = await DatabaseHelper.instance.getCachedContacts(); + if (cachedData.isNotEmpty) { + _memoryCache.addAll(cachedData); + } + } catch (e) { + debugPrint("Cache load error: $e"); + } + } + + // --- متد ۱: دریافت لیست سبک (فقط نام و ID) - بسیار سریع --- + // این متد برای لیست جستجو استفاده می‌شود + static Future> getContactsLight() async { + if (!await FlutterContacts.requestPermission(readonly: true)) return []; + + // withProperties: false یعنی فقط ID و Name را بده (بدون عکس، بدون شماره) + // این کار حجم انتقال داده را تا ۹۰٪ کاهش می‌دهد و "Slow Binder" را رفع می‌کند + return await FlutterContacts.getContacts( + withProperties: false, withPhoto: false, sorted: true); + } + + // --- متد ۲: دریافت اطلاعات کامل یک نفر (وقتی رویش کلیک شد) --- + static Future getFullContact(String contactId) async { + return await FlutterContacts.getContact(contactId); + } + + // --- متد ۳: همگام‌سازی پس‌زمینه (برای دیتابیس) --- + // این متد سنگین است و باید فقط برای مپ کردن نام‌ها در دیتابیس استفاده شود + static Future syncWithDevice() async { + if (!await FlutterContacts.requestPermission(readonly: true)) return false; + + try { + // دریافت مخاطبین با شماره (سنگین) + List contacts = await FlutterContacts.getContacts( + withProperties: true, + withPhoto: false, + ); + + Map newMap = {}; + + for (var contact in contacts) { + if (contact.phones.isNotEmpty) { + for (var phone in contact.phones) { + String cleanPhone = normalizePhone(phone.number); + if (cleanPhone.isNotEmpty) { + newMap[cleanPhone] = contact.displayName; + } + } + } + } + + _memoryCache.addAll(newMap); + await DatabaseHelper.instance.cacheContacts(newMap); + return true; + } catch (e) { + return false; + } + } + + static String getName(String phone) { + String cleanPhone = normalizePhone(phone); + return _memoryCache[cleanPhone] ?? phone; + } + + static String normalizePhone(String phone) { + return PhoneHelper.normalizePhone(phone); + } + + static bool isRawNumber(String input) { + if (input.isEmpty) return false; + // اگر فقط شامل اعداد، علامت مثبت یا خط فاصله باشد، احتمالا شماره خام است + return RegExp(r'^[0-9+\-\s]+$').hasMatch(input); + } +} diff --git a/lib/utils/crypto_helper.dart b/lib/utils/crypto_helper.dart new file mode 100644 index 0000000..0861f7f --- /dev/null +++ b/lib/utils/crypto_helper.dart @@ -0,0 +1,60 @@ +import 'package:encrypt/encrypt.dart' as enc; +import 'package:crypto/crypto.dart'; +import 'dart:convert'; +import 'dart:typed_data'; + +class CryptoHelper { + // این پیشوند باعث می‌شود بفهمیم پیام رمزدار است + static const String prefix = "ENC:"; + + // تبدیل رمز ساده کاربر (مثلا 1234) به کلید امن ۳۲ بایتی + static enc.Key _generateKey(String password) { + var bytes = utf8.encode(password); + var digest = sha256.convert(bytes); + return enc.Key(Uint8List.fromList(digest.bytes)); + } + + // متد رمزنگاری + static String encrypt(String plainText, String password) { + try { + final key = _generateKey(password); + final iv = enc.IV.fromLength(16); // تولید IV تصادفی + final encrypter = enc.Encrypter(enc.AES(key)); + + final encrypted = encrypter.encrypt(plainText, iv: iv); + + // فرمت خروجی: ENC:IV_BASE64:MESSAGE_BASE64 + return "$prefix${iv.base64}:${encrypted.base64}"; + } catch (e) { + print("Error creating encryption: $e"); + return plainText; + } + } + + // متد رمزگشایی + static String decrypt(String encryptedText, String password) { + // اگر پیام پیشوند ما را نداشت، یعنی پیام معمولی است + if (!encryptedText.startsWith(prefix)) return encryptedText; + + try { + // جدا کردن بخش‌ها (حذف ENC و جدا کردن IV از متن) + final parts = encryptedText.substring(4).split(':'); + if (parts.length != 2) return "فرمت پیام نامعتبر است"; + + final iv = enc.IV.fromBase64(parts[0]); + final cipherText = parts[1]; + + final key = _generateKey(password); + final encrypter = enc.Encrypter(enc.AES(key)); + + return encrypter.decrypt64(cipherText, iv: iv); + } catch (e) { + return "⛔ رمز اشتباه است یا پیام مخدوش شده."; + } + } + + // متد کمکی برای تشخیص اینکه آیا پیام رمزدار است یا نه + static bool isEncrypted(String text) { + return text.startsWith(prefix); + } +} \ No newline at end of file diff --git a/lib/utils/database_helper.dart b/lib/utils/database_helper.dart new file mode 100644 index 0000000..6001f78 --- /dev/null +++ b/lib/utils/database_helper.dart @@ -0,0 +1,1124 @@ +import 'dart:io'; + +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:path/path.dart'; +import 'package:sqflite_sqlcipher/sqflite.dart'; + +import 'phone_helper.dart'; +import 'protocol_helper.dart'; + +class DatabaseHelper { + static final DatabaseHelper instance = DatabaseHelper._init(); + static Database? _database; + static const String _primaryDbName = 'app_v7.db'; + static const String _alternateDbName = 'app_v8.db'; + + DatabaseHelper._init(); + + final _secureStorage = const FlutterSecureStorage(); + String? _dbPassword; + + Future get database async { + if (_database != null) return _database!; + _database = await _initDB(await _resolveDatabasePath()); + return _database!; + } + + Future _resolveDatabasePath() async { + final dbPath = await getDatabasesPath(); + final primaryPath = join(dbPath, _primaryDbName); + final alternatePath = join(dbPath, _alternateDbName); + final primaryFile = File(primaryPath); + final alternateFile = File(alternatePath); + + final hasPrimary = await primaryFile.exists(); + final hasAlternate = await alternateFile.exists(); + + if (hasPrimary && hasAlternate) { + final primaryLength = await primaryFile.length(); + final alternateLength = await alternateFile.length(); + if (primaryLength != alternateLength) { + return primaryLength >= alternateLength ? primaryPath : alternatePath; + } + + final primaryStat = await primaryFile.stat(); + final alternateStat = await alternateFile.stat(); + return primaryStat.modified.isAfter(alternateStat.modified) + ? primaryPath + : alternatePath; + } + + if (hasPrimary) return primaryPath; + if (hasAlternate) return alternatePath; + return primaryPath; + } + + Future _getDatabasePassword() async { + if (_dbPassword != null) return _dbPassword!; + + const key = 'saba_db_password_v1'; + var password = await _secureStorage.read(key: key); + + if (password == null) { + password = + "saba_${DateTime.now().microsecondsSinceEpoch}_${key.hashCode}"; + await _secureStorage.write(key: key, value: password); + } + + _dbPassword = password; + return password; + } + + Future resetAppData() async { + final dbPath = await getDatabasesPath(); + final primaryPath = join(dbPath, _primaryDbName); + final alternatePath = join(dbPath, _alternateDbName); + final keyPath = join(dbPath, '.saba_local.key'); + + if (_database != null) { + await _database!.close(); + _database = null; + } + + for (final path in [primaryPath, alternatePath]) { + try { + await deleteDatabase(path); + } catch (_) {} + final file = File(path); + if (await file.exists()) { + try { + await file.delete(); + } catch (_) {} + } + } + + final keyFile = File(keyPath); + if (await keyFile.exists()) { + try { + await keyFile.delete(); + } catch (_) {} + } + } + + Future _initDB(String path) async { + final password = await _getDatabasePassword(); + try { + return await openDatabase( + path, + password: password, + version: 12, + onCreate: _createDB, + onUpgrade: _onUpgrade, + onConfigure: _onConfigure, + ); + } catch (e) { + if (e.toString().contains('file is not a database') || + e.toString().contains('open_failed')) { + try { + await deleteDatabase(path); + final file = File(path); + if (await file.exists()) { + await file.delete(); + } + } catch (_) {} + + return await openDatabase( + path, + password: password, + version: 7, + onCreate: _createDB, + onUpgrade: _onUpgrade, + onConfigure: _onConfigure, + ); + } + rethrow; + } + } + + Future _onUpgrade(Database db, int oldVersion, int newVersion) async { + if (oldVersion < 2) { + try { + await db.execute( + 'ALTER TABLE contacts_cache ADD COLUMN peer_fingerprint TEXT'); + } catch (_) {} + } + if (oldVersion < 3) { + try { + await db.execute( + 'ALTER TABLE contacts_cache ADD COLUMN symmetric_key TEXT'); + } catch (_) {} + } + if (oldVersion < 5) { + try { + await db.execute(''' + CREATE TABLE IF NOT EXISTS decrypted_cache ( + payload TEXT PRIMARY KEY, + body TEXT, + date INTEGER + ) + '''); + } catch (_) {} + } + if (oldVersion < 6) { + final migrations = [ + 'ALTER TABLE contacts_cache ADD COLUMN ecc_shared_key TEXT', + 'ALTER TABLE contacts_cache ADD COLUMN verification_state TEXT DEFAULT "unverified"', + 'ALTER TABLE contacts_cache ADD COLUMN verified_at INTEGER', + 'ALTER TABLE message_fragments ADD COLUMN packet_mode TEXT', + 'ALTER TABLE message_fragments ADD COLUMN updated_at INTEGER', + ]; + for (final sql in migrations) { + try { + await db.execute(sql); + } catch (_) {} + } + } + if (oldVersion < 7) { + try { + await db.execute(''' + CREATE TABLE IF NOT EXISTS sms_cache ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + sms_id INTEGER UNIQUE, + address TEXT, + body TEXT, + date INTEGER, + type INTEGER, + is_me INTEGER, + is_read INTEGER DEFAULT 1, + is_secure INTEGER DEFAULT 0, + packet_id TEXT, + packet_mode TEXT + ) + '''); + await db.execute( + 'CREATE INDEX IF NOT EXISTS idx_sms_address_date ON sms_cache(address, date)'); + } catch (_) {} + } + if (oldVersion < 9) { + try { + await db.execute( + 'ALTER TABLE message_fragments ADD COLUMN is_me INTEGER DEFAULT 0'); + } catch (_) {} + } + if (oldVersion < 10) { + try { + await db.execute( + 'ALTER TABLE sms_cache ADD COLUMN is_read INTEGER DEFAULT 1'); + await db.execute( + 'ALTER TABLE group_messages ADD COLUMN is_read INTEGER DEFAULT 1'); + } catch (_) {} + } + if (oldVersion < 11) { + try { + await db.execute( + 'ALTER TABLE sms_cache ADD COLUMN is_secure INTEGER DEFAULT 0'); + await db.execute( + 'ALTER TABLE group_messages ADD COLUMN is_secure INTEGER DEFAULT 0'); + } catch (_) {} + } + if (oldVersion < 12) { + try { + await db.execute('ALTER TABLE sms_cache ADD COLUMN packet_id TEXT'); + await db.execute('ALTER TABLE sms_cache ADD COLUMN packet_mode TEXT'); + await db + .execute('ALTER TABLE group_messages ADD COLUMN packet_id TEXT'); + await db + .execute('ALTER TABLE group_messages ADD COLUMN packet_mode TEXT'); + } catch (_) {} + } + } + + Future _onConfigure(Database db) async { + await db.execute('PRAGMA foreign_keys = ON'); + } + + Future _createDB(Database db, int version) async { + await db.execute(''' + CREATE TABLE contacts_cache ( + phone TEXT PRIMARY KEY, + name TEXT, + peer_public_key TEXT, + peer_fingerprint TEXT, + symmetric_key TEXT, + ecc_shared_key TEXT, + secure_state TEXT, + verification_state TEXT DEFAULT 'unverified', + verified_at INTEGER, + mode TEXT DEFAULT 'normal' + ) + '''); + + await db.execute( + 'CREATE TABLE sms_groups (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, group_key TEXT)'); + await db.execute(''' + CREATE TABLE group_members ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + group_id INTEGER, + phone TEXT, + name TEXT, + FOREIGN KEY (group_id) REFERENCES sms_groups (id) ON DELETE CASCADE + ) + '''); + await db.execute(''' + CREATE TABLE group_messages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + group_id INTEGER, + sender_phone TEXT, + body TEXT, + date INTEGER, + is_read INTEGER DEFAULT 1, + is_secure INTEGER DEFAULT 0, + packet_id TEXT, + packet_mode TEXT, + FOREIGN KEY (group_id) REFERENCES sms_groups (id) ON DELETE CASCADE + ) + '''); + + await db.execute(''' + CREATE TABLE message_fragments ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + phone TEXT, + msg_id TEXT, + frag_index INTEGER, + total_frags INTEGER, + packet_mode TEXT, + body TEXT, + date INTEGER, + updated_at INTEGER, + is_me INTEGER DEFAULT 0 + ) + '''); + + await db.execute(''' + CREATE TABLE decrypted_cache ( + payload TEXT PRIMARY KEY, + body TEXT, + date INTEGER + ) + '''); + + await db.execute( + 'CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT)'); + + await db.execute(''' + CREATE TABLE IF NOT EXISTS sms_cache ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + sms_id INTEGER UNIQUE, + address TEXT, + body TEXT, + date INTEGER, + type INTEGER, + is_me INTEGER, + is_read INTEGER DEFAULT 1, + is_secure INTEGER DEFAULT 0, + packet_id TEXT, + packet_mode TEXT + ) + '''); + await db.execute( + 'CREATE INDEX IF NOT EXISTS idx_sms_address_date ON sms_cache(address, date)'); + } + + String _normalizePhone(String phone) { + return PhoneHelper.normalizePhone(phone); + } + + Future cacheContacts(Map contactsMap) async { + final db = await instance.database; + final batch = db.batch(); + contactsMap.forEach((phone, name) { + batch.insert( + 'contacts_cache', {'phone': _normalizePhone(phone), 'name': name}, + conflictAlgorithm: ConflictAlgorithm.ignore); + }); + await batch.commit(noResult: true); + } + + Future?> getContact(String phone) async { + final db = await instance.database; + final res = await db.query('contacts_cache', + where: 'phone = ?', whereArgs: [_normalizePhone(phone)]); + if (res.isEmpty) return null; + return Map.from(res.first); + } + + Future updateContactSecurity( + String phone, { + String? publicKey, + String? state, + String? mode, + String? peerFingerprint, + String? symmetricKey, + String? eccSharedKey, + String? verificationState, + int? verifiedAt, + }) async { + final db = await instance.database; + final cleanPhone = _normalizePhone(phone); + final data = {}; + if (publicKey != null) data['peer_public_key'] = publicKey; + if (state != null) data['secure_state'] = state; + if (mode != null) data['mode'] = mode; + if (peerFingerprint != null) data['peer_fingerprint'] = peerFingerprint; + if (symmetricKey != null) data['symmetric_key'] = symmetricKey; + if (eccSharedKey != null) data['ecc_shared_key'] = eccSharedKey; + if (verificationState != null) { + data['verification_state'] = verificationState; + } + if (verifiedAt != null) { + data['verified_at'] = verifiedAt; + } + + if (data.isEmpty) return; + final existing = await getContact(cleanPhone); + if (existing == null) { + data['phone'] = cleanPhone; + await db.insert('contacts_cache', data); + } else { + await db.update('contacts_cache', data, + where: 'phone = ?', whereArgs: [cleanPhone]); + } + } + + Future resetAsymmetricSecurity(String phone) async { + final db = await instance.database; + final cleanPhone = _normalizePhone(phone); + await db.update( + 'contacts_cache', + { + 'peer_public_key': null, + 'peer_fingerprint': null, + 'ecc_shared_key': null, + 'secure_state': 'none', + 'verification_state': 'unverified', + 'verified_at': null, + 'mode': 'normal', + }, + where: 'phone = ?', + whereArgs: [cleanPhone]); + } + + Future> getCachedContacts() async { + final db = await instance.database; + final result = await db.query('contacts_cache'); + final contacts = {}; + for (final row in result) { + contacts[row['phone'] as String] = + row['name'] as String? ?? row['phone'] as String; + } + return contacts; + } + + Future saveFragment( + String phone, String msgId, int index, int total, String body, + {String packetMode = 'AE', bool isMe = false}) async { + final db = await instance.database; + final normalized = _normalizePhone(phone); + final now = DateTime.now().millisecondsSinceEpoch; + final existing = await db.query('message_fragments', + where: 'phone = ? AND msg_id = ? AND frag_index = ?', + whereArgs: [normalized, msgId, index]); + + if (existing.isEmpty) { + await db.insert('message_fragments', { + 'phone': normalized, + 'msg_id': msgId, + 'frag_index': index, + 'total_frags': total, + 'packet_mode': packetMode, + 'body': body, + 'date': now, + 'updated_at': now, + 'is_me': isMe ? 1 : 0, + }); + } else { + await db.update('message_fragments', {'updated_at': now}, + where: 'phone = ? AND msg_id = ? AND frag_index = ?', + whereArgs: [normalized, msgId, index]); + } + } + + Future>> getFragments( + String phone, String msgId) async { + final db = await instance.database; + return db.query('message_fragments', + where: 'phone = ? AND msg_id = ?', + whereArgs: [_normalizePhone(phone), msgId], + groupBy: 'frag_index', + orderBy: 'frag_index ASC'); + } + + Future>> getPendingPacketsForPhone( + String phone) async { + final db = await instance.database; + return db.rawQuery(''' + SELECT phone, msg_id, packet_mode, COUNT(DISTINCT frag_index) AS received_parts, MAX(total_frags) AS total_parts, MIN(date) AS first_seen, MAX(COALESCE(updated_at, date)) AS last_seen, MAX(is_me) AS isMe + FROM message_fragments WHERE phone = ? GROUP BY phone, msg_id, packet_mode + HAVING COUNT(DISTINCT frag_index) < MAX(total_frags) ORDER BY MIN(date) ASC + ''', [_normalizePhone(phone)]); + } + + Future clearFragments(String phone, String msgId) async { + final db = await instance.database; + await db.delete('message_fragments', + where: 'phone = ? AND msg_id = ?', + whereArgs: [_normalizePhone(phone), msgId]); + } + + Future clearCompletedPackets(String phone) async { + final db = await instance.database; + final normalizedPhone = _normalizePhone(phone); + final completedPackets = await db.rawQuery(''' + SELECT msg_id, packet_mode FROM message_fragments WHERE phone = ? GROUP BY phone, msg_id, packet_mode + HAVING COUNT(DISTINCT frag_index) >= MAX(total_frags) + ''', [normalizedPhone]); + + if (completedPackets.isEmpty) return; + final batch = db.batch(); + for (final row in completedPackets) { + batch.delete('message_fragments', + where: 'phone = ? AND msg_id = ? AND packet_mode = ?', + whereArgs: [normalizedPhone, row['msg_id'], row['packet_mode']]); + } + await batch.commit(noResult: true); + } + + Future clearStalePendingPackets(String phone, + {required int olderThanMs}) async { + final db = await instance.database; + final normalizedPhone = _normalizePhone(phone); + final stalePackets = await db.rawQuery(''' + SELECT msg_id, packet_mode FROM message_fragments WHERE phone = ? GROUP BY phone, msg_id, packet_mode + HAVING COUNT(DISTINCT frag_index) < MAX(total_frags) AND MAX(COALESCE(updated_at, date)) < ? + ''', [normalizedPhone, olderThanMs]); + + if (stalePackets.isEmpty) return; + final batch = db.batch(); + for (final row in stalePackets) { + batch.delete('message_fragments', + where: 'phone = ? AND msg_id = ? AND packet_mode = ?', + whereArgs: [normalizedPhone, row['msg_id'], row['packet_mode']]); + } + await batch.commit(noResult: true); + } + + Future setSetting(String key, String value) async { + final db = await instance.database; + await db.insert('app_settings', {'key': key, 'value': value}, + conflictAlgorithm: ConflictAlgorithm.replace); + } + + Future getSetting(String key) async { + final db = await instance.database; + final res = + await db.query('app_settings', where: 'key = ?', whereArgs: [key]); + return res.isNotEmpty ? res.first['value'] as String : null; + } + + Future saveIdentity( + {required String privateKey, + required String publicKey, + required String fingerprint}) async { + await setSetting('identity_private', privateKey); + await setSetting('identity_public', publicKey); + await setSetting('identity_fingerprint', fingerprint); + } + + Future?> getIdentity() async { + final privateKey = await getSetting('identity_private'); + final publicKey = await getSetting('identity_public'); + final fingerprint = await getSetting('identity_fingerprint'); + if (privateKey == null || publicKey == null || fingerprint == null) { + return null; + } + return { + 'privateKey': privateKey, + 'publicKey': publicKey, + 'fingerprint': fingerprint + }; + } + + Future createGroup( + String name, List> members) async { + final db = await instance.database; + final groupId = await db.insert('sms_groups', {'name': name}); + final batch = db.batch(); + for (final m in members) { + batch.insert('group_members', { + 'group_id': groupId, + 'phone': _normalizePhone(m['phone']!), + 'name': m['name'] + }); + } + await batch.commit(noResult: true); + return groupId; + } + + Future>> getGroups() async { + final db = await instance.database; + final rows = await db.query('sms_groups', orderBy: 'id DESC'); + return rows.map((row) => Map.from(row)).toList(); + } + + Future updateGroupName(int groupId, String newName) async { + final db = await instance.database; + return db.update('sms_groups', {'name': newName}, + where: 'id = ?', whereArgs: [groupId]); + } + + Future updateGroupKey(int groupId, String key) async { + final db = await instance.database; + return db.update('sms_groups', {'group_key': key}, + where: 'id = ?', whereArgs: [groupId]); + } + + Future>> getGroupsContainingPhone( + String phone) async { + final db = await instance.database; + final rows = await db.rawQuery(''' + SELECT g.* FROM sms_groups g JOIN group_members m ON g.id = m.group_id WHERE m.phone = ? + ''', [_normalizePhone(phone)]); + return rows.map((row) => Map.from(row)).toList(); + } + + Future>> getGroupMembers(int groupId) async { + final db = await instance.database; + return db + .query('group_members', where: 'group_id = ?', whereArgs: [groupId]); + } + + Future addMemberToGroup(int groupId, String name, String phone) async { + final db = await instance.database; + final cleanPhone = _normalizePhone(phone); + final exists = await db.query('group_members', + where: 'group_id = ? AND phone = ?', whereArgs: [groupId, cleanPhone]); + if (exists.isNotEmpty) return false; + await db.insert('group_members', + {'group_id': groupId, 'phone': cleanPhone, 'name': name}); + return true; + } + + Future removeGroupMember(int groupId, String phone) async { + final db = await instance.database; + return db.delete('group_members', + where: 'id = ? AND phone = ?', + whereArgs: [groupId, _normalizePhone(phone)]); + } + + Future saveGroupMessage(int groupId, String body, int date, + {String? senderPhone, + int isSecure = 0, + String? packetId, + String? packetMode}) async { + final db = await instance.database; + return await db.insert('group_messages', { + 'group_id': groupId, + 'sender_phone': senderPhone != null ? _normalizePhone(senderPhone) : null, + 'body': body, + 'date': date, + 'is_read': 0, + 'is_secure': isSecure, + 'packet_id': packetId, + 'packet_mode': packetMode, + }); + } + + Future>> getGroupMessages(int groupId) async { + final db = await instance.database; + return db.query('group_messages', + where: 'group_id = ?', whereArgs: [groupId], orderBy: 'date DESC'); + } + + Future saveDecrypted(String payload, String decrypted) async { + final db = await instance.database; + await db.insert( + 'decrypted_cache', + { + 'payload': payload, + 'body': decrypted, + 'date': DateTime.now().millisecondsSinceEpoch, + }, + conflictAlgorithm: ConflictAlgorithm.replace); + } + + Future getDecrypted(String payload) async { + final db = await instance.database; + final res = await db + .query('decrypted_cache', where: 'payload = ?', whereArgs: [payload]); + if (res.isEmpty) return null; + return res.first['body'] as String?; + } + + Future deleteGroupMessage(int messageId) async { + final db = await instance.database; + return db.delete('group_messages', where: 'id = ?', whereArgs: [messageId]); + } + + Future deleteGroup(int groupId) async { + final db = await instance.database; + return db.delete('sms_groups', where: 'id = ?', whereArgs: [groupId]); + } + + // --- SMS Cache for Performance --- + + Future saveSingleSmsToCache(Map sms) async { + final db = await instance.database; + final data = Map.from(sms); + if (!data.containsKey('is_read')) { + data['is_read'] = 1; // Default to read if not specified + } + return await db.insert('sms_cache', data, + conflictAlgorithm: ConflictAlgorithm.replace); + } + + Future markAsRead(String address) async { + final db = await instance.database; + await db.update('sms_cache', {'is_read': 1}, + where: 'address = ?', whereArgs: [_normalizePhone(address)]); + } + + Future markGroupAsRead(int groupId) async { + final db = await instance.database; + await db.update('group_messages', {'is_read': 1}, + where: 'group_id = ?', whereArgs: [groupId]); + } + + bool _isUnreadExcludedProtocolType(String type) { + return type == 'key_init' || + type == 'key_reply' || + type == 'norm' || + type == 'nack'; + } + + String? _packetModeForProtocolType(String type) { + switch (type) { + case 'sym': + case 'sfra': + return 'SYM'; + case 'asym': + case 'afrag': + return 'AE'; + default: + return null; + } + } + + String? _unreadLogicalKey(Map row, {bool isGroup = false}) { + final body = row['body'] as String? ?? ''; + final parsed = ProtocolHelper.parseMessage(body); + final type = parsed['type'] as String? ?? 'plain'; + if (_isUnreadExcludedProtocolType(type)) { + return null; + } + + final packetId = + (row['packet_id'] as String?) ?? (parsed['packetId'] as String?); + final packetMode = + (row['packet_mode'] as String?) ?? _packetModeForProtocolType(type); + + if (packetId != null && + packetId.isNotEmpty && + packetMode != null && + packetMode.isNotEmpty) { + return 'packet::$packetMode::$packetId'; + } + + final smsId = row['sms_id'] as int?; + if (smsId != null) { + return 'sms::$smsId'; + } + + final rowId = row['id'] as int?; + if (rowId != null) { + return '${isGroup ? 'group' : 'cache'}::$rowId'; + } + + final date = row['date'] as int? ?? 0; + return 'body::$date::${body.hashCode}'; + } + + Future getUnreadCount(String address) async { + final db = await instance.database; + final rows = await db.query( + 'sms_cache', + columns: ['id', 'sms_id', 'body', 'packet_id', 'packet_mode', 'date'], + where: 'address = ? AND is_read = 0 AND is_me = 0', + whereArgs: [_normalizePhone(address)], + orderBy: 'date DESC, id DESC', + ); + + final logicalMessages = {}; + for (final row in rows) { + final key = _unreadLogicalKey(Map.from(row)); + if (key != null) { + logicalMessages.add(key); + } + } + return logicalMessages.length; + } + + Future getGroupUnreadCount(int groupId) async { + final db = await instance.database; + final rows = await db.query( + 'group_messages', + columns: [ + 'id', + 'body', + 'packet_id', + 'packet_mode', + 'date', + 'sender_phone' + ], + where: 'group_id = ? AND is_read = 0 AND sender_phone IS NOT NULL', + whereArgs: [groupId], + orderBy: 'date DESC, id DESC', + ); + + final logicalMessages = {}; + for (final row in rows) { + final key = + _unreadLogicalKey(Map.from(row), isGroup: true); + if (key != null) { + logicalMessages.add(key); + } + } + return logicalMessages.length; + } + + Future batchInsertSms(List> smsList) async { + final db = await instance.database; + const duplicateWindowMs = 5000; + + await db.transaction((txn) async { + for (final sms in smsList) { + final data = Map.from(sms); + final smsId = data['sms_id'] as int?; + final address = _normalizePhone(data['address'] as String? ?? ''); + final body = data['body'] as String? ?? ''; + final date = data['date'] as int? ?? 0; + final isMe = data['is_me'] as int? ?? 0; + final parsed = ProtocolHelper.parseMessage(body); + final parsedType = parsed['type'] as String? ?? 'plain'; + final parsedPacketId = parsed['packetId'] as String?; + final parsedPacketMode = switch (parsedType) { + 'sym' || 'sfra' => 'SYM', + 'asym' || 'afrag' => 'AE', + _ => null, + }; + final isSecureProtocol = parsedPacketMode != null; + + data['address'] = address; + + if (smsId != null) { + final existingBySmsId = await txn.query( + 'sms_cache', + columns: ['id'], + where: 'sms_id = ?', + whereArgs: [smsId], + limit: 1, + ); + if (existingBySmsId.isNotEmpty) { + await txn.delete( + 'sms_cache', + where: + 'sms_id IS NULL AND address = ? AND body = ? AND is_me = ? AND ABS(date - ?) <= ?', + whereArgs: [address, body, isMe, date, duplicateWindowMs], + ); + + if (isSecureProtocol) { + List> staleSecureRows = []; + if (parsedPacketId != null && parsedPacketId.isNotEmpty) { + staleSecureRows = await txn.query( + 'sms_cache', + columns: ['id'], + where: + 'sms_id IS NULL AND address = ? AND is_me = ? AND is_secure = 1 AND packet_id = ? AND packet_mode = ? AND ABS(date - ?) <= ?', + whereArgs: [ + address, + isMe, + parsedPacketId, + parsedPacketMode, + date, + duplicateWindowMs, + ], + orderBy: 'ABS(date - $date) ASC, id DESC', + limit: 1, + ); + } + + if (staleSecureRows.isEmpty) { + staleSecureRows = await txn.query( + 'sms_cache', + columns: ['id'], + where: + 'sms_id IS NULL AND address = ? AND is_me = ? AND is_secure = 1 AND packet_mode = ? AND ABS(date - ?) <= ?', + whereArgs: [ + address, + isMe, + parsedPacketMode, + date, + duplicateWindowMs, + ], + orderBy: 'ABS(date - $date) ASC, id DESC', + limit: 1, + ); + } + + if (staleSecureRows.isNotEmpty) { + await txn.delete( + 'sms_cache', + where: 'id = ?', + whereArgs: [staleSecureRows.first['id']], + ); + } + } + continue; + } + + final syncedMatch = await txn.query( + 'sms_cache', + columns: ['id'], + where: + 'sms_id IS NULL AND address = ? AND body = ? AND is_me = ? AND ABS(date - ?) <= ?', + whereArgs: [address, body, isMe, date, duplicateWindowMs], + orderBy: 'date DESC, id DESC', + limit: 1, + ); + + if (syncedMatch.isNotEmpty) { + await txn.update( + 'sms_cache', + { + 'sms_id': smsId, + 'date': date, + 'type': data['type'], + 'is_me': isMe, + 'address': address, + }, + where: 'id = ?', + whereArgs: [syncedMatch.first['id']], + ); + continue; + } + + if (isSecureProtocol) { + List> secureFallbackMatch = []; + if (parsedPacketId != null && parsedPacketId.isNotEmpty) { + secureFallbackMatch = await txn.query( + 'sms_cache', + columns: ['id'], + where: + 'sms_id IS NULL AND address = ? AND is_me = ? AND is_secure = 1 AND packet_id = ? AND packet_mode = ? AND ABS(date - ?) <= ?', + whereArgs: [ + address, + isMe, + parsedPacketId, + parsedPacketMode, + date, + duplicateWindowMs, + ], + orderBy: 'ABS(date - $date) ASC, id DESC', + limit: 1, + ); + } + + if (secureFallbackMatch.isEmpty) { + secureFallbackMatch = await txn.query( + 'sms_cache', + columns: ['id'], + where: + 'sms_id IS NULL AND address = ? AND is_me = ? AND is_secure = 1 AND packet_mode = ? AND ABS(date - ?) <= ?', + whereArgs: [ + address, + isMe, + parsedPacketMode, + date, + duplicateWindowMs, + ], + orderBy: 'ABS(date - $date) ASC, id DESC', + limit: 1, + ); + } + + if (secureFallbackMatch.isNotEmpty) { + await txn.update( + 'sms_cache', + { + 'sms_id': smsId, + 'date': date, + 'type': data['type'], + 'is_me': isMe, + 'address': address, + 'packet_id': parsedPacketId, + 'packet_mode': parsedPacketMode, + 'is_secure': 1, + }, + where: 'id = ?', + whereArgs: [secureFallbackMatch.first['id']], + ); + continue; + } + } + } + + await txn.insert( + 'sms_cache', + data, + conflictAlgorithm: ConflictAlgorithm.ignore, + ); + } + }); + } + + Future>> getPaginatedSms( + String address, int limit, int offset, + {int? afterDate}) async { + final db = await instance.database; + final normalized = _normalizePhone(address); + const orderBy = 'date DESC, sms_id DESC, id DESC'; + if (afterDate == null) { + return db.query('sms_cache', + where: 'address = ?', + whereArgs: [normalized], + orderBy: orderBy, + limit: limit, + offset: offset); + } else { + return db.query('sms_cache', + where: 'address = ? AND date >= ?', + whereArgs: [normalized, afterDate], + orderBy: orderBy, + limit: limit, + offset: offset); + } + } + + Future getSmsCount(String address) async { + final db = await instance.database; + final normalized = _normalizePhone(address); + final result = await db.rawQuery( + 'SELECT COUNT(*) FROM sms_cache WHERE address = ?', [normalized]); + return Sqflite.firstIntValue(result) ?? 0; + } + + Future>> getConversations() async { + final db = await instance.database; + // Uses a subquery to find the latest message ID for each unique address + return await db.rawQuery(''' + SELECT * FROM sms_cache + WHERE id IN (SELECT MAX(id) FROM sms_cache GROUP BY address) + ORDER BY date DESC + '''); + } + + Future clearSmsCacheForAddress(String address) async { + final db = await instance.database; + final normalized = _normalizePhone(address); + return db + .delete('sms_cache', where: 'address = ?', whereArgs: [normalized]); + } + + Future updateSmsBody(int id, String newBody, + {int? isSecure, String? packetId, String? packetMode}) async { + final db = await database; + final Map values = {'body': newBody}; + if (isSecure != null) { + values['is_secure'] = isSecure; + } + if (packetId != null) { + values['packet_id'] = packetId; + } + if (packetMode != null) { + values['packet_mode'] = packetMode; + } + return await db.update( + 'sms_cache', + values, + where: 'id = ?', + whereArgs: [id], + ); + } + + Future consolidatePacketMessage( + String address, { + required String packetId, + required String packetMode, + required String body, + required int date, + required int type, + required int isMe, + int isRead = 1, + int isSecure = 1, + }) async { + final db = await database; + final normalized = _normalizePhone(address); + final rows = await db.query( + 'sms_cache', + columns: ['id'], + where: 'address = ? AND packet_id = ? AND packet_mode = ?', + whereArgs: [normalized, packetId, packetMode], + orderBy: 'date DESC, sms_id DESC, id DESC', + ); + + if (rows.isNotEmpty) { + final keeperId = rows.first['id'] as int; + await db.update( + 'sms_cache', + { + 'body': body, + 'date': date, + 'type': type, + 'is_me': isMe, + 'is_read': isRead, + 'is_secure': isSecure, + 'packet_id': packetId, + 'packet_mode': packetMode, + }, + where: 'id = ?', + whereArgs: [keeperId], + ); + + if (rows.length > 1) { + final duplicateIds = + rows.skip(1).map((row) => row['id'] as int).toList(growable: false); + await db.delete( + 'sms_cache', + where: 'id IN (${List.filled(duplicateIds.length, '?').join(', ')})', + whereArgs: duplicateIds, + ); + } + + return keeperId; + } + + return db.insert('sms_cache', { + 'address': normalized, + 'body': body, + 'date': date, + 'type': type, + 'is_me': isMe, + 'is_read': isRead, + 'is_secure': isSecure, + 'packet_id': packetId, + 'packet_mode': packetMode, + }); + } + + Future deleteSmsFragments(String address, String packetId) async { + final db = await database; + return await db.delete( + 'sms_cache', + where: 'address = ? AND (packet_id = ? OR body LIKE ?)', + whereArgs: [_normalizePhone(address), packetId, '%|$packetId|%'], + ); + } + + Future deleteGroupFragments(int groupId, String packetId) async { + final db = await database; + return await db.delete( + 'group_messages', + where: 'group_id = ? AND body LIKE ?', + whereArgs: [groupId, '%|$packetId|%'], + ); + } +} diff --git a/lib/utils/message_processor.dart b/lib/utils/message_processor.dart new file mode 100644 index 0000000..448433e --- /dev/null +++ b/lib/utils/message_processor.dart @@ -0,0 +1,168 @@ +import '../models/chat_model.dart'; +import 'protocol_helper.dart'; + +class MessageProcessor { + /// Processes raw SMS data into ChatModel objects in a background-friendly way. + /// This is intended to be called via compute() or Isolate.run(). + static List processSmsList( + List> rawSmsList, String targetAddress) { + // 1. Sort by date + final allSms = List>.from(rawSmsList) + ..sort((a, b) { + final dateComp = + (a['date'] as int? ?? 0).compareTo(b['date'] as int? ?? 0); + if (dateComp != 0) return dateComp; + final smsIdComp = + (a['sms_id'] as int? ?? 0).compareTo(b['sms_id'] as int? ?? 0); + if (smsIdComp != 0) return smsIdComp; + return (a['id'] as int? ?? 0).compareTo(b['id'] as int? ?? 0); + }); + + final convertedMessages = []; + final processedPacketIds = {}; + final packetLeaders = {}; // packetKey -> newest SMS ID + final packetFragments = >>{}; + final packetTotals = {}; + final allDecryptedBodies = {}; + + // PASS 1: Identify all packets and their status + for (final sms in allSms) { + final bodyText = (sms['body'] as String).trim(); + final parsed = ProtocolHelper.parseMessage(bodyText); + final type = parsed['type'] as String; + final bool dbIsSecure = (sms['is_secure'] as int? ?? 0) == 1; + + final packetId = parsed['packetId'] as String?; + final packetMode = (type == 'asym' || type == 'afrag') ? 'AE' : 'SYM'; + final packetKey = (packetId == null || packetId.isEmpty) + ? null + : '$packetMode::$packetId'; + + if (type == 'sym' || type == 'asym') { + if (packetKey != null) { + processedPacketIds.add(packetKey); + } + } + + if (dbIsSecure && type == 'plain') { + allDecryptedBodies.add(bodyText); + } + + if (type == 'key_init' || type == 'key_reply' || type == 'norm') continue; + + if ((type == 'sfra' || type == 'afrag') && packetKey != null) { + packetLeaders[packetKey] = sms['sms_id'] as int? ?? 0; + packetFragments.putIfAbsent(packetKey, () => []).add(sms); + packetTotals[packetKey] = parsed['totalParts'] as int? ?? 1; + } + } + + // PASS 2: Convert to ChatModel with linked deduplication + for (final sms in allSms) { + final isMe = (sms['is_me'] as int? ?? 0) == 1; + final smsId = sms['sms_id'] as int?; + final cacheRowId = sms['id'] as int?; + final rawBody = (sms['body'] as String); + final bool dbIsSecure = (sms['is_secure'] as int? ?? 0) == 1; + + final parsed = ProtocolHelper.parseMessage(rawBody); + final type = parsed['type'] as String; + + // Deduplication Rule: If this is a plain message but its content is a known decrypted version of a secure message, skip. + if (type == 'plain' && + !dbIsSecure && + allDecryptedBodies.contains(rawBody.trim())) { + continue; + } + + if (type == 'key_init' || type == 'key_reply' || type == 'norm') continue; + + final String? dbPacketId = sms['packet_id'] as String?; + final String? dbPacketMode = sms['packet_mode'] as String?; + final packetId = dbPacketId ?? parsed['packetId'] as String?; + final bool isAsymmetric = type == 'afrag' || type == 'asym'; + final String packetMode = dbPacketMode ?? (isAsymmetric ? 'AE' : 'SYM'); + final packetKey = (packetId == null || packetId.isEmpty) + ? null + : '$packetMode::$packetId'; + final isFragment = type == 'sfra' || type == 'afrag'; + + // Deduplication: If we already have a decrypted/complete version of this packet, skip the fragments. + if (packetKey != null && + processedPacketIds.contains(packetKey) && + !dbIsSecure && + (isFragment || type == 'sym' || type == 'asym')) { + continue; + } + + String bodyText = rawBody; + String? encryptedPayload; + bool isSecureMessage = dbIsSecure || type != 'plain'; + bool isAssembled = false; + + if (isFragment && packetKey != null) { + if (packetLeaders[packetKey] != sms['sms_id']) continue; + + final fragments = packetFragments[packetKey] ?? []; + final totalPartsCount = packetTotals[packetKey] ?? 1; + final receivedPartsCount = fragments.length; + + if (receivedPartsCount == totalPartsCount) { + fragments.sort((a, b) { + final pA = + ProtocolHelper.parseMessage(a['body'] as String)['partNo'] + as int? ?? + 0; + final pB = + ProtocolHelper.parseMessage(b['body'] as String)['partNo'] + as int? ?? + 0; + return pA.compareTo(pB); + }); + final payload = fragments + .map((f) => + ProtocolHelper.parseMessage(f['body'] as String)['chunk'] + as String? ?? + '') + .join(); + final isGroup = parsed['isGroup'] == true; + bodyText = (type == 'sfra') + ? (isGroup + ? '${ProtocolHelper.gPrefix}${ProtocolHelper.typeSym}|$payload' + : ProtocolHelper.buildSymmetricMsg(payload)) + : ProtocolHelper.buildAsymmetricMsg(payload); + encryptedPayload = payload; + isAssembled = true; + processedPacketIds.add(packetKey); + } else { + bodyText = + 'در حال ${isMe ? "ارسال" : "دریافت"} قطعات... ($receivedPartsCount/$totalPartsCount)'; + } + } else if (type != 'plain') { + if (type == 'sym' || type == 'asym') { + encryptedPayload = parsed['payload'] as String?; + if (packetKey != null) processedPacketIds.add(packetKey); + } + } + + convertedMessages.add(ChatModel( + id: smsId, + localId: cacheRowId != null ? 'cache::$cacheRowId' : null, + body: bodyText, + rawBody: rawBody, + encryptedPayload: encryptedPayload, + packetId: packetId, + packetMode: (packetId != null) ? packetMode : null, + date: sms['date'] as int? ?? 0, + isMe: isMe, + status: isMe ? MessageStatus.sent : MessageStatus.received, + isSecure: isSecureMessage, + isPendingMultipart: isFragment && !isAssembled, + statusLabel: + (isFragment && !isAssembled) ? 'در حال دریافت قطعات...' : null, + )); + } + + return convertedMessages.reversed.toList(); + } +} diff --git a/lib/utils/notification_helper.dart b/lib/utils/notification_helper.dart new file mode 100644 index 0000000..f59afe3 --- /dev/null +++ b/lib/utils/notification_helper.dart @@ -0,0 +1,67 @@ +import 'dart:async'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; + +class NotificationHelper { + static final NotificationHelper instance = NotificationHelper._init(); + final StreamController notificationStreamController = StreamController.broadcast(); + Stream get notificationStream => notificationStreamController.stream; + final FlutterLocalNotificationsPlugin _notificationsPlugin = + FlutterLocalNotificationsPlugin(); + bool _isInitialized = false; + + NotificationHelper._init(); + + Future init() async { + const AndroidInitializationSettings initializationSettingsAndroid = + AndroidInitializationSettings('@mipmap/ic_launcher'); + + const InitializationSettings initializationSettings = + InitializationSettings( + android: initializationSettingsAndroid, + ); + + await _notificationsPlugin.initialize( + initializationSettings, + onDidReceiveNotificationResponse: (details) { + if (details.payload != null) { + // This will be handled by the UI listening to a stream or similar + // or we can use a global navigator key if available. + // For now, we'll use a static notificationStream to let listeners know. + notificationStreamController.add(details.payload!); + } + }, + ); + _isInitialized = true; + } + + Future showNotification({ + required int id, + required String title, + required String body, + String? payload, + }) async { + if (!_isInitialized) await init(); + + const AndroidNotificationDetails androidPlatformChannelSpecifics = + AndroidNotificationDetails( + 'sms_channel', + 'SMS Notifications', + channelDescription: 'Notifications for incoming secure messages', + importance: Importance.max, + priority: Priority.high, + showWhen: true, + ); + + const NotificationDetails platformChannelSpecifics = NotificationDetails( + android: androidPlatformChannelSpecifics, + ); + + await _notificationsPlugin.show( + id, + title, + body, + platformChannelSpecifics, + payload: payload, + ); + } +} diff --git a/lib/utils/phone_helper.dart b/lib/utils/phone_helper.dart new file mode 100644 index 0000000..4a77079 --- /dev/null +++ b/lib/utils/phone_helper.dart @@ -0,0 +1,36 @@ +class PhoneHelper { + static String normalizePhone(String phone) { + final raw = phone.trim(); + if (raw.isEmpty) return ''; + + final digits = raw.replaceAll(RegExp(r'\D'), ''); + if (digits.isEmpty) return raw; + + if (raw.startsWith('+')) { + return '+$digits'; + } + + if (raw.startsWith('00') && digits.length > 2) { + return '+${digits.substring(2)}'; + } + + // Iranian local formats + if (digits.length == 11 && digits.startsWith('0')) { + return '+98${digits.substring(1)}'; + } + if (digits.length == 10) { + return '+98$digits'; + } + if (digits.startsWith('98') && digits.length >= 12 && digits.length <= 15) { + return '+$digits'; + } + + // Preserve full international numbers instead of collapsing them to + // the last 10 digits, which can merge different identities together. + if (digits.length >= 11 && digits.length <= 15) { + return '+$digits'; + } + + return raw; + } +} diff --git a/lib/utils/protocol_helper.dart b/lib/utils/protocol_helper.dart new file mode 100644 index 0000000..f27f745 --- /dev/null +++ b/lib/utils/protocol_helper.dart @@ -0,0 +1,467 @@ +import 'dart:convert'; +import 'dart:math'; + +import 'package:flutter/foundation.dart'; + +class ProtocolHelper { + static const String prefix = "@S:"; + static const String gPrefix = "@G:"; + + static const String typeNack = "NACK"; + static const String typeSym = "SYM"; + static const String typeSfra = "SFRA"; + static const String typeNorm = "NORM"; + static const String typeKeyInit = "KI"; + static const String typeKeyReply = "KR"; + static const String typeAsym = "AE"; + static const String typeAsymFrag = "AF"; + + static const int maxSmsChars = 136; + static const int fragmentHeaderBytes = 6; + static const int fragmentChunkBytes = 90; + + static String encodeTransportPayload(List bytes) { + return base64UrlEncode(bytes).replaceAll('=', ''); + } + + static List decodeTransportPayload(String value) { + // Parity with Python _repair_base64 and SecureCryptoHelper.b64uDecode + // 1. Map common mangles including space-to-plus + String clean = value.replaceAll(' ', '+'); + + // 2. Map mangled separators to standard Base64 characters + clean = + clean.replaceAll('|', '/').replaceAll(';', '/').replaceAll('!', '/'); + + // 3. Keep ONLY valid Base64/Base64URL characters + clean = clean.replaceAll(RegExp(r'[^A-Za-z0-9+/=\-_]'), ''); + + // 4. Standardize alphabet (Base64URL -> Standard Base64 for the decoder) + clean = clean.replaceAll('-', '+').replaceAll('_', '/'); + + // 5. Recalculate padding + clean = clean.split('=')[0]; + final missingPadding = (4 - (clean.length % 4)) % 4; + return base64.decode(clean + ('=' * missingPadding)); + } + + static String _b64Encode(List bytes) => encodeTransportPayload(bytes); + static List _b64Decode(String value) => decodeTransportPayload(value); + + static List _transportCandidates(String value) { + final normalized = value + .replaceAll('¡', '@') + .replaceAll('¡', '@') + .replaceAll('ö', '|') + .replaceAll('ö', '|') + .replaceAll('§', '|') + .replaceAll('§', '|') + .replaceAll(RegExp(r'\s+'), ''); + + final candidates = {normalized}; + final separatorPattern = RegExp(r'[|;!]'); + final matches = separatorPattern.allMatches(normalized).toList(); + if (matches.isEmpty) return candidates.toList(); + + final replacementOptions = ['', '-', '_']; + final maxRepairs = matches.length > 4 ? 4 : matches.length; + + void build(int index, String current, int offset) { + if (index >= maxRepairs) { + candidates.add(current); + return; + } + + final match = matches[index]; + final start = match.start + offset; + final end = match.end + offset; + for (final replacement in replacementOptions) { + final next = + current.substring(0, start) + replacement + current.substring(end); + final nextOffset = + offset + replacement.length - (match.end - match.start); + build(index + 1, next, nextOffset); + } + } + + build(0, normalized, 0); + return candidates.toList(); + } + + static Map? _parseAsymmetricFragmentPayload( + String encoded, { + required bool isGroup, + }) { + for (final candidate in _transportCandidates(encoded)) { + try { + final raw = _b64Decode(candidate); + if (raw.length < 6) continue; + final packetId = raw + .sublist(0, 4) + .map((b) => b.toRadixString(16).padLeft(2, '0')) + .join(); + return { + "type": "afrag", + "isGroup": isGroup, + "packetId": packetId, + "totalParts": raw[4], + "partNo": raw[5], + "chunk": _b64Encode(raw.sublist(6)) + }; + } catch (_) {} + } + return null; + } + + static String buildSymmetricMsg(String encryptedPayload) { + return "$prefix$typeSym|$encryptedPayload"; + } + + static String buildAsymmetricMsg(String b64Payload) { + return "$prefix$typeAsym|$b64Payload"; + } + + static String buildSymmetricFrag( + String packetId, int partNo, int totalParts, String chunk) { + return "$prefix$typeSfra|$packetId|$partNo|$totalParts|$chunk"; + } + + static String buildNormalMode() { + return "$prefix$typeNorm|"; + } + + static String buildKeyInit(String publicKeyPayload) { + return "$prefix$typeKeyInit|$publicKeyPayload"; + } + + static String buildKeyReply(String publicKeyPayload) { + return "$prefix$typeKeyReply|$publicKeyPayload"; + } + + static List buildAsymmetricFrames(List payloadBytes, + {String? packetId}) { + final single = "$prefix$typeAsym|${_b64Encode(payloadBytes)}"; + if (single.length <= maxSmsChars) { + return [single]; + } + return buildAsymmetricFragments(payloadBytes, packetId: packetId); + } + + static List buildAsymmetricFragments(List payloadBytes, + {String? packetId}) { + final random = Random(); + final packetRaw = packetId != null + ? Uint8List.fromList(List.generate( + packetId.length ~/ 2, + (index) => int.parse(packetId.substring(index * 2, index * 2 + 2), + radix: 16), + )) + : Uint8List.fromList(List.generate(4, (_) => random.nextInt(256))); + if (packetRaw.length != 4) { + throw StateError('Asymmetric packet ids must contain exactly 4 bytes.'); + } + + final total = (payloadBytes.length / fragmentChunkBytes).ceil(); + if (total > 255) { + throw StateError('Payload is too large for SMS fragmentation.'); + } + final frames = []; + for (var i = 0; i < total; i++) { + final start = i * fragmentChunkBytes; + final end = min(start + fragmentChunkBytes, payloadBytes.length); + final chunk = payloadBytes.sublist(start, end); + final raw = Uint8List.fromList([ + ...packetRaw, + total, + i + 1, + ...chunk, + ]); + frames.add("$prefix$typeAsymFrag|${_b64Encode(raw)}"); + } + return frames; + } + + static Map parseMessage(String rawText) { + if (rawText.isEmpty) return {"type": "plain", "body": ""}; + + // Step 1: Preliminary cleaning (Mojibake Fix & Control Code Removal) + // Remove all non-printable control characters immediately + String cleaned = rawText.replaceAll(RegExp(r'[\x00-\x1F\x7F-\x9F]'), ''); + + // Parity with Python: DO NOT trim(). Only remove newlines and nulls at the end. + // This preserves trailing spaces that might be mangled '+' characters. + String body = cleaned.replaceAll(RegExp(r'[\x00\r\n]+$'), ''); + + // Mojibake Fix + body = body + .replaceAll('¡', '@') + .replaceAll('¡', '@') + .replaceAll('ö', '|') + .replaceAll('ö', '|') + .replaceAll('§', '|') + .replaceAll('§', '|') + .replaceAll('¿', '?') + .replaceAll('¿', '?'); + + // Fast-path for legacy symmetric fragments. This avoids falling through to + // generic SYM/b1 parsing when the SMS transport slightly damages the + // prefix but the SFRA structure is still intact. + final directSfra = RegExp( + r'SFRA\s*[|;!ö§]\s*([^|;!ö§\s]+)\s*[|;!ö§]\s*(\d+)\s*[|;!ö§]\s*(\d+)\s*[|;!ö§](.*)$', + caseSensitive: false, + ).firstMatch(body); + if (directSfra != null) { + final lowerBodyForGroup = body.toUpperCase(); + final rawChunk = directSfra.group(4) ?? ''; + return { + "type": "sfra", + "isGroup": lowerBodyForGroup.contains('@G:') || + lowerBodyForGroup.contains('G|'), + "packetId": (directSfra.group(1) ?? '').trim(), + "partNo": int.tryParse((directSfra.group(2) ?? '').trim()) ?? 1, + "totalParts": int.tryParse((directSfra.group(3) ?? '').trim()) ?? 1, + "chunk": rawChunk.replaceAll(RegExp(r'\s+'), ''), + }; + } + + final directAf = RegExp( + r'AF\s*[|;!ö§]\s*(.+)$', + caseSensitive: false, + ).firstMatch(body); + if (directAf != null) { + final lowerBodyForGroup = body.toUpperCase(); + final parsedAf = _parseAsymmetricFragmentPayload( + directAf.group(1) ?? '', + isGroup: lowerBodyForGroup.contains('@G:') || + lowerBodyForGroup.contains('G|'), + ); + if (parsedAf != null) { + return parsedAf; + } + } + + // Step 2: Protocol Search + final protocolTypes = [ + typeSfra, + typeSym, + typeAsym, + typeAsymFrag, + typeNorm, + typeKeyInit, + typeKeyReply, + typeNack + ]; + + // Structural delimiters (Mainly | ; ! but also ö and § as fallbacks) + final sepRegex = RegExp(r'[|;!ö§]'); + + int startIdx = -1; + String? detectedType; + bool isGroup = false; + + // A. Standard Header Search (@S: or @G:) - Case Insensitive + final lowerBody = body.toLowerCase(); + final sIdx = lowerBody.indexOf(prefix.toLowerCase()); + final gIdx = lowerBody.indexOf(gPrefix.toLowerCase()); + + if (sIdx != -1 || gIdx != -1) { + isGroup = gIdx != -1 && (sIdx == -1 || gIdx < sIdx); + startIdx = isGroup ? gIdx : sIdx; + final actualPrefixLength = isGroup ? gPrefix.length : prefix.length; + + final contentAfterPrefix = + body.substring(startIdx + actualPrefixLength).trim(); + final lowerContent = contentAfterPrefix.toLowerCase(); + + for (final t in protocolTypes) { + if (lowerContent.startsWith(t.toLowerCase())) { + detectedType = t; + break; + } + } + } + + debugPrint( + '[PROTOCOL] Search Header: detected=$detectedType, startIdx=$startIdx, isGroup=$isGroup'); + + // B. Fuzzy Fallback (Marker + Separator) + if (detectedType == null) { + final fuzzyProtocolTypes = [typeSfra, typeSym, typeAsymFrag]; + for (final t in fuzzyProtocolTypes) { + // Broaden the separator character set for fuzzy matching + final fuzzyRegex = + RegExp('${t.toLowerCase()}\\s*[|;!ö§:]', caseSensitive: false); + final match = fuzzyRegex.firstMatch(body); + if (match != null) { + detectedType = t; + startIdx = max(0, match.start - 3); + final lookback = body.substring(0, match.start).toUpperCase(); + isGroup = lookback.contains('@G:') || lookback.contains('G|'); + break; + } + } + debugPrint( + '[PROTOCOL] Search Fuzzy: detected=$detectedType, startIdx=$startIdx, isGroup=$isGroup'); + } + + // C. Raw Variant Fallback (b1: or h1:) + if (detectedType == null) { + final normalizedBody = body.trimLeft(); + final lower = normalizedBody.toLowerCase(); + if (lower.startsWith('b1:') || lower.startsWith('h1:')) { + return { + "type": "sym", + "isGroup": false, + "payload": normalizedBody.trim() + }; + } + return {"type": "plain", "body": rawText}; + } + + // Step 3: Extract Payload from First Structural Separator + // Find the first occurrence of detectedType after startIdx + final typeStartPos = + body.toUpperCase().indexOf(detectedType.toUpperCase(), startIdx); + if (typeStartPos == -1) return {"type": "plain", "body": rawText}; + + final sepMatch = sepRegex.firstMatch(body.substring(typeStartPos)); + if (sepMatch == null) { + if (detectedType == typeKeyInit || + detectedType == typeKeyReply || + detectedType == typeSym) { + return { + "type": detectedType.toLowerCase(), + "isGroup": isGroup, + "payload": body.substring(typeStartPos + detectedType.length).trim() + }; + } + return {"type": "plain", "body": rawText}; + } + + final firstSepIdxInSubstring = sepMatch.start; + final firstSepIdxInBody = typeStartPos + firstSepIdxInSubstring; + + // Crucial difference: Keep the absolute raw content without trimming to prevent truncation of trailing Base64 spaces (mangled '+') + final absoluteRawContent = body.substring(firstSepIdxInBody + 1); + final rawContent = absoluteRawContent.trim(); + final sepChar = sepMatch.group(0)!; + final parts = [detectedType, ...rawContent.split(sepChar)]; + + debugPrint( + '[PROTOCOL] Parsed: type=$detectedType, isGroup=$isGroup, sepChar=$sepChar, partsCount=${parts.length}, rawLen=${body.length}'); + if (detectedType == typeSfra) { + debugPrint('[PROTOCOL] Fragment Debug: parts=$parts'); + } + + // Type Handlers + if (detectedType == typeNorm) return {"type": "norm", "isGroup": isGroup}; + + if (detectedType == typeSym) { + // Support both: SYM|payload AND SYM|packetId|payload + if (parts.length >= 3) { + return { + "type": "sym", + "isGroup": isGroup, + "packetId": parts[1].trim(), + "payload": parts.sublist(2).join(sepChar) + }; + } + return {"type": "sym", "isGroup": isGroup, "payload": absoluteRawContent}; + } + + if (detectedType == typeSfra && parts.length >= 4) { + final packetId = parts[1].trim(); + final partNo = int.tryParse(parts[2].trim()) ?? 1; + final totalParts = int.tryParse(parts[3].trim()) ?? 1; + + // Accurate Chunk Extraction: skip exactly 3 delimiters in absoluteRawContent + int dCount = 0; + int chunkStartPos = 0; + for (int i = 0; i < absoluteRawContent.length; i++) { + if (absoluteRawContent[i] == sepChar) { + dCount++; + if (dCount == 3) { + chunkStartPos = i + 1; + break; + } + } + } + + // Preserve suspicious separator noise inside chunks so the crypto layer + // can try repair candidates instead of silently dropping real data. + final String rawChunk = (chunkStartPos > 0) + ? absoluteRawContent.substring(chunkStartPos) + : (parts.length > 4 ? parts.sublist(4).join(sepChar) : ""); + final String chunk = rawChunk.replaceAll(RegExp(r'\s+'), ''); + + return { + "type": "sfra", + "isGroup": isGroup, + "packetId": packetId, + "partNo": partNo, + "totalParts": totalParts, + "chunk": chunk + }; + } + + if (detectedType == typeNack && parts.length >= 3) { + return { + "type": "nack", + "isGroup": isGroup, + "packetId": parts[1], + "missingPart": int.tryParse(parts[2]) ?? 1 + }; + } + + if (detectedType == typeKeyInit) { + return { + "type": "key_init", + "isGroup": isGroup, + "payload": absoluteRawContent + }; + } + if (detectedType == typeKeyReply) { + return { + "type": "key_reply", + "isGroup": isGroup, + "payload": absoluteRawContent + }; + } + if (detectedType == typeAsym) { + if (parts.length >= 3) { + return { + "type": "asym", + "isGroup": isGroup, + "packetId": parts[1].trim(), + "payload": parts.sublist(2).join(sepChar) + }; + } + return { + "type": "asym", + "isGroup": isGroup, + "payload": absoluteRawContent + }; + } + + if (detectedType == typeSym) { + final payload = parts.length > 1 ? parts.sublist(1).join(sepChar) : ""; + return { + "type": "sym", + "isGroup": isGroup, + "payload": payload.replaceAll(RegExp(r'\s+'), '') + }; + } + + if (detectedType == typeAsymFrag) { + final parsedAf = _parseAsymmetricFragmentPayload( + absoluteRawContent, + isGroup: isGroup, + ); + if (parsedAf != null) { + return parsedAf; + } + } + + return {"type": "plain", "body": rawText}; + } +} diff --git a/lib/utils/secure_crypto_helper.dart b/lib/utils/secure_crypto_helper.dart new file mode 100644 index 0000000..4d6ed6c --- /dev/null +++ b/lib/utils/secure_crypto_helper.dart @@ -0,0 +1,490 @@ +import 'dart:convert'; +import 'dart:math'; +import 'package:crypto/crypto.dart' as dart_crypto; +import 'package:cryptography/cryptography.dart'; +import 'package:flutter/foundation.dart'; +import 'package:pointycastle/export.dart' as pc; + +class EccIdentityMaterial { + final String privateKey; + final String publicKey; + final String fingerprint; + + const EccIdentityMaterial({ + required this.privateKey, + required this.publicKey, + required this.fingerprint, + }); +} + +class SecureCryptoHelper { + final _aesGcm = AesGcm.with256bits(); + final _hkdf = Hkdf(hmac: Hmac.sha256(), outputLength: 32); + final _random = Random.secure(); + final pc.ECDomainParameters _ecDomain = pc.ECDomainParameters('secp256r1'); + + static const _variantMap = { + "ك": "ک", + "ي": "ی", + "ى": "ی", + "ة": "ه", + "ە": "ه", + "٠": "0", + "١": "1", + "٢": "2", + "٣": "3", + "٤": "4", + "٥": "5", + "٦": "6", + "٧": "7", + "٨": "8", + "٩": "9", + "۰": "0", + "۱": "1", + "۲": "2", + "۳": "3", + "۴": "4", + "۵": "5", + "۶": "6", + "۷": "7", + "۸": "8", + "۹": "9", + }; + + String _visualSafe(String text) { + String res = text.trim(); + // 1. Remove invisible/zero-width characters (matches Python's _LEGACY_INVISIBLE_CHARS) + res = res.replaceAll(RegExp(r'[\u200c\u200d\u200e\u200f\ufeff]'), ''); + + // 2. Normalize common decomposed (NFD) Persian characters to composite (NFC) legacy fallback + res = res.replaceAll('\u0627\u0653', '\u0622'); // Alif + Madda -> آ + res = res.replaceAll('\u0627\u0654', '\u0623'); // Alif + Hamza -> أ + res = res.replaceAll('\u0627\u0655', '\u0625'); // Alif + Lower Hamza -> إ + res = res.replaceAll('\u0648\u0654', '\u0624'); // Waw + Hamza -> ؤ + res = res.replaceAll('\u064a\u0654', '\u0626'); // Yeh + Hamza (Arabic) -> ئ + res = + res.replaceAll('\u06cc\u0654', '\u0626'); // Yeh + Hamza (Persian) -> ئ + res = res.replaceAll( + '\u0627\u0644\u0644\u0647', 'الله'); // Allah ligature (Standard) + + // 3. Map Arabic variants and digits to Persian/Western standards (matches Python's dict) + _variantMap.forEach((key, value) { + res = res.replaceAll(key, value); + }); + + // 4. Aggressive cleanup of invisible characters (Matches Python's _LEGACY_INVISIBLE_CHARS) + res = res.replaceAll(RegExp(r'[\u200c\u200d\u200e\u200f\ufeff]'), ''); + + // NOTE: We DO NOT remove Harakats (diacritics) here because Python's NFC normalization + // preserves them. We only map letter/digit variants. + + return res; + } + + String b64uEncode(List bytes) { + return base64UrlEncode(bytes).replaceAll('=', ''); + } + + List b64uDecode(String value) { + // 1. Strip transport prefixes if present + String input = value.trim(); + if (input.startsWith('b1:')) { + input = input.substring(3); + } + + // 2. Log illegal characters for diagnostics + final illegalChars = input.replaceAll(RegExp(r'[A-Za-z0-9+/=\s\-_]'), ''); + if (illegalChars.isNotEmpty) { + debugPrint('[CRYPTO] Found illegal chars in Base64: "$illegalChars"'); + } + + // 3. Aggressive cleaning - ALLOW | ; ! as they might be mangled separators/chars + String clean = input.replaceAll(RegExp(r'[^A-Za-z0-9+/=\s\-_|;!]'), ''); + + // 4. Map standard mangles (Parity with Python's _repair_base64) + clean = clean.replaceAll(' ', '+'); + clean = + clean.replaceAll('|', '/').replaceAll(';', '/').replaceAll('!', '/'); + + // 4. Parity with Python: translate URL-safe to Standard before decoding + clean = clean.replaceAll('-', '+').replaceAll('_', '/'); + + // 5. Handle padding: discard all '=' to recalculate from scratch based on data bits + clean = clean.split('=')[0]; + + // 6. Critical: Final cleanup from non-alphabet symbols after mapping/split + clean = clean.replaceAll(RegExp(r'[^A-Za-z0-9+/]'), ''); + + // 7. Base64 length validation logic + if (clean.length % 4 == 1) { + debugPrint( + '[CRYPTO] Base64 Critical Failure: len ${clean.length} % 4 == 1. Prefix: ${clean.substring(0, min(10, clean.length))}'); + return []; + } + + final missingPadding = (4 - (clean.length % 4)) % 4; + final padded = clean + ('=' * missingPadding); + + try { + return base64.decode(padded); + } catch (e) { + debugPrint('[CRYPTO] Base64 Final Decode Error: $e'); + return []; + } + } + + String hexEncode(List bytes) { + return bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(); + } + + List hexDecode(String value) { + String input = value.trim(); + if (input.startsWith('h1:')) { + input = input.substring(3); + } + final clean = input.replaceAll(RegExp(r'[^0-9A-Fa-f]'), ''); + final evenLength = clean.length - (clean.length % 2); + final normalized = clean.substring(0, evenLength); + return List.generate( + normalized.length ~/ 2, + (i) => int.parse(normalized.substring(i * 2, i * 2 + 2), radix: 16), + ); + } + + List decodeTransportPayload(String value) { + if (value.startsWith('h1:')) { + return hexDecode(value.substring(3)); + } + if (value.startsWith('b1:')) { + return b64uDecode(value.substring(3)); + } + return b64uDecode(value); + } + + Future encryptSymmetric(String message, String password) async { + final normKeyText = _visualSafe(password); + final digest = dart_crypto.sha256.convert(utf8.encode(normKeyText)); + final keyBytes = Uint8List.fromList(digest.bytes); + + final nonce = _aesGcm.newNonce(); + final secretBox = await _aesGcm.encrypt( + utf8.encode(message), + secretKey: SecretKey(keyBytes), + nonce: nonce, + ); + + final combined = Uint8List.fromList([ + ...secretBox.nonce, + ...secretBox.cipherText, + ...secretBox.mac.bytes, + ]); + + return 'b1:${b64uEncode(combined)}'; + } + + Future decryptSymmetric(String payload, String password) async { + try { + final raw = decodeTransportPayload(payload); + final keyVariants = [ + {'label': 'visual_safe', 'text': _visualSafe(password)}, + {'label': 'raw', 'text': password.trim()}, + ]; + + if (raw.length < 28) { + debugPrint('[CRYPTO] Symmetric decryption failed: payload too short.'); + return null; + } + + final nonce = raw.sublist(0, 12); + final ciphertextWithTag = raw.sublist(12); + final ciphertext = + ciphertextWithTag.sublist(0, ciphertextWithTag.length - 16); + final mac = ciphertextWithTag.sublist(ciphertextWithTag.length - 16); + + for (final variant in keyVariants) { + final label = variant['label']!; + final keyText = variant['text']!; + final digest = dart_crypto.sha256.convert(utf8.encode(keyText)); + final keyBytes = Uint8List.fromList(digest.bytes); + + debugPrint('[CRYPTO] Trying symmetric decryption variant "$label".'); + + try { + final secretBox = SecretBox( + ciphertext, + nonce: nonce, + mac: Mac(mac), + ); + + final decryptedBytes = await _aesGcm.decrypt( + secretBox, + secretKey: SecretKey(keyBytes), + ); + + debugPrint( + '[CRYPTO] Symmetric decryption succeeded via variant "$label".'); + try { + return utf8.decode(decryptedBytes); + } catch (e) { + debugPrint('[CRYPTO] UTF-8 decode failed after decryption.'); + return '[UTF-8 Decode Error]'; + } + } catch (e) { + debugPrint('[CRYPTO] Symmetric decryption variant "$label" failed.'); + } + } + + debugPrint('[CRYPTO] All symmetric decryption variants failed.'); + return null; + } catch (e) { + debugPrint('[CRYPTO] Symmetric decryption error: $e'); + return null; + } + } + + String fingerprintFromPublicBytes(List publicBytes) { + final digest = + dart_crypto.sha256.convert(publicBytes).toString().toUpperCase(); + final parts = []; + for (var i = 0; i < digest.length; i += 4) { + parts.add(digest.substring(i, i + 4)); + } + return parts.join(' '); + } + + List _normalizeP256Coordinate(List value) { + if (value.length == 32) return List.from(value); + if (value.length == 33 && value.first == 0) { + return value.sublist(1); + } + if (value.length < 32) { + return List.filled(32 - value.length, 0) + value; + } + return value.sublist(value.length - 32); + } + + pc.SecureRandom _newSecureRandom() { + final seed = Uint8List.fromList( + List.generate(32, (_) => _random.nextInt(256)), + ); + return pc.FortunaRandom()..seed(pc.KeyParameter(seed)); + } + + BigInt _bytesToBigInt(List bytes) { + var result = BigInt.zero; + for (final byte in bytes) { + result = (result << 8) | BigInt.from(byte); + } + return result; + } + + List _bigIntToBytes(BigInt value) { + if (value == BigInt.zero) { + return [0]; + } + final result = []; + var current = value; + while (current > BigInt.zero) { + result.insert(0, (current & BigInt.from(0xff)).toInt()); + current = current >> 8; + } + return result; + } + + String publicKeyTransport(String value) { + final publicBytes = decodePublicKey(value); + return 'b1:${b64uEncode(publicBytes)}'; + } + + Future generateIdentity() async { + final params = pc.ParametersWithRandom( + pc.ECKeyGeneratorParameters(_ecDomain), + _newSecureRandom(), + ); + final generator = pc.KeyGenerator('EC')..init(params); + final keyPair = generator.generateKeyPair(); + final privateKey = keyPair.privateKey as pc.ECPrivateKey; + final publicKey = keyPair.publicKey as pc.ECPublicKey; + final privateBytes = Uint8List.fromList( + _normalizeP256Coordinate(_bigIntToBytes(privateKey.d!)), + ); + final publicBytes = Uint8List.fromList([ + ..._normalizeP256Coordinate( + _bigIntToBytes(publicKey.Q!.x!.toBigInteger()!), + ), + ..._normalizeP256Coordinate( + _bigIntToBytes(publicKey.Q!.y!.toBigInteger()!), + ), + ]); + return EccIdentityMaterial( + privateKey: b64uEncode(privateBytes), + publicKey: b64uEncode(publicBytes), + fingerprint: fingerprintFromPublicBytes(publicBytes), + ); + } + + List decodePublicKey(String value) { + try { + final String input = value.startsWith('h1:') || value.startsWith('b1:') + ? value.substring(3) + : value; + + final raw = b64uDecode(input); + if (raw.isNotEmpty) { + if (raw.length == 65 && raw.first == 4) { + return raw.sublist(1); + } + if (raw.length == 64) { + return raw; + } + } + throw StateError( + 'P-256 public key length must be 64 bytes (got ${raw.length}).'); + } catch (e) { + debugPrint('Public key decode error for value "$value": $e'); + rethrow; + } + } + + Future> deriveSharedKey({ + required String privateKey, + required String localPublicKey, + required String publicKey, + }) async { + final privateBytes = b64uDecode(privateKey); + final publicBytes = decodePublicKey(publicKey); + if (privateBytes.length != 32) { + throw StateError('P-256 private key must contain 32 bytes.'); + } + final peerX = publicBytes.sublist(0, 32); + final peerY = publicBytes.sublist(32, 64); + final localPublicBytes = decodePublicKey(localPublicKey); + if (localPublicBytes.length != 64) { + throw StateError('Local P-256 public key must contain 64 bytes.'); + } + + final agreement = pc.ECDHBasicAgreement() + ..init( + pc.ECPrivateKey( + _bytesToBigInt(privateBytes), + _ecDomain, + ), + ); + final sharedPoint = pc.ECPublicKey( + _ecDomain.curve.createPoint( + _bytesToBigInt(peerX), + _bytesToBigInt(peerY), + ), + _ecDomain, + ); + final sharedValue = agreement.calculateAgreement(sharedPoint); + final sharedBytes = Uint8List.fromList( + _normalizeP256Coordinate(_bigIntToBytes(sharedValue)), + ); + final derived = await _hkdf.deriveKey( + secretKey: SecretKey(sharedBytes), + nonce: utf8.encode('SABA:ECDH:P256:HKDF:v1'), + info: utf8.encode('SABA:ECDH:P256:AES-256-GCM'), + ); + final finalKey = await derived.extractBytes(); + return finalKey; + } + + Future encryptWithSharedKey( + String message, List sharedKey) async { + final nonce = _aesGcm.newNonce(); + final secretBox = await _aesGcm.encrypt( + utf8.encode(message), + secretKey: SecretKey(sharedKey), + nonce: nonce, + ); + final combined = [ + ...secretBox.nonce, + ...secretBox.cipherText, + ...secretBox.mac.bytes, + ]; + return b64uEncode(combined); + } + + Future decryptWithSharedKey( + String payload, List sharedKey) async { + try { + final raw = b64uDecode(payload); + if (raw.length < 28) return null; + + final nonce = raw.sublist(0, 12); + final ciphertextWithTag = raw.sublist(12); + final ciphertext = + ciphertextWithTag.sublist(0, ciphertextWithTag.length - 16); + final mac = ciphertextWithTag.sublist(ciphertextWithTag.length - 16); + + try { + final secretBox = SecretBox( + ciphertext, + nonce: nonce, + mac: Mac(mac), + ); + + final plain = + await _aesGcm.decrypt(secretBox, secretKey: SecretKey(sharedKey)); + return utf8.decode(plain); + } catch (e) { + debugPrint('[CRYPTO] Asymmetric decryption failed: $e'); + return null; + } + } catch (e) { + debugPrint('Asymmetric payload decryption error: $e'); + return null; + } + } + + List randomBytes(int length) { + return List.generate(length, (_) => _random.nextInt(256)); + } + + Future encryptStorageText(String value, List keyBytes) async { + final nonce = _aesGcm.newNonce(); + final secretBox = await _aesGcm.encrypt( + utf8.encode(value), + secretKey: SecretKey(keyBytes), + nonce: nonce, + ); + return 'enc1:${b64uEncode([ + ...secretBox.nonce, + ...secretBox.cipherText, + ...secretBox.mac.bytes, + ])}'; + } + + Future decryptStorageText(String? value, List keyBytes) async { + if (value == null || value.isEmpty) return value; + if (!value.startsWith('enc1:')) return value; + + try { + final raw = b64uDecode(value.substring(5)); + if (raw.length < 28) { + return null; + } + + final nonce = raw.sublist(0, 12); + final ciphertextWithTag = raw.sublist(12); + final ciphertext = + ciphertextWithTag.sublist(0, ciphertextWithTag.length - 16); + final mac = ciphertextWithTag.sublist(ciphertextWithTag.length - 16); + + final secretBox = SecretBox( + ciphertext, + nonce: nonce, + mac: Mac(mac), + ); + final plain = await _aesGcm.decrypt( + secretBox, + secretKey: SecretKey(keyBytes), + ); + return utf8.decode(plain); + } catch (e) { + debugPrint('Storage payload decryption error: $e'); + return null; + } + } +} diff --git a/lib/utils/secure_messaging_service.dart b/lib/utils/secure_messaging_service.dart new file mode 100644 index 0000000..f2070db --- /dev/null +++ b/lib/utils/secure_messaging_service.dart @@ -0,0 +1,1198 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:another_telephony/telephony.dart'; +import 'package:flutter/foundation.dart'; + +import 'contact_helper.dart'; +import 'database_helper.dart'; +import 'notification_helper.dart'; +import 'protocol_helper.dart'; +import 'secure_crypto_helper.dart'; + +class SecureMessagingService { + static final SecureMessagingService instance = SecureMessagingService._init(); + final _crypto = SecureCryptoHelper(); + final _db = DatabaseHelper.instance; + final _telephony = Telephony.instance; + + static const int maxTextLimit = 5000; + static const int fragmentTimeoutMs = 45 * 60 * 1000; + static const int fragmentRetentionMs = 7 * 24 * 60 * 60 * 1000; + + final _messageStreamController = + StreamController>.broadcast(); + + Stream> get messageStream => + _messageStreamController.stream; + + final Set _activeOutgoingPacketIds = {}; + + String? currentChatPhone; + bool _isInitialized = false; + bool _listenerRegistered = false; + + SecureMessagingService._init(); + + Future init() async { + if (_isInitialized) return; + await NotificationHelper.instance.init(); + await _ensureIdentity(); + await _ensureInstallDate(); + if (!_listenerRegistered) { + _setupGlobalListener(); + _listenerRegistered = true; + } + _isInitialized = true; + } + + Future resetForFreshInstall() async { + currentChatPhone = null; + _isInitialized = false; + await _db.resetAppData(); + } + + Future getInstallDate() async { + final val = await _db.getSetting('install_date'); + if (val == null) return null; + return int.tryParse(val); + } + + Future _ensureInstallDate() async { + final existing = await _db.getSetting('install_date'); + if (existing == null) { + final now = DateTime.now().millisecondsSinceEpoch.toString(); + await _db.setSetting('install_date', now); + } + } + + Future _ensureIdentity() async { + final existing = await _db.getIdentity(); + if (existing != null) { + try { + final privateBytes = _crypto.b64uDecode(existing['privateKey']!); + if (privateBytes.length != 32) { + throw StateError( + 'Local P-256 private key must contain 32 bytes.', + ); + } + final publicBytes = _crypto.decodePublicKey(existing['publicKey']!); + if (publicBytes.length != 64) { + throw StateError( + 'Local P-256 public key must contain 64 bytes.', + ); + } + return; + } catch (e) { + debugPrint('[ECC] Local identity is invalid; regenerating. $e'); + } + } + final identity = await _crypto.generateIdentity(); + await _db.saveIdentity( + privateKey: identity.privateKey, + publicKey: identity.publicKey, + fingerprint: identity.fingerprint, + ); + } + + void _setupGlobalListener() { + _telephony.listenIncomingSms( + onNewMessage: _handleOnNewMessage, + onBackgroundMessage: backgroundMessageHandler, + listenInBackground: true, + ); + } + + static void _handleOnNewMessage(SmsMessage message) { + instance._processAndBroadcast(message); + } + + String? _packetModeForType(String type) { + switch (type) { + case 'sym': + case 'sfra': + return 'SYM'; + case 'asym': + case 'afrag': + return 'AE'; + default: + return null; + } + } + + bool _isControlProtocolType(String type) { + return type == 'key_init' || type == 'key_reply' || type == 'norm'; + } + + Map _buildStreamEvent( + String phone, + String originalBody, + String? processedBody, { + bool isMe = false, + required int date, + }) { + final parsed = ProtocolHelper.parseMessage(originalBody); + final type = parsed['type'] as String? ?? 'plain'; + final packetId = parsed['packetId'] as String?; + final packetMode = _packetModeForType(type); + final effectiveBody = processedBody ?? originalBody; + final isMultipartPending = packetId != null && + packetMode != null && + effectiveBody.contains('در حال'); + final isMultipartComplete = packetId != null && + packetMode != null && + !isMultipartPending && + effectiveBody != originalBody && + effectiveBody != 'REFRESH'; + + return { + 'phone': phone, + 'body': effectiveBody, + 'originalBody': originalBody, + 'packetId': packetId, + 'packetMode': packetMode, + 'date': date, + 'isMultipartPending': isMultipartPending, + 'isMultipartComplete': isMultipartComplete, + 'isMe': isMe, + }; + } + + Future _processAndBroadcast(SmsMessage message) async { + final phone = ContactHelper.normalizePhone(message.address ?? ""); + final body = message.body ?? ""; + final parsed = ProtocolHelper.parseMessage(body); + final type = parsed['type'] as String? ?? 'plain'; + final packetId = parsed['packetId'] as String?; + final packetMode = _packetModeForType(type); + final isControlProtocol = _isControlProtocolType(type); + + // Persist to local cache immediately so it survives screen re-entry (loadMessages) + final savedId = await _db.saveSingleSmsToCache({ + 'sms_id': message.id, + 'address': phone, + 'body': body, + 'date': message.date ?? DateTime.now().millisecondsSinceEpoch, + 'type': 1, // Received + 'is_me': 0, + 'is_read': ((currentChatPhone == phone) || isControlProtocol) + ? 1 + : 0, // Control protocol messages never count as unread + 'is_secure': type != 'plain' ? 1 : 0, + 'packet_id': packetId, + 'packet_mode': packetMode, + }); + + // Always attempt to process (handle fragments, decryption, etc.) + final processedBody = await processIncomingSms(phone, body); + + if (processedBody != null && + processedBody != body && + processedBody != 'REFRESH' && + savedId > 0) { + // Update the cache with the decrypted/processed version and mark as secure + await _db.updateSmsBody(savedId, processedBody, + isSecure: 1, packetId: packetId, packetMode: packetMode); + } + + if (isControlProtocol) { + _messageStreamController.add({'phone': phone, 'body': 'REFRESH'}); + return; + } + + // If the message is an echo and we couldn't process it further than the raw string, + // skip broadcasting to avoid UI flickering (e.g. replacing plain text with raw protocol strings). + final isMeEcho = (message.type == SmsType.MESSAGE_TYPE_SENT) || + (packetId != null && _activeOutgoingPacketIds.contains(packetId)); + if (processedBody == null && isMeEcho) { + return; + } + + final event = _buildStreamEvent( + phone, + body, + processedBody, + isMe: isMeEcho, + date: message.date ?? DateTime.now().millisecondsSinceEpoch, + ); + + // Broadcast to the stream so the UI can react immediately + _messageStreamController.add(event); + + // Handle notifications if the chat is not currently open for this contact + if (currentChatPhone != phone) { + final name = ContactHelper.getName(phone); + final notificationBody = + (processedBody != null) ? (event['body'] as String) : body; + + await NotificationHelper.instance.showNotification( + id: phone.hashCode, + title: name, + body: notificationBody, + payload: phone, + ); + } + } + + Future isAsymmetricReady(String phone) async { + final contact = await _db.getContact(phone); + final secureState = contact?['secure_state'] as String? ?? 'none'; + final verificationState = + contact?['verification_state'] as String? ?? 'unverified'; + return (contact?['ecc_shared_key'] as String?)?.isNotEmpty == true && + (contact?['peer_public_key'] as String?)?.isNotEmpty == true && + secureState == 'ready' && + verificationState == 'verified'; + } + + Future?> getSecurityContext(String phone) async { + await _ensureIdentity(); + final identity = await _db.getIdentity(); + final contact = await _db.getContact(phone); + if (identity == null) return null; + return { + 'localFingerprint': identity['fingerprint'], + 'peerFingerprint': contact?['peer_fingerprint'], + 'secureState': contact?['secure_state'] ?? 'none', + 'verificationState': contact?['verification_state'] ?? 'unverified', + 'mode': contact?['mode'] ?? 'normal', + 'hasPeerKey': + (contact?['peer_public_key'] as String?)?.isNotEmpty == true, + }; + } + + Future resetAsymmetricSecurity(String phone) async { + final normalizedPhone = ContactHelper.normalizePhone(phone); + await _db.resetAsymmetricSecurity(normalizedPhone); + _messageStreamController.add({'phone': normalizedPhone, 'body': 'REFRESH'}); + } + + Future>> getPendingPacketsForPhone(String phone) { + return _db.getPendingPacketsForPhone(phone); + } + + Future cleanupFragmentBuffer(String phone) async { + final retentionCutoff = + DateTime.now().millisecondsSinceEpoch - fragmentRetentionMs; + await _db.clearCompletedPackets(phone); + await _db.clearStalePendingPackets( + phone, + olderThanMs: retentionCutoff, + ); + } + + Future markFingerprintVerified(String phone) async { + final normalizedPhone = ContactHelper.normalizePhone(phone); + final contact = await _db.getContact(normalizedPhone); + final hasAsymmetricMaterial = + (contact?['ecc_shared_key'] as String?)?.isNotEmpty == true && + (contact?['peer_public_key'] as String?)?.isNotEmpty == true; + await _db.updateContactSecurity( + normalizedPhone, + verificationState: 'verified', + verifiedAt: DateTime.now().millisecondsSinceEpoch, + state: hasAsymmetricMaterial + ? 'ready' + : (contact?['secure_state'] as String?), + mode: hasAsymmetricMaterial ? 'asymmetric' : null, + ); + _messageStreamController.add({'phone': normalizedPhone, 'body': 'REFRESH'}); + } + + Future> startAsymmetricHandshake(String phone) async { + await _ensureIdentity(); + final normalizedPhone = ContactHelper.normalizePhone(phone); + final identity = await _db.getIdentity(); + if (identity == null) { + throw StateError('Identity is not available.'); + } + + await _db.updateContactSecurity( + normalizedPhone, + state: 'handshake_pending', + mode: 'asymmetric', + ); + final publicKeyTransport = + _crypto.publicKeyTransport(identity['publicKey']!); + await _telephony.sendSms( + to: normalizedPhone, + message: ProtocolHelper.buildKeyInit(publicKeyTransport), + ); + _messageStreamController.add({'phone': normalizedPhone, 'body': 'REFRESH'}); + return { + 'sentText': false, + 'notice': 'در حال تبادل کلید عمومی...', + }; + } + + Future> sendMessage( + String phone, + String text, { + required String securityLevel, + String? symmetricKey, + String? forcedPacketId, + int? localTimestamp, + }) async { + final normalizedPhone = ContactHelper.normalizePhone(phone); + final messageTimestamp = + localTimestamp ?? DateTime.now().millisecondsSinceEpoch; + if (text.length > maxTextLimit) { + throw "طول پیام نباید بیشتر از $maxTextLimit کاراکتر باشد."; + } + + if (securityLevel == 'normal') { + await _telephony.sendSms(to: normalizedPhone, message: text); + await _db.saveSingleSmsToCache({ + 'address': normalizedPhone, + 'body': text, + 'date': messageTimestamp, + 'type': 2, + 'is_me': 1, + }); + return {'sentText': true, 'notice': 'sent'}; + } + + if (securityLevel == 'symmetric') { + final effectiveKey = (symmetricKey ?? '').trim(); + if (effectiveKey.isEmpty) { + return { + 'sentText': false, + 'notice': 'کلید متقارن برای این مخاطب تنظیم نشده است.' + }; + } + await _db.updateContactSecurity( + normalizedPhone, + symmetricKey: effectiveKey, + mode: 'symmetric', + state: 'ready', + ); + final encrypted = await _crypto.encryptSymmetric(text, effectiveKey); + final cleanEncrypted = encrypted.replaceAll(RegExp(r'\s+'), ''); + await _db.saveDecrypted( + cleanEncrypted, text); // Cache for instant recovery + final protocolMsg = ProtocolHelper.buildSymmetricMsg(encrypted); + if (protocolMsg.length <= ProtocolHelper.maxSmsChars) { + await _telephony.sendSms(to: normalizedPhone, message: protocolMsg); + + // Cache immediately to prevent disappearing bubble during UI refreshes + await _db.saveSingleSmsToCache({ + 'address': normalizedPhone, + 'body': protocolMsg, + 'date': messageTimestamp, + 'type': 2, // Sent + 'is_me': 1, + 'is_secure': 1, + 'packet_id': forcedPacketId, + 'packet_mode': 'SYM', + }); + + return { + 'sentText': true, + 'notice': 'sent', + 'packetId': forcedPacketId, + 'packetMode': 'SYM', + }; + } + final packetId = await _sendLegacyFragmented(normalizedPhone, encrypted, + forcedPacketId: forcedPacketId); + return { + 'sentText': true, + 'notice': 'sent_fragmented', + 'packetId': packetId, + 'packetMode': 'SYM', + }; + } + + final contact = await _db.getContact(normalizedPhone); + final secureState = contact?['secure_state'] as String? ?? 'none'; + final verificationState = + contact?['verification_state'] as String? ?? 'unverified'; + final hasPeerKey = + (contact?['peer_public_key'] as String?)?.isNotEmpty == true; + final sharedKeyEncoded = contact?['ecc_shared_key'] as String?; + final hasSharedKey = (sharedKeyEncoded?.isNotEmpty ?? false); + + if (!await isAsymmetricReady(normalizedPhone)) { + if (verificationState == 'changed') { + return { + 'sentText': false, + 'notice': + 'کلید مخاطب تغییر کرده است؛ ابتدا اثر انگشت جدید را دوباره تایید کنید.', + }; + } + if (hasPeerKey && hasSharedKey) { + return { + 'sentText': false, + 'notice': + 'کلید مخاطب دریافت شده اما هنوز تایید نشده است؛ ابتدا اثر انگشت را تطبیق و تایید کنید.', + }; + } + if (secureState == 'handshake_pending') { + return { + 'sentText': false, + 'notice': 'تبادل کلید هنوز کامل نشده است.', + }; + } + return startAsymmetricHandshake(normalizedPhone); + } + + if (verificationState == 'changed') { + return { + 'sentText': false, + 'notice': + 'کلید مخاطب تغییر کرده است؛ ابتدا اثر انگشت جدید را دوباره تایید کنید.', + }; + } + if (sharedKeyEncoded == null || sharedKeyEncoded.isEmpty) { + return startAsymmetricHandshake(normalizedPhone); + } + final sharedKey = _crypto.b64uDecode(sharedKeyEncoded); + final encrypted = await _crypto.encryptWithSharedKey(text, sharedKey); + final cleanEncrypted = encrypted.replaceAll(RegExp(r'\s+'), ''); + await _db.saveDecrypted(cleanEncrypted, text); // Cache for instant recovery + final frames = + ProtocolHelper.buildAsymmetricFrames(_crypto.b64uDecode(encrypted)); + + final fullProtocolBody = ProtocolHelper.buildAsymmetricMsg(encrypted); + if (frames.length == 1) { + await _db.saveSingleSmsToCache({ + 'address': normalizedPhone, + 'body': fullProtocolBody, + 'date': messageTimestamp, + 'type': 2, + 'is_me': 1, + 'is_secure': 1, + 'packet_id': forcedPacketId, + 'packet_mode': 'AE', + }); + } + + final packetId = await _sendFrames(normalizedPhone, frames, + securePrefix: 'ECC', forcedPacketId: forcedPacketId); + await _db.updateContactSecurity(normalizedPhone, + mode: 'asymmetric', state: 'ready'); + return { + 'sentText': true, + 'notice': frames.length > 1 ? 'sent_fragmented' : 'sent', + 'packetId': packetId, + 'packetMode': 'AE', + 'protocolBody': fullProtocolBody, + 'encryptedPayload': cleanEncrypted, + }; + } + + Future sendSecureMessage(String phone, String text, + {String? symmetricKey}) async { + await sendMessage( + phone, + text, + securityLevel: symmetricKey != null && symmetricKey.trim().isNotEmpty + ? 'symmetric' + : 'normal', + symmetricKey: symmetricKey, + ); + } + + Future getEncryptedPreview(String text, String symmetricKey) async { + final encrypted = await _crypto.encryptSymmetric(text, symmetricKey); + return ProtocolHelper.buildSymmetricMsg(encrypted); + } + + Future _sendFrames(String phone, List frames, + {required String securePrefix, String? forcedPacketId}) async { + final packetId = forcedPacketId ?? + Random().nextInt(0xFFFFFFFF).toRadixString(16).padLeft(10, '0'); + + if (frames.length > 1) { + _activeOutgoingPacketIds.add(packetId); + } + + for (var i = 0; i < frames.length; i++) { + await _telephony.sendSms(to: phone, message: frames[i]); + if (frames.length > 1) { + final parsed = ProtocolHelper.parseMessage(frames[i]); + await _db.saveFragment( + phone, + parsed['packetId'] ?? packetId, + parsed['partNo'] ?? (i + 1), + parsed['totalParts'] ?? frames.length, + parsed['chunk'] ?? frames[i], + packetMode: 'AE', + isMe: true, + ); + _messageStreamController.add({ + 'phone': phone, + 'body': + '$securePrefix در حال ارسال بخش ${i + 1} از ${frames.length}...', + 'originalBody': 'SFRA_PART', + 'packetId': parsed['packetId'] ?? packetId, + 'packetMode': 'AE', + 'isMultipartPending': true, + 'isMultipartComplete': false, + 'receivedParts': i + 1, + 'totalParts': frames.length, + 'isMe': true, + }); + await Future.delayed(const Duration(milliseconds: 2200)); + } + } + + if (frames.length > 1) { + // Keep it for a bit longer to catch late echoes, then remove + Future.delayed(const Duration(seconds: 10), () { + _activeOutgoingPacketIds.remove(packetId); + }); + } + + _messageStreamController.add({'phone': phone, 'body': 'REFRESH'}); + return frames.length > 1 ? packetId : null; + } + + Future _sendLegacyFragmented(String phone, String encryptedPayload, + {bool isGroup = false, String? forcedPacketId}) async { + final packetId = forcedPacketId ?? + Random().nextInt(0xFFFFFFFF).toRadixString(16).padLeft(10, '0'); + const chunkSize = 90; + final total = (encryptedPayload.length / chunkSize).ceil(); + _activeOutgoingPacketIds.add(packetId); + + try { + for (var i = 0; i < total; i++) { + final start = i * chunkSize; + final end = min(start + chunkSize, encryptedPayload.length); + final chunk = encryptedPayload.substring(start, end); + final frame = isGroup + ? ('${ProtocolHelper.gPrefix}${ProtocolHelper.typeSfra}|$packetId|${i + 1}|$total|$chunk') + : ProtocolHelper.buildSymmetricFrag(packetId, i + 1, total, chunk); + await _telephony.sendSms(to: phone, message: frame); + await _db.saveFragment(phone, packetId, i + 1, total, chunk, + packetMode: 'SYM', isMe: true); + + _messageStreamController.add({ + 'phone': phone, + 'body': 'در حال ارسال بخش ${i + 1} از $total...', + 'originalBody': 'SFRA_PART', + 'packetId': packetId, + 'packetMode': 'SYM', + 'isMultipartPending': true, + 'isMultipartComplete': false, + 'receivedParts': i + 1, + 'totalParts': total, + 'isMe': true, + }); + // Reduce delay from 2200ms to 1200ms for better UX + await Future.delayed(const Duration(milliseconds: 1200)); + } + } finally { + Future.delayed(const Duration(seconds: 10), () { + _activeOutgoingPacketIds.remove(packetId); + }); + } + + _messageStreamController.add({'phone': phone, 'body': 'REFRESH'}); + return total > 1 ? packetId : null; + } + + Future resolvePayloadForRetry( + String rawMessage, { + String? phone, + String? hintedPayload, + }) async { + if (hintedPayload != null && hintedPayload.trim().isNotEmpty) { + return hintedPayload.trim(); + } + + final parsed = ProtocolHelper.parseMessage(rawMessage); + final directPayload = parsed['payload'] as String?; + if (directPayload != null && directPayload.trim().isNotEmpty) { + return directPayload.trim(); + } + + final type = parsed['type'] as String? ?? 'plain'; + final packetId = parsed['packetId'] as String?; + if ((type != 'sfra' && type != 'afrag') || + packetId == null || + phone == null) { + return rawMessage.trim().isEmpty ? null : rawMessage.trim(); + } + + final fragments = await _db.getFragments(phone, packetId); + if (fragments.isEmpty) { + final chunk = parsed['chunk'] as String?; + return chunk?.trim().isEmpty == false ? chunk!.trim() : null; + } + + final sorted = List>.from(fragments) + ..sort( + (a, b) => (a['frag_index'] as int).compareTo(b['frag_index'] as int)); + + if (type == 'sfra') { + return sorted + .map((fragment) => (fragment['body'] as String?) ?? '') + .join() + .trim(); + } + + final payloadBytes = []; + for (final fragment in sorted) { + final chunk = fragment['body'] as String? ?? ''; + if (chunk.isEmpty) continue; + payloadBytes.addAll(_crypto.b64uDecode(chunk)); + } + return payloadBytes.isEmpty ? null : _crypto.b64uEncode(payloadBytes); + } + + Future decryptWithKey( + String rawMessage, + String key, { + String? phone, + String? hintedPayload, + }) async { + final actualPayload = await resolvePayloadForRetry( + rawMessage, + phone: phone, + hintedPayload: hintedPayload, + ); + if (actualPayload == null || actualPayload.isEmpty) { + return null; + } + + final decrypted = await _crypto.decryptSymmetric(actualPayload, key); + if (decrypted != null) { + await _db.saveDecrypted(actualPayload, decrypted); + } + return decrypted; + } + + Future processIncomingSms( + String phone, + String body, { + bool broadcast = true, + bool isMe = false, + bool isScan = false, + }) async { + await _ensureIdentity(); + final parsed = ProtocolHelper.parseMessage(body); + final type = parsed['type']; + final packetId = parsed['packetId'] as String?; + + // If we are currently sending this packet, this "incoming" SMS is likely an echo of our own sent message + bool effectiveIsMe = isMe; + if (!effectiveIsMe && + packetId != null && + _activeOutgoingPacketIds.contains(packetId)) { + effectiveIsMe = true; + } + + debugPrint( + '[CRYPTO] Incoming SMS from $phone: type=$type, isMe=$effectiveIsMe, packetId=$packetId'); + + if (type == 'plain') return body; + if (parsed['isGroup'] == true) { + if (type == 'sfra') { + return _handleLegacyFrag(phone, parsed, + broadcast: broadcast, isMe: effectiveIsMe, isScan: isScan); + } + return _handleGroupMsg(phone, body, type, parsed, isMe: effectiveIsMe); + } + + switch (type) { + case 'norm': + return 'بازگشت به حالت عادی برای این گفتگو دریافت شد.'; + case 'sym': + return _handleSymmetricMsg(phone, parsed['payload'], + isMe: effectiveIsMe); + case 'sfra': + return _handleLegacyFrag(phone, parsed, + broadcast: broadcast, isMe: effectiveIsMe, isScan: isScan); + case 'key_init': + await _handleKeyExchange(phone, parsed['payload'], shouldReply: true); + return null; + case 'key_reply': + await _handleKeyExchange(phone, parsed['payload'], shouldReply: false); + return null; + case 'asym': + return _handleAsymmetricMsg(phone, parsed['payload'], + isMe: effectiveIsMe); + case 'afrag': + return _handleAsymmetricFrag(phone, parsed, + broadcast: broadcast, isMe: effectiveIsMe, isScan: isScan); + default: + return body; + } + } + + Future _handleKeyExchange(String phone, String peerPublicKey, + {required bool shouldReply}) async { + try { + final identity = await _db.getIdentity(); + if (identity == null) return; + final contact = await _db.getContact(phone); + final secureState = contact?['secure_state'] as String? ?? 'none'; + if (!shouldReply && secureState != 'handshake_pending') { + debugPrint('[ECC] Ignoring unexpected key reply for $phone.'); + return; + } + final existingPublicKey = contact?['peer_public_key'] as String?; + String verificationState = + contact?['verification_state'] as String? ?? 'unverified'; + if (existingPublicKey != null && + existingPublicKey.isNotEmpty && + existingPublicKey != peerPublicKey) { + verificationState = 'changed'; + } else if (verificationState != 'verified') { + verificationState = 'unverified'; + } + + final sharedKey = await _crypto.deriveSharedKey( + privateKey: identity['privateKey']!, + localPublicKey: identity['publicKey']!, + publicKey: peerPublicKey, + ); + final peerPublicBytes = _crypto.decodePublicKey(peerPublicKey); + final nextSecureState = + verificationState == 'verified' ? 'ready' : 'pending_verification'; + + await _db.updateContactSecurity( + phone, + publicKey: peerPublicKey, + peerFingerprint: _crypto.fingerprintFromPublicBytes(peerPublicBytes), + eccSharedKey: _crypto.b64uEncode(sharedKey), + state: nextSecureState, + mode: 'asymmetric', + verificationState: verificationState, + ); + + if (shouldReply) { + final publicKeyTransport = + _crypto.publicKeyTransport(identity['publicKey']!); + await _telephony.sendSms( + to: phone, + message: ProtocolHelper.buildKeyReply(publicKeyTransport)); + } + _messageStreamController.add({'phone': phone, 'body': 'REFRESH'}); + } catch (e) { + debugPrint('Key exchange failed for $phone: $e'); + await _db.updateContactSecurity( + phone, + state: 'handshake_failed', + mode: 'asymmetric', + ); + _messageStreamController.add({'phone': phone, 'body': 'REFRESH'}); + } + } + + Future _handleSymmetricMsg(String phone, String payload, + {String? symmetricKey, bool isMe = false}) async { + final cleanPayload = payload.replaceAll(RegExp(r'\s+'), ''); + final cached = await _db.getDecrypted(cleanPayload); + if (cached != null) return cached; + + final contact = await _db.getContact(phone); + final savedKey = symmetricKey ?? contact?['symmetric_key'] as String?; + if (savedKey == null || savedKey.isEmpty) { + if (isMe) return null; // Don't show "Locked" for our own echoed message + final label = isMe ? 'ارسال شده' : 'دریافت شد'; + return 'پیام امن متقارن $label. برای بازگشایی، کلید متقارن را وارد کنید. ::PAYLOAD::$payload'; + } + + final decrypted = await _crypto.decryptSymmetric(payload, savedKey); + if (decrypted == null) { + if (isMe) return null; // Skip placeholder for our own failed echo + final label = isMe ? 'ارسال شده' : 'دریافت شد'; + return 'پیام امن متقارن $label. برای بازگشایی، کلید متقارن را وارد کنید. ::PAYLOAD::$payload'; + } + + await _db.saveDecrypted(cleanPayload, decrypted); + return decrypted; + } + + Future _handleAsymmetricMsg(String phone, String payload, + {bool isMe = false}) async { + final cleanPayload = payload.replaceAll(RegExp(r'\s+'), ''); + final cached = await _db.getDecrypted(cleanPayload); + if (cached != null) return cached; + + final contact = await _db.getContact(phone); + final sharedKeyEncoded = contact?['ecc_shared_key'] as String?; + if (sharedKeyEncoded == null || sharedKeyEncoded.isEmpty) { + if (isMe) return null; + final label = isMe ? 'ارسال شده' : 'دریافت شد'; + return 'پیام ${'رمزنگاری غیر متقارن (طولانی‌تر و امن‌تر)'} $label اما تبادل کلید هنوز کامل نشده است. ::PAYLOAD::$payload'; + } + + final decrypted = await _crypto.decryptWithSharedKey( + cleanPayload, _crypto.b64uDecode(sharedKeyEncoded)); + if (decrypted == null) { + if (isMe) return null; + return 'بازگشایی پیام ECC ناموفق بود. اثر انگشت یا تبادل کلید را بررسی کنید. ::PAYLOAD::$cleanPayload'; + } + + await _db.saveDecrypted(cleanPayload, decrypted); + return decrypted; + } + + bool _isPacketExpired(List> fragments) { + if (fragments.isEmpty) return false; + final lastSeen = fragments + .map((f) => (f['updated_at'] ?? f['date'] ?? 0) as int) + .fold(0, max); + return DateTime.now().millisecondsSinceEpoch - lastSeen > fragmentTimeoutMs; + } + + Future _handleLegacyFrag( + String phone, + Map frag, { + bool broadcast = true, + bool isMe = false, + bool isScan = false, + }) async { + debugPrint( + '[CRYPTO] Handling legacy fragment: id=${frag['packetId']}, part=${frag['partNo']}/${frag['totalParts']}, len=${frag['chunk']?.length}'); + await _db.saveFragment(phone, frag['packetId'], frag['partNo'], + frag['totalParts'], frag['chunk'], + packetMode: 'SYM'); + final fragments = await _db.getFragments(phone, frag['packetId']); + debugPrint( + '[CRYPTO] Fragment Status for ${frag['packetId']}: owned=${fragments.length}, total=${frag['totalParts']}'); + + if (fragments.length == frag['totalParts']) { + final sorted = List>.from(fragments) + ..sort((a, b) => + (a['frag_index'] as int).compareTo(b['frag_index'] as int)); + final payload = sorted.map((f) => f['body'] as String).join().trim(); + debugPrint( + '[CRYPTO] Packet ${frag['packetId']} reassembled. Total payload length: ${payload.length}'); + if (!isScan) { + await _db.clearFragments(phone, frag['packetId']); + } + if (frag['isGroup'] == true) { + final fullMsg = + '${ProtocolHelper.gPrefix}${ProtocolHelper.typeSym}|$payload'; + final result = await _handleGroupMsg(phone, fullMsg, "gsym", frag); + + // Delete individual fragments from group_messages + final groups = await _db.getGroupsContainingPhone(phone); + for (var g in groups) { + await _db.deleteGroupFragments(g['id'] as int, frag['packetId']); + } + + if (broadcast) { + _messageStreamController.add({ + 'phone': phone, + 'body': result ?? 'REFRESH', + 'originalBody': payload, + 'packetId': frag['packetId'], + 'packetMode': 'SYM', + 'isMultipartComplete': true, + 'isMe': isMe, + }); + } + return result; + } + final result = await _handleSymmetricMsg(phone, payload, isMe: isMe); + final eventBody = result ?? ProtocolHelper.buildSymmetricMsg(payload); + final eventDate = DateTime.now().millisecondsSinceEpoch; + + await _db.consolidatePacketMessage( + phone, + packetId: frag['packetId'] as String, + packetMode: 'SYM', + body: eventBody, + date: eventDate, + type: isMe ? 2 : 1, + isMe: isMe ? 1 : 0, + isRead: isMe ? 1 : 1, + isSecure: 1, + ); + + if (broadcast) { + _messageStreamController.add({ + 'phone': phone, + 'body': eventBody, + 'originalBody': ProtocolHelper.buildSymmetricMsg(payload), + 'packetId': frag['packetId'], + 'packetMode': 'SYM', + 'date': eventDate, + 'isMultipartPending': false, + 'isMultipartComplete': true, + 'isMe': isMe, + }); + } + return result; + } + + final action = isMe ? 'ارسال' : 'دریافت'; + final expired = _isPacketExpired(fragments); + final status = expired + ? 'باقی قطعات پیام نرسیده‌اند (زمان تمام شد)' + : 'در حال $action قطعات... (${fragments.length}/${frag['totalParts']})'; + if (broadcast) { + _messageStreamController.add({ + 'phone': phone, + 'body': status, + 'originalBody': 'SFRA_PART', + 'isMe': isMe, + 'packetId': frag['packetId'], + 'packetMode': 'SYM', + 'isMultipartPending': true, + 'isMultipartComplete': false, + 'receivedParts': fragments.length, + 'totalParts': frag['totalParts'], + }); + } + return status; + } + + Future _handleAsymmetricFrag( + String phone, + Map frag, { + bool broadcast = true, + bool isMe = false, + bool isScan = false, + }) async { + await _db.saveFragment(phone, frag['packetId'], frag['partNo'], + frag['totalParts'], frag['chunk'], + packetMode: 'AE'); + final fragments = await _db.getFragments(phone, frag['packetId']); + + if (fragments.length == frag['totalParts']) { + final sorted = List>.from(fragments) + ..sort((a, b) => + (a['frag_index'] as int).compareTo(b['frag_index'] as int)); + final payloadBytes = []; + for (final fragment in sorted) { + payloadBytes.addAll(_crypto.b64uDecode(fragment['body'] as String)); + } + if (!isScan) { + await _db.clearFragments(phone, frag['packetId']); + } + + final encodedPayload = _crypto.b64uEncode(payloadBytes); + final result = + await _handleAsymmetricMsg(phone, encodedPayload, isMe: isMe); + final eventBody = + result ?? ProtocolHelper.buildAsymmetricMsg(encodedPayload); + final eventDate = DateTime.now().millisecondsSinceEpoch; + + await _db.consolidatePacketMessage( + phone, + packetId: frag['packetId'] as String, + packetMode: 'AE', + body: eventBody, + date: eventDate, + type: isMe ? 2 : 1, + isMe: isMe ? 1 : 0, + isRead: isMe ? 1 : 1, + isSecure: 1, + ); + + if (broadcast) { + _messageStreamController.add({ + 'phone': phone, + 'body': eventBody, + 'originalBody': ProtocolHelper.buildAsymmetricMsg(encodedPayload), + 'packetId': frag['packetId'], + 'packetMode': 'AE', + 'date': eventDate, + 'isMultipartPending': false, + 'isMultipartComplete': true, + 'isMe': isMe, + }); + } + return result; + } + + final action = isMe ? 'ارسال' : 'دریافت'; + final expired = _isPacketExpired(fragments); + final status = expired + ? 'باقی قطعات پیام ECC نرسیده‌اند (زمان تمام شد)' + : 'در حال $action قطعات... (${fragments.length}/${frag['totalParts']})'; + if (broadcast) { + _messageStreamController.add({ + 'phone': phone, + 'body': status, + 'originalBody': 'SFRA_PART', + 'isMe': isMe, + 'packetId': frag['packetId'], + 'packetMode': 'AE', + 'isMultipartPending': true, + 'isMultipartComplete': false, + 'receivedParts': fragments.length, + 'totalParts': frag['totalParts'], + }); + } + return status; + } + + Future _handleGroupMsg( + String phone, String body, String type, Map parsed, + {bool isMe = false}) async { + final groups = await _db.getGroupsContainingPhone(phone); + if (groups.isEmpty) return body; + + final effectiveParsed = + parsed['payload'] != null ? parsed : ProtocolHelper.parseMessage(body); + final effectiveType = effectiveParsed['type'] as String? ?? type; + + String? firstSuccess; + for (final group in groups) { + final groupId = group['id'] as int; + String currentStoredBody = body; + final groupKey = (group['group_key'] as String? ?? '').trim(); + + if ((effectiveType == 'sym' || effectiveType == 'gsym') && + groupKey.isNotEmpty) { + final payload = effectiveParsed['payload'] as String?; + if (payload != null) { + final result = await _crypto.decryptSymmetric(payload, groupKey); + if (result != null) { + currentStoredBody = result; + firstSuccess ??= result; + } else { + currentStoredBody = + 'پیام امن گروهی دریافت شد اما کلید این گروه (ID: $groupId) معتبر نیست.'; + } + } + } else if (effectiveType == 'sym' || effectiveType == 'gsym') { + final label = isMe ? 'ارسال شده' : 'دریافت شد'; + return 'پیام امن گروهی $label. برای مشاهده، کلید گروه را وارد کنید. ::PAYLOAD::${effectiveParsed['payload']}'; + } + + await _db.saveGroupMessage( + groupId, currentStoredBody, DateTime.now().millisecondsSinceEpoch, + senderPhone: phone, + isSecure: firstSuccess != null ? 1 : 0, + packetId: parsed['packetId'], + packetMode: 'SYM'); + + if (firstSuccess != null) { + debugPrint('[CRYPTO] Group decryption SUCCESS for group $groupId.'); + break; + } + } + + if (firstSuccess != null) { + _messageStreamController.add({'phone': phone, 'body': 'REFRESH'}); + return firstSuccess; + } + return "گروه: ${groups[0]['name']}"; + } + + Future sendGroupSecureMessage( + int groupId, List phones, String text, String key) async { + if (text.length > maxTextLimit) { + throw "طول پیام نباید بیشتر از $maxTextLimit کاراکتر باشد."; + } + + final encrypted = await _crypto.encryptSymmetric(text, key); + final protocolMsg = + '${ProtocolHelper.gPrefix}${ProtocolHelper.typeSym}|$encrypted'; + await _db.saveGroupMessage( + groupId, text, DateTime.now().millisecondsSinceEpoch, + isSecure: 1, packetId: null, packetMode: 'SYM'); + + for (final phone in phones) { + final normalized = ContactHelper.normalizePhone(phone); + if (protocolMsg.length <= ProtocolHelper.maxSmsChars) { + await _telephony.sendSms(to: normalized, message: protocolMsg); + await Future.delayed(const Duration(milliseconds: 1500)); + } else { + await _sendLegacyFragmented(normalized, encrypted, isGroup: true); + } + } + _messageStreamController + .add({'phone': 'group_$groupId', 'body': 'REFRESH'}); + } +} + +@pragma('vm:entry-point') +void backgroundMessageHandler(SmsMessage message) async { + await ContactHelper.loadFromLocalCache(); + final phone = ContactHelper.normalizePhone(message.address ?? ""); + final name = ContactHelper.getName(phone); + final body = message.body ?? ""; + final parsed = ProtocolHelper.parseMessage(body); + final type = parsed['type']; + final isSecure = type != 'plain'; + final isControlProtocol = + type == 'key_init' || type == 'key_reply' || type == 'norm'; + + final db = DatabaseHelper.instance; + + // CRITICAL: Always persist to sms_cache so it survives app restarts + await db.saveSingleSmsToCache({ + 'sms_id': message.id, + 'address': phone, + 'body': body, + 'date': message.date ?? DateTime.now().millisecondsSinceEpoch, + 'type': 1, // Inbox + 'is_me': 0, + 'is_read': isControlProtocol ? 1 : 0, + 'is_secure': isSecure ? 1 : 0, + 'packet_id': parsed['packetId'], + 'packet_mode': type == 'afrag' + ? 'AE' + : (type == 'sfra' || type == 'sym' + ? 'SYM' + : (type == 'asym' ? 'AE' : null)), + }); + + if (isControlProtocol) { + return; + } + + if (type == 'sfra' || type == 'afrag') { + await db.saveFragment( + phone, + parsed['packetId'], + parsed['partNo'], + parsed['totalParts'], + parsed['chunk'], + packetMode: type == 'afrag' ? 'AE' : 'SYM', + ); + final fragments = await db.getFragments(phone, parsed['packetId']); + if (fragments.length == parsed['totalParts']) { + await NotificationHelper.instance.showNotification( + id: phone.hashCode, + title: "پیام امن جدید ($name)", + body: "پیام چندبخشی کامل شد. برای بازگشایی وارد برنامه شوید.", + payload: phone, + ); + } else { + await NotificationHelper.instance.showNotification( + id: phone.hashCode, + title: "پیام امن جدید ($name)", + body: + "در حال دریافت قطعات... (${fragments.length}/${parsed['totalParts']})", + payload: phone, + ); + } + return; + } + + if (parsed['isGroup'] == true) { + final groups = await db.getGroupsContainingPhone(phone); + if (groups.isNotEmpty) { + for (final group in groups) { + await db.saveGroupMessage( + group['id'] as int, body, DateTime.now().millisecondsSinceEpoch, + senderPhone: phone); + } + await NotificationHelper.instance.showNotification( + id: groups[0]['id'] as int, + title: "پیام جدید در گروه ${groups[0]['name']}", + body: isSecure ? "پیام امن گروهی" : body, + payload: "group_${groups[0]['id']}", + ); + return; + } + } + + await NotificationHelper.instance.showNotification( + id: phone.hashCode, + title: "پیام جدید از $name", + body: isSecure ? "پیام امن دریافت شد" : body, + payload: phone, + ); +} diff --git a/lib/widgets/app_lock_overlay.dart b/lib/widgets/app_lock_overlay.dart new file mode 100644 index 0000000..73749aa --- /dev/null +++ b/lib/widgets/app_lock_overlay.dart @@ -0,0 +1,306 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../utils/app_lock_service.dart'; +import '../utils/app_theme.dart'; + +class AppLockOverlay extends StatefulWidget { + const AppLockOverlay({ + super.key, + required this.child, + }); + + final Widget child; + + @override + State createState() => _AppLockOverlayState(); +} + +class _AppLockOverlayState extends State + with WidgetsBindingObserver { + bool _shouldRelockOnResume = false; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + final service = AppLockService.instance; + if (!service.isEnabled) return; + + if (state == AppLifecycleState.inactive || + state == AppLifecycleState.paused || + state == AppLifecycleState.hidden) { + _shouldRelockOnResume = true; + return; + } + + if (state == AppLifecycleState.resumed && _shouldRelockOnResume) { + _shouldRelockOnResume = false; + service.lock(); + } + } + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: AppLockService.instance, + builder: (context, _) { + final service = AppLockService.instance; + return Stack( + fit: StackFit.expand, + children: [ + widget.child, + if (service.initialized && service.isLocked) + const Positioned.fill(child: _AppLockBarrier()), + ], + ); + }, + ); + } +} + +class _AppLockBarrier extends StatelessWidget { + const _AppLockBarrier(); + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + child: Material( + color: AppTheme.darkBg.withValues(alpha: 0.96), + child: Stack( + fit: StackFit.expand, + children: [ + Positioned.fill( + child: CustomPaint( + painter: _LockBackgroundPainter(), + ), + ), + const SafeArea( + child: Center( + child: Padding( + padding: EdgeInsets.all(20), + child: _AppLockCard(), + ), + ), + ), + ], + ), + ), + ); + } +} + +class _AppLockCard extends StatefulWidget { + const _AppLockCard(); + + @override + State<_AppLockCard> createState() => _AppLockCardState(); +} + +class _AppLockCardState extends State<_AppLockCard> { + final TextEditingController _controller = TextEditingController(); + bool _isVerifying = false; + String? _errorText; + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + Future _unlock() async { + if (_isVerifying) return; + + FocusScope.of(context).unfocus(); + final passcode = _controller.text.trim(); + if (passcode.isEmpty) { + setState(() => _errorText = 'رمز برنامه را وارد کنید.'); + return; + } + + setState(() { + _isVerifying = true; + _errorText = null; + }); + + final isValid = await AppLockService.instance.verifyPasscode(passcode); + + if (!mounted) return; + setState(() { + _isVerifying = false; + _errorText = isValid ? null : 'رمز واردشده درست نیست.'; + }); + + if (isValid) { + _controller.clear(); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: AppTheme.glassWrapper( + radius: 28, + sigma: 14, + child: Padding( + padding: const EdgeInsets.fromLTRB(24, 28, 24, 24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 76, + height: 76, + decoration: BoxDecoration( + shape: BoxShape.circle, + gradient: LinearGradient( + colors: [ + theme.primaryColor.withValues(alpha: 0.95), + AppTheme.accentCyan.withValues(alpha: 0.95), + ], + ), + boxShadow: [ + BoxShadow( + color: theme.primaryColor.withValues(alpha: 0.28), + blurRadius: 20, + spreadRadius: 1, + ), + ], + ), + child: const Icon( + Icons.lock_rounded, + size: 38, + color: Colors.white, + ), + ), + const SizedBox(height: 18), + const Text( + 'قفل برنامه فعال است', + style: TextStyle( + fontSize: 22, + fontWeight: FontWeight.bold, + color: Colors.white, + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 10), + const Text( + 'برای ورود به صبا، رمز برنامه را وارد کنید.', + style: TextStyle( + fontSize: 14, + height: 1.6, + color: Colors.white70, + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 24), + TextField( + controller: _controller, + autofocus: true, + keyboardType: TextInputType.number, + textInputAction: TextInputAction.done, + obscureText: true, + obscuringCharacter: '•', + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, + LengthLimitingTextInputFormatter(8), + ], + onSubmitted: (_) => _unlock(), + decoration: InputDecoration( + labelText: 'رمز برنامه', + hintText: '۴ تا ۸ رقم', + errorText: _errorText, + filled: true, + fillColor: Colors.white.withValues(alpha: 0.06), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(16), + ), + ), + ), + const SizedBox(height: 18), + SizedBox( + width: double.infinity, + child: ElevatedButton.icon( + onPressed: _isVerifying ? null : _unlock, + style: ElevatedButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 15), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + ), + icon: _isVerifying + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.lock_open_rounded), + label: + Text(_isVerifying ? 'در حال بررسی...' : 'ورود به برنامه'), + ), + ), + ], + ), + ), + ), + ); + } +} + +class _LockBackgroundPainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + final purplePaint = Paint() + ..shader = RadialGradient( + colors: [ + AppTheme.accentPurple.withValues(alpha: 0.22), + AppTheme.accentPurple.withValues(alpha: 0), + ], + ).createShader( + Rect.fromCircle( + center: Offset(size.width * 0.18, size.height * 0.2), + radius: size.width * 0.55, + ), + ); + + final cyanPaint = Paint() + ..shader = RadialGradient( + colors: [ + AppTheme.accentCyan.withValues(alpha: 0.14), + AppTheme.accentCyan.withValues(alpha: 0), + ], + ).createShader( + Rect.fromCircle( + center: Offset(size.width * 0.82, size.height * 0.78), + radius: size.width * 0.6, + ), + ); + + canvas.drawCircle( + Offset(size.width * 0.18, size.height * 0.2), + size.width * 0.55, + purplePaint, + ); + canvas.drawCircle( + Offset(size.width * 0.82, size.height * 0.78), + size.width * 0.6, + cyanPaint, + ); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} diff --git a/lib/widgets/message_bubble.dart b/lib/widgets/message_bubble.dart new file mode 100644 index 0000000..83955d2 --- /dev/null +++ b/lib/widgets/message_bubble.dart @@ -0,0 +1,439 @@ +import 'package:flutter/material.dart'; +import 'package:shimmer/shimmer.dart'; +import '../models/chat_model.dart'; + +class MessageBubble extends StatefulWidget { + final String body; + final String? rawBody; + final String? statusLabel; + final int date; + final bool isMe; + final MessageStatus status; + final bool isSecure; + final bool canRetryDecryption; + final VoidCallback? onRetryDecryption; + + final String? packetMode; + final bool isPendingMultipart; + + const MessageBubble({ + super.key, + required this.body, + this.rawBody, + this.statusLabel, + required this.date, + required this.isMe, + required this.status, + this.isSecure = false, + this.canRetryDecryption = false, + this.onRetryDecryption, + this.packetMode, + this.isPendingMultipart = false, + }); + + @override + State createState() => _MessageBubbleState(); +} + +class _MessageBubbleState extends State + with SingleTickerProviderStateMixin { + bool _showRaw = false; + late AnimationController _animationController; + late Animation _slideAnimation; + late Animation _fadeAnimation; + + @override + void initState() { + super.initState(); + _animationController = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 400), + ); + + _fadeAnimation = CurvedAnimation( + parent: _animationController, + curve: Curves.easeIn, + ); + + // Directional Slide: Received from left, Sent from right + final double startOffsetX = widget.isMe ? 0.3 : -0.3; + + _slideAnimation = Tween( + begin: Offset(startOffsetX, 0), + end: Offset.zero, + ).animate(CurvedAnimation( + parent: _animationController, + curve: Curves.elasticOut, // Added premium bounce effect + )); + + _animationController.forward(); + } + + @override + void dispose() { + _animationController.dispose(); + super.dispose(); + } + + bool get _hasRawView => + widget.rawBody != null && + widget.rawBody!.isNotEmpty && + widget.rawBody != widget.body; + + String get _displayBody { + if (_showRaw && widget.rawBody != null) { + return widget.rawBody!; + } + + // Handle the payload separator + if (widget.body.contains(' ::PAYLOAD::')) { + return widget.body.split(' ::PAYLOAD::')[0]; + } + if (widget.body.contains(' | ')) { + return widget.body.split(' | ')[0]; + } + return widget.body; + } + + @override + Widget build(BuildContext context) { + final bool isLocked = widget.canRetryDecryption && !widget.isMe; + + // Premium Gradient logic for Sent messages + final List sentGradients = widget.status == MessageStatus.failed + ? [Colors.redAccent, Colors.red.shade900] + : (widget.isSecure + ? [const Color(0xFF6A11CB), const Color(0xFF2575FC), const Color(0xFF00D2FF)] // Secure: Violet to Cyan + : [const Color(0xFF7000FF), const Color(0xFF5C6BC0)]); // Normal: Deep Purple to Indigo + + // Received background colors + final Color receivedBg = isLocked + ? const Color(0xFF0A192F) // Deep Blue Glass for locked + : (widget.isSecure ? const Color(0xFF0D0D15) : const Color(0xFF0F0F0F)); + + return FadeTransition( + opacity: _fadeAnimation, + child: SlideTransition( + position: _slideAnimation, + child: ScaleTransition( + scale: CurvedAnimation( + parent: _animationController, + curve: const Interval(0.0, 0.7, curve: Curves.easeOutBack), + ), + child: Row( + textDirection: TextDirection.ltr, + mainAxisAlignment: + widget.isMe ? MainAxisAlignment.end : MainAxisAlignment.start, + children: [ + Padding( + padding: EdgeInsets.only( + left: widget.isMe ? 50 : 8, + right: widget.isMe ? 8 : 50, + top: 6, + bottom: 6, + ), + child: CustomPaint( + painter: BubblePainter( + color: widget.isMe ? null : receivedBg, + gradient: widget.isMe + ? LinearGradient( + colors: sentGradients, + begin: Alignment.topLeft, + end: Alignment.bottomRight, + stops: sentGradients.length == 3 ? [0.0, 0.5, 1.0] : null, + ) + : (!widget.isMe && widget.isSecure && !isLocked + ? const LinearGradient( + colors: [Color(0xFF1A1A2E), Color(0xFF16213E)], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ) + : null), + isMe: widget.isMe, + isSecure: widget.isSecure, + ), + child: Container( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 16), + constraints: BoxConstraints( + maxWidth: MediaQuery.of(context).size.width * 0.78), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + if (widget.isSecure) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + isLocked + ? Icons.security_rounded + : Icons.verified_user_rounded, + size: 14, + color: widget.isMe + ? Colors.white70 + : (isLocked + ? const Color(0xFF00E5FF) + : const Color(0xFF00D2FF)), + ), + const SizedBox(width: 6), + Expanded( + child: Text( + isLocked + ? "پیام رمزگذاری شده (نیاز به کلید)" + : (widget.isPendingMultipart + ? "در حال دریافت قطعات پیام..." + : (widget.packetMode == 'SYM' + ? "رمزنگاری متقارن (AES-256)" + : (widget.packetMode == 'AE' + ? "رمزنگاری نامتقارن (ECC)" + : "پیام امن تایید شده"))), + style: TextStyle( + fontWeight: FontWeight.bold, + color: widget.isMe + ? Colors.white.withValues(alpha: 0.8) + : (isLocked + ? const Color(0xFF00E5FF) + : const Color(0xFF00D2FF)), + fontSize: 10, + letterSpacing: 0.2, + ), + ), + ), + ], + ), + ), + if (widget.isPendingMultipart) + Shimmer.fromColors( + baseColor: Colors.white.withValues(alpha: 0.1), + highlightColor: Colors.white.withValues(alpha: 0.3), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container(height: 14, width: double.infinity, decoration: BoxDecoration(color: Colors.white10, borderRadius: BorderRadius.circular(4))), + const SizedBox(height: 6), + Container(height: 14, width: 150, decoration: BoxDecoration(color: Colors.white10, borderRadius: BorderRadius.circular(4))), + ], + ), + ) + else + Directionality( + textDirection: TextDirection.rtl, + child: Text( + _displayBody, + style: TextStyle( + color: widget.isMe + ? Colors.white + : Colors.white.withValues(alpha: 0.95), + fontSize: 15.5, + fontWeight: isLocked ? FontWeight.w700 : FontWeight.w400, + height: 1.5, + fontFamily: _showRaw ? "monospace" : null, + ), + ), + ), + if (isLocked) ...[ + const SizedBox(height: 12), + InkWell( + onTap: widget.onRetryDecryption, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + decoration: BoxDecoration( + color: const Color(0xFF00E5FF).withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFF00E5FF).withValues(alpha: 0.3), width: 1), + ), + child: const Row( + children: [ + Icon(Icons.vpn_key_rounded, size: 18, color: Color(0xFF00E5FF)), + SizedBox(width: 10), + Expanded( + child: Text( + "برای بازگشایی ضربه بزنید", + style: TextStyle(fontSize: 12, color: Color(0xFF00E5FF), fontWeight: FontWeight.bold), + ), + ), + Icon(Icons.chevron_right_rounded, color: Color(0xFF00E5FF)), + ], + ), + ), + ), + ], + const SizedBox(height: 8), + Row( + mainAxisAlignment: MainAxisAlignment.end, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + if (widget.isSecure && _hasRawView) + Padding( + padding: const EdgeInsets.only(right: 8), + child: InkWell( + onTap: () => setState(() => _showRaw = !_showRaw), + child: Text( + _showRaw ? "متن اصلی" : "دیتای خام", + style: TextStyle( + fontSize: 9, + fontWeight: FontWeight.bold, + color: widget.isMe ? Colors.white70 : const Color(0xFF00D2FF), + ), + ), + ), + ), + if (widget.statusLabel != null) + Flexible( + child: Text( + widget.statusLabel!, + style: TextStyle(fontSize: 9, color: widget.isMe ? Colors.white60 : Colors.white38), + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 6), + Text( + _formatTime(widget.date), + style: TextStyle(fontSize: 10, color: widget.isMe ? Colors.white60 : Colors.white38), + ), + if (widget.isMe) ...[ + const SizedBox(width: 4), + _buildStatusIcon(), + ] + ], + ), + ], + ), + ), + ), + ), + ], + ), + ), + ), + ); + } + + Widget _buildStatusIcon() { + switch (widget.status) { + case MessageStatus.sending: + return const SizedBox( + width: 8, + height: 8, + child: CircularProgressIndicator( + color: Colors.white, + strokeWidth: 1, + ), + ); + case MessageStatus.sent: + return const Icon(Icons.done_all, size: 12, color: Colors.white70); + case MessageStatus.failed: + return const Icon(Icons.error_outline, size: 12, color: Colors.white); + default: + return const SizedBox(); + } + } + + String _formatTime(int millis) { + final d = DateTime.fromMillisecondsSinceEpoch(millis); + return "${d.hour}:${d.minute.toString().padLeft(2, '0')}"; + } +} + +class BubblePainter extends CustomPainter { + final Color? color; + final Gradient? gradient; + final bool isMe; + final bool isSecure; + + BubblePainter({ + this.color, + this.gradient, + required this.isMe, + this.isSecure = false, + }); + + @override + void paint(Canvas canvas, Size size) { + final Paint paint = Paint()..style = PaintingStyle.fill; + const double tailWidth = 10.0; + const double tailHeight = 12.0; + + if (gradient != null) { + paint.shader = gradient!.createShader(Rect.fromLTWH(0, 0, size.width, size.height)); + } else if (color != null) { + paint.color = color!; + } + + const double R = 22.0; // Standard radius + final Path path = Path(); + + if (isMe) { + // Sent Message: Tail on bottom-right + path.moveTo(R, 0); + path.lineTo(size.width - R, 0); + path.quadraticBezierTo(size.width, 0, size.width, R); + path.lineTo(size.width, size.height - tailHeight - R); + path.quadraticBezierTo(size.width, size.height - tailHeight, size.width - tailWidth, size.height - tailHeight); + path.lineTo(size.width, size.height); // Pointy tail tip + path.lineTo(size.width - tailWidth - R, size.height - tailHeight); + path.lineTo(R, size.height - tailHeight); + path.quadraticBezierTo(0, size.height - tailHeight, 0, size.height - tailHeight - R); + path.lineTo(0, R); + path.quadraticBezierTo(0, 0, R, 0); + path.close(); + } else { + // Received Message: Tail on bottom-left + path.moveTo(tailWidth + R, 0); + path.lineTo(size.width - R, 0); + path.quadraticBezierTo(size.width, 0, size.width, R); + path.lineTo(size.width, size.height - tailHeight - R); + path.quadraticBezierTo(size.width, size.height - tailHeight, size.width - R, size.height - tailHeight); + path.lineTo(tailWidth + R, size.height - tailHeight); + path.lineTo(0, size.height); // Pointy tail tip + path.lineTo(tailWidth, size.height - tailHeight); + path.lineTo(tailWidth, R); + path.quadraticBezierTo(tailWidth, 0, tailWidth + R, 0); + path.close(); + } + + // --- Enhanced Glowing Shadows --- + if (isSecure) { + final Color shadowColor = isMe ? const Color(0xFF7000FF) : const Color(0xFF00D2FF); + // Layered glow effect + for (int i = 1; i <= 3; i++) { + canvas.drawShadow( + path.shift(Offset(0, 1.0 * i)), + shadowColor.withValues(alpha: 0.15 / i), + 4.0 * i, + false, + ); + } + } else { + canvas.drawShadow( + path.shift(const Offset(0, 3)), + Colors.black.withValues(alpha: 0.4), + 6.0, + false, + ); + } + + canvas.drawPath(path, paint); + + // --- Subtle Inner Border for Glass Effect --- + if (!isMe) { + final Paint borderPaint = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 0.5 + ..color = Colors.white.withValues(alpha: 0.15); + canvas.drawPath(path, borderPaint); + } + } + + @override + bool shouldRepaint(covariant BubblePainter oldDelegate) => + oldDelegate.color != color || + oldDelegate.gradient != gradient || + oldDelegate.isMe != isMe || + oldDelegate.isSecure != isSecure; +} + + +// Removed incorrect ColorExt diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..ed2584b --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "saba_secure_sms") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.saba_secure_sms") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..d0e7f79 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin"); + flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar); +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..b29e9ba --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_secure_storage_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..4e0004d --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "saba_secure_sms"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "saba_secure_sms"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/macos/.gitignore b/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..e140042 --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,24 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import cryptography_flutter +import flutter_local_notifications +import flutter_secure_storage_macos +import google_sign_in_ios +import path_provider_foundation +import shared_preferences_foundation +import sqflite_sqlcipher + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + CryptographyFlutterPlugin.register(with: registry.registrar(forPlugin: "CryptographyFlutterPlugin")) + FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin")) + FlutterSecureStoragePlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStoragePlugin")) + FLTGoogleSignInPlugin.register(with: registry.registrar(forPlugin: "FLTGoogleSignInPlugin")) + PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) + SqfliteSqlCipherPlugin.register(with: registry.registrar(forPlugin: "SqfliteSqlCipherPlugin")) +} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..2ea6d9c --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,705 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* saba_secure_sms.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "saba_secure_sms.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* saba_secure_sms.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* saba_secure_sms.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.sabaSecureSms.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/saba_secure_sms.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/saba_secure_sms"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.sabaSecureSms.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/saba_secure_sms.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/saba_secure_sms"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.sabaSecureSms.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/saba_secure_sms.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/saba_secure_sms"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..d341969 --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..4087c16 --- /dev/null +++ b/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = saba_secure_sms + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.sabaSecureSms + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.example. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/macos/RunnerTests/RunnerTests.swift b/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..1aa7a1f --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,839 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + another_telephony: + dependency: "direct main" + description: + name: another_telephony + sha256: "7dd16759099ea3e4ce762c4f5bbfa097940335555d5caa916aaa52eec6a70cb6" + url: "https://pub.dev" + source: hosted + version: "0.4.1" + archive: + dependency: transitive + description: + name: archive + sha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ff + url: "https://pub.dev" + source: hosted + version: "4.0.9" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + asn1lib: + dependency: transitive + description: + name: asn1lib + sha256: "9a8f69025044eb466b9b60ef3bc3ac99b4dc6c158ae9c56d25eeccf5bc56d024" + url: "https://pub.dev" + source: hosted + version: "1.6.5" + async: + dependency: transitive + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + cli_util: + dependency: transitive + description: + name: cli_util + sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c + url: "https://pub.dev" + source: hosted + version: "0.4.2" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + crypto: + dependency: "direct main" + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + cryptography: + dependency: "direct main" + description: + name: cryptography + sha256: "3eda3029d34ec9095a27a198ac9785630fe525c0eb6a49f3d575272f8e792ef0" + url: "https://pub.dev" + source: hosted + version: "2.9.0" + cryptography_flutter: + dependency: "direct main" + description: + name: cryptography_flutter + sha256: d1c7e7a31a072d63b27ce0537b89868f9bda9188f2b1651ae728a295762921d4 + url: "https://pub.dev" + source: hosted + version: "2.3.4" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + dbus: + dependency: transitive + description: + name: dbus + sha256: d0c98dcd4f5169878b6cf8f6e0a52403a9dff371a3e2f019697accbf6f44a270 + url: "https://pub.dev" + source: hosted + version: "0.7.12" + encrypt: + dependency: "direct main" + description: + name: encrypt + sha256: "62d9aa4670cc2a8798bab89b39fc71b6dfbacf615de6cf5001fb39f7e4a996a2" + url: "https://pub.dev" + source: hosted + version: "5.0.3" + extension_google_sign_in_as_googleapis_auth: + dependency: "direct main" + description: + name: extension_google_sign_in_as_googleapis_auth + sha256: "8a9c887a377ee5b990b2b29be229de8401a43002a7d0d0b29f7d014c1c6bfeac" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "16ed7b077ef01ad6170a3d0c57caa4a112a38d7a2ed5602e0aca9ca6f3d98da6" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_contacts: + dependency: "direct main" + description: + name: flutter_contacts + sha256: "388d32cd33f16640ee169570128c933b45f3259bddbfae7a100bb49e5ffea9ae" + url: "https://pub.dev" + source: hosted + version: "1.1.9+2" + flutter_launcher_icons: + dependency: "direct dev" + description: + name: flutter_launcher_icons + sha256: "526faf84284b86a4cb36d20a5e45147747b7563d921373d4ee0559c54fcdbcea" + url: "https://pub.dev" + source: hosted + version: "0.13.1" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "9e8c3858111da373efc5aa341de011d9bd23e2c5c5e0c62bccf32438e192d7b1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + flutter_local_notifications: + dependency: "direct main" + description: + name: flutter_local_notifications + sha256: "674173fd3c9eda9d4c8528da2ce0ea69f161577495a9cc835a2a4ecd7eadeb35" + url: "https://pub.dev" + source: hosted + version: "17.2.4" + flutter_local_notifications_linux: + dependency: transitive + description: + name: flutter_local_notifications_linux + sha256: c49bd06165cad9beeb79090b18cd1eb0296f4bf4b23b84426e37dd7c027fc3af + url: "https://pub.dev" + source: hosted + version: "4.0.1" + flutter_local_notifications_platform_interface: + dependency: transitive + description: + name: flutter_local_notifications_platform_interface + sha256: "85f8d07fe708c1bdcf45037f2c0109753b26ae077e9d9e899d55971711a4ea66" + url: "https://pub.dev" + source: hosted + version: "7.2.0" + flutter_localizations: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_secure_storage: + dependency: "direct main" + description: + name: flutter_secure_storage + sha256: "9cad52d75ebc511adfae3d447d5d13da15a55a92c9410e50f67335b6d21d16ea" + url: "https://pub.dev" + source: hosted + version: "9.2.4" + flutter_secure_storage_linux: + dependency: transitive + description: + name: flutter_secure_storage_linux + sha256: be76c1d24a97d0b98f8b54bce6b481a380a6590df992d0098f868ad54dc8f688 + url: "https://pub.dev" + source: hosted + version: "1.2.3" + flutter_secure_storage_macos: + dependency: transitive + description: + name: flutter_secure_storage_macos + sha256: "6c0a2795a2d1de26ae202a0d78527d163f4acbb11cde4c75c670f3a0fc064247" + url: "https://pub.dev" + source: hosted + version: "3.1.3" + flutter_secure_storage_platform_interface: + dependency: transitive + description: + name: flutter_secure_storage_platform_interface + sha256: cf91ad32ce5adef6fba4d736a542baca9daf3beac4db2d04be350b87f69ac4a8 + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_secure_storage_web: + dependency: transitive + description: + name: flutter_secure_storage_web + sha256: f4ebff989b4f07b2656fb16b47852c0aab9fed9b4ec1c70103368337bc1886a9 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + flutter_secure_storage_windows: + dependency: transitive + description: + name: flutter_secure_storage_windows + sha256: b20b07cb5ed4ed74fc567b78a72936203f587eba460af1df11281c9326cd3709 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + flutter_windowmanager_plus: + dependency: "direct main" + description: + name: flutter_windowmanager_plus + sha256: "4e2bf7c7f374699fd74d59785f1d74efd40052c24a5edde5a4d825cc72608d40" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + google_fonts: + dependency: "direct main" + description: + name: google_fonts + sha256: db9df7a5898d894eeda4c78143f35c30a243558be439518972366880b80bf88e + url: "https://pub.dev" + source: hosted + version: "8.0.2" + google_identity_services_web: + dependency: transitive + description: + name: google_identity_services_web + sha256: "5d187c46dc59e02646e10fe82665fc3884a9b71bc1c90c2b8b749316d33ee454" + url: "https://pub.dev" + source: hosted + version: "0.3.3+1" + google_sign_in: + dependency: transitive + description: + name: google_sign_in + sha256: "521031b65853b4409b8213c0387d57edaad7e2a949ce6dea0d8b2afc9cb29763" + url: "https://pub.dev" + source: hosted + version: "7.2.0" + google_sign_in_android: + dependency: transitive + description: + name: google_sign_in_android + sha256: be0d0733a6a7c5da165879d844a239aa87587a3c767a9163faedde581f731f76 + url: "https://pub.dev" + source: hosted + version: "7.2.10" + google_sign_in_ios: + dependency: transitive + description: + name: google_sign_in_ios + sha256: ac1e4c1205267cb7999d1d81333fccffdfda29e853f434bbaf71525498bb6950 + url: "https://pub.dev" + source: hosted + version: "6.3.0" + google_sign_in_platform_interface: + dependency: transitive + description: + name: google_sign_in_platform_interface + sha256: "7f59208c42b415a3cca203571128d6f84f885fead2d5b53eb65a9e27f2965bb5" + url: "https://pub.dev" + source: hosted + version: "3.1.0" + google_sign_in_web: + dependency: transitive + description: + name: google_sign_in_web + sha256: d473003eeca892f96a01a64fc803378be765071cb0c265ee872c7f8683245d14 + url: "https://pub.dev" + source: hosted + version: "1.1.3" + googleapis_auth: + dependency: transitive + description: + name: googleapis_auth + sha256: b81fe352cc4a330b3710d2b7ad258d9bcef6f909bb759b306bf42973a7d046db + url: "https://pub.dev" + source: hosted + version: "2.0.0" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: f9881ff4998044947ec38d098bc7c8316ae1186fa786eddffdb867b9bc94dfce + url: "https://pub.dev" + source: hosted + version: "4.8.0" + intl: + dependency: transitive + description: + name: intl + sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5" + url: "https://pub.dev" + source: hosted + version: "0.20.2" + js: + dependency: transitive + description: + name: js + sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 + url: "https://pub.dev" + source: hosted + version: "0.6.7" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: cb09e7dac6210041fad964ed7fbee004f14258b4eca4040f72d1234062ace4c8 + url: "https://pub.dev" + source: hosted + version: "4.11.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: cbf8d4b858bb0134ef3ef87841abdf8d63bfc255c266b7bf6b39daa1085c4290 + url: "https://pub.dev" + source: hosted + version: "3.0.0" + lottie: + dependency: "direct main" + description: + name: lottie + sha256: "8ae0be46dbd9e19641791dc12ee480d34e1fd3f84c749adc05f3ad9342b71b95" + url: "https://pub.dev" + source: hosted + version: "3.3.2" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + url: "https://pub.dev" + source: hosted + version: "0.12.19" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + url: "https://pub.dev" + source: hosted + version: "1.17.0" + path: + dependency: "direct main" + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider: + dependency: transitive + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "149441ca6e4f38193b2e004c0ca6376a3d11f51fa5a77552d8bd4d2b0c0912ba" + url: "https://pub.dev" + source: hosted + version: "2.2.23" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "6d13aece7b3f5c5a9731eaf553ff9dcbc2eff41087fd2df587fd0fed9a3eb0c4" + url: "https://pub.dev" + source: hosted + version: "2.5.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + permission_handler: + dependency: "direct main" + description: + name: permission_handler + sha256: "59adad729136f01ea9e35a48f5d1395e25cba6cea552249ddbe9cf950f5d7849" + url: "https://pub.dev" + source: hosted + version: "11.4.0" + permission_handler_android: + dependency: transitive + description: + name: permission_handler_android + sha256: d3971dcdd76182a0c198c096b5db2f0884b0d4196723d21a866fc4cdea057ebc + url: "https://pub.dev" + source: hosted + version: "12.1.0" + permission_handler_apple: + dependency: transitive + description: + name: permission_handler_apple + sha256: f000131e755c54cf4d84a5d8bd6e4149e262cc31c5a8b1d698de1ac85fa41023 + url: "https://pub.dev" + source: hosted + version: "9.4.7" + permission_handler_html: + dependency: transitive + description: + name: permission_handler_html + sha256: "38f000e83355abb3392140f6bc3030660cfaef189e1f87824facb76300b4ff24" + url: "https://pub.dev" + source: hosted + version: "0.1.3+5" + permission_handler_platform_interface: + dependency: transitive + description: + name: permission_handler_platform_interface + sha256: eb99b295153abce5d683cac8c02e22faab63e50679b937fa1bf67d58bb282878 + url: "https://pub.dev" + source: hosted + version: "4.3.0" + permission_handler_windows: + dependency: transitive + description: + name: permission_handler_windows + sha256: "1a790728016f79a41216d88672dbc5df30e686e811ad4e698bfc51f76ad91f1e" + url: "https://pub.dev" + source: hosted + version: "0.2.1" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pointycastle: + dependency: "direct main" + description: + name: pointycastle + sha256: "4be0097fcf3fd3e8449e53730c631200ebc7b88016acecab2b0da2f0149222fe" + url: "https://pub.dev" + source: hosted + version: "3.9.1" + posix: + dependency: transitive + description: + name: posix + sha256: "185ef7606574f789b40f289c233efa52e96dead518aed988e040a10737febb07" + url: "https://pub.dev" + source: hosted + version: "6.5.0" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf + url: "https://pub.dev" + source: hosted + version: "2.5.5" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: e8d4762b1e2e8578fc4d0fd548cebf24afd24f49719c08974df92834565e2c53 + url: "https://pub.dev" + source: hosted + version: "2.4.23" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "4e7eaffc2b17ba398759f1151415869a34771ba11ebbccd1b0145472a619a64f" + url: "https://pub.dev" + source: hosted + version: "2.5.6" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shimmer: + dependency: "direct main" + description: + name: shimmer + sha256: "5f88c883a22e9f9f299e5ba0e4f7e6054857224976a5d9f839d4ebdc94a14ac9" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + sqflite_common: + dependency: transitive + description: + name: sqflite_common + sha256: "761b9740ecbd4d3e66b8916d784e581861fd3c3553eda85e167bc49fdb68f709" + url: "https://pub.dev" + source: hosted + version: "2.5.4+6" + sqflite_sqlcipher: + dependency: "direct main" + description: + name: sqflite_sqlcipher + sha256: ba7733c5514cf0ccb0331997b771a890f73678bcd84cdfb5f7487a88a71f1738 + url: "https://pub.dev" + source: hosted + version: "3.4.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "688af5ed3402a4bde5b3a6c15fd768dbf2621a614950b17f04626c431ab3c4c3" + url: "https://pub.dev" + source: hosted + version: "1.3.0" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: "69fe30f3a8b04a0be0c15ae6490fc859a78ef4c43ae2dd5e8a623d45bfcf9225" + url: "https://pub.dev" + source: hosted + version: "3.3.0+3" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + test_api: + dependency: transitive + description: + name: test_api + sha256: "8161c84903fd860b26bfdefb7963b3f0b68fee7adea0f59ef805ecca346f0c7a" + url: "https://pub.dev" + source: hosted + version: "0.7.10" + timezone: + dependency: transitive + description: + name: timezone + sha256: "2236ec079a174ce07434e89fcd3fcda430025eb7692244139a9cf54fdcf1fc7d" + url: "https://pub.dev" + source: hosted + version: "0.9.4" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: f6be3ed8bd01289b34d679c2b62226f63c0e69f9fd2e50a6b3c1c729a961041b + url: "https://pub.dev" + source: hosted + version: "14.3.0" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + win32: + dependency: transitive + description: + name: win32 + sha256: "329edf97fdd893e0f1e3b9e88d6a0e627128cc17cc316a8d67fda8f1451178ba" + url: "https://pub.dev" + source: hosted + version: "5.13.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + url: "https://pub.dev" + source: hosted + version: "6.6.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.10.0 <4.0.0" + flutter: ">=3.38.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..3d1c7db --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,56 @@ +name: saba_secure_sms +description: "A secure SMS messaging application with ECC encryption." +publish_to: 'none' +version: 1.0.0+1 + +environment: + sdk: '>=3.0.0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + flutter_localizations: + sdk: flutter + + # SMS and Contacts + another_telephony: ^0.4.1 + permission_handler: ^11.0.0 + flutter_contacts: ^1.1.9 + + # Cryptography and Database + cryptography: ^2.5.0 + cryptography_flutter: ^2.3.4 + crypto: ^3.0.3 + encrypt: ^5.0.3 + pointycastle: ^3.9.1 + sqflite_sqlcipher: ^3.0.1 + flutter_secure_storage: ^9.0.0 + path: ^1.8.3 + + # UI and Icons + cupertino_icons: ^1.0.6 + flutter_local_notifications: ^17.1.2 + flutter_windowmanager_plus: ^1.0.1 + shared_preferences: ^2.2.2 + lottie: ^3.3.2 + shimmer: ^3.0.0 + extension_google_sign_in_as_googleapis_auth: ^3.0.0 + google_fonts: ^8.0.2 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^3.0.0 + flutter_launcher_icons: ^0.13.1 + +flutter: + uses-material-design: true + assets: + - صبا-.png + - صبا بالا.png + +flutter_launcher_icons: + android: "ic_launcher" + ios: true + image_path: "صبا-.png" + min_sdk_android: 21 diff --git a/test/background_logic_test.dart b/test/background_logic_test.dart new file mode 100644 index 0000000..5123306 --- /dev/null +++ b/test/background_logic_test.dart @@ -0,0 +1,51 @@ + +import '../lib/utils/protocol_helper.dart'; + +// Simulated environment for verification +class MockDatabase { + final List> savedFragments = []; + Future saveFragment(String phone, String msgId, int index, int total, String body) async { + savedFragments.add({ + 'phone': phone, + 'msgId': msgId, + 'index': index, + 'total': total, + 'body': body, + }); + print(' [MockDB] Saved fragment $index/$total for $msgId'); + } +} + +void main() async { + print('Verifying Background Message Handling Logic...'); + + final mockDb = MockDatabase(); + final phone = '09123456789'; + + // Test Case 1: Standard Symmetric Message + print('\nCase 1: Standard Symmetric Message'); + final body1 = '@S:SYM|h1:payload'; + final parsed1 = ProtocolHelper.parseMessage(body1); + assert(parsed1['type'] == 'sym'); + assert(parsed1['payload'] == 'h1:payload'); + print('✅ Logic: Show "Secure Message Received" notification'); + + // Test Case 2: Fragment Message + print('\nCase 2: Fragment Message'); + final body2 = '@S:SFRA|msg123|1|3|chunk1'; + final parsed2 = ProtocolHelper.parseMessage(body2); + assert(parsed2['type'] == 'sfra'); + + // Real logic would be: if (type == 'sfra') { await db.saveFragment(...) } + if (parsed2['type'] == 'sfra') { + await mockDb.saveFragment( + phone, parsed2['packetId'], parsed2['partNo'], parsed2['totalParts'], parsed2['chunk']); + } + + assert(mockDb.savedFragments.length == 1); + assert(mockDb.savedFragments[0]['msgId'] == 'msg123'); + assert(mockDb.savedFragments[0]['index'] == 1); + print('✅ Logic: Save fragment to DB and show "Receiving part 1/3" notification'); + + print('\nAll background logic checks passed! 🚀'); +} diff --git a/test/protocol_test.dart b/test/protocol_test.dart new file mode 100644 index 0000000..0660cb0 --- /dev/null +++ b/test/protocol_test.dart @@ -0,0 +1,80 @@ +import '../lib/utils/protocol_helper.dart'; + +void expect(dynamic actual, dynamic expected, String message) { + if (actual == expected) { + print('✅ $message'); + } else { + print('❌ $message (Expected: $expected, Actual: $actual)'); + throw Exception('Test failed: $message'); + } +} + +void main() { + print('Running Robust ProtocolHelper Tests...'); + + // 1. Standard Plain Text + var res = ProtocolHelper.parseMessage('Hello world'); + expect(res['type'], 'plain', 'Standard plain text'); + + // 2. Standard Symmetric + res = ProtocolHelper.parseMessage('@S:SYM|b1:payload'); + expect(res['type'], 'sym', 'Standard symmetric message'); + expect(res['payload'], 'b1:payload', 'Standard symmetric payload'); + + // 3. Mangled Prefix Symmetric + res = ProtocolHelper.parseMessage(' @ S: SYM | b1:payload '); + expect(res['type'], 'sym', 'Mangled prefix symmetric (with spaces)'); + expect(res['payload'], 'b1:payload', 'Mangled prefix symmetric payload'); + + // 4. Missing Prefix Symmetric + res = ProtocolHelper.parseMessage('SYM|b1:payload'); + expect(res['type'], 'sym', 'Missing prefix symmetric'); + expect(res['payload'], 'b1:payload', 'Missing prefix symmetric payload'); + + // 5. Standard Fragment + res = ProtocolHelper.parseMessage('@S:SFRA|pkt1|1|2|chunk1'); + expect(res['type'], 'sfra', 'Standard fragment'); + expect(res['packetId'], 'pkt1', 'Fragment packetId'); + expect(res['partNo'], 1, 'Fragment partNo'); + expect(res['totalParts'], 2, 'Fragment totalParts'); + expect(res['chunk'], 'chunk1', 'Fragment chunk'); + + // 6. Mangled Prefix Fragment + res = ProtocolHelper.parseMessage('[MSG] S: SFRA | pkt1 | 2 | 2 | chunk2'); + expect(res['type'], 'sfra', 'Mangled prefix fragment'); + expect(res['chunk'], 'chunk2', 'Mangled prefix fragment chunk'); + + // 7. Missing Prefix Fragment + res = ProtocolHelper.parseMessage('SFRA|pkt1|1|2|chunk1'); + expect(res['type'], 'sfra', 'Missing prefix fragment'); + + // 8. Mangled Separators (Persian style) + res = ProtocolHelper.parseMessage('@S:SFRA;pkt1!1;2!chunk1'); + expect(res['type'], 'sfra', 'Mangled separators fragment (; and !)'); + expect(res['packetId'], 'pkt1', 'Mangled separators packetId'); + expect(res['totalParts'], 2, 'Mangled separators totalParts'); + + // 9. Group Message Identification + res = ProtocolHelper.parseMessage('@G:SYM|b1:group_payload'); + expect(res['type'], 'sym', 'Standard group message type'); + expect(res['isGroup'], true, 'Standard group message isGroup flag'); + + res = ProtocolHelper.parseMessage('G: SYM | b1:group_payload'); + expect(res['type'], 'sym', 'Mangled group message type'); + expect(res['isGroup'], true, 'Mangled group message isGroup flag'); + + // 10. Prevention of incorrect b1: fallback on fragments + // If we have a fragment header but a mangled prefix, it should detect SFRA first + res = ProtocolHelper.parseMessage(' X S: SFRA|id|1|2|b1:part1'); + expect(res['type'], 'sfra', 'Ensure SFRA takes precedence over b1: fallback'); + expect(res['chunk'], 'b1:part1', 'Ensure chunk contains the b1: marker if it was part of it'); + + // 11. b1: Fallback (valid only if no pipes) + res = ProtocolHelper.parseMessage(' b1:standalone_payload '); + expect(res['type'], 'sym', 'b1: fallback valid'); + + res = ProtocolHelper.parseMessage(' h1:standalone_payload '); + expect(res['type'], 'sym', 'h1: fallback valid'); + + print('All 11 robust tests passed! 🚀'); +} diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..fca2a07 --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,48 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:saba_secure_sms/widgets/message_bubble.dart'; + +void main() { + testWidgets('MessageBubble renders secure multipart status', (tester) async { + await tester.pumpWidget( + const MaterialApp( + home: Scaffold( + body: MessageBubble( + body: 'در حال دریافت قطعات...', + statusLabel: + 'رمزنگاری غیر متقارن (طولانی‌تر و امن‌تر) • در حال سرهم‌بندی... (2/4)', + date: 0, + isMe: false, + status: MessageStatus.received, + isSecure: true, + ), + ), + ), + ); + + expect(find.text('در حال دریافت قطعات...'), findsOneWidget); + expect(find.textContaining('در حال سرهم‌بندی'), findsOneWidget); + expect(find.text('پیام امن چندبخشی'), findsOneWidget); + }); + + testWidgets('MessageBubble hides encrypted body for locked messages', + (tester) async { + await tester.pumpWidget( + const MaterialApp( + home: Scaffold( + body: MessageBubble( + body: 'پیام امن دریافت شد. ::PAYLOAD::abc', + date: 0, + isMe: false, + status: MessageStatus.received, + isSecure: true, + canRetryDecryption: true, + ), + ), + ), + ); + + expect(find.text('این متن رمزگذاری شده است'), findsOneWidget); + expect(find.text('بازگشایی پیام'), findsOneWidget); + }); +} diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..1d0b566 --- /dev/null +++ b/web/index.html @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + saba_secure_sms + + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..2720d19 --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "saba_secure_sms", + "short_name": "saba_secure_sms", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..7db46f4 --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(saba_secure_sms LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "saba_secure_sms") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8883006 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,17 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FlutterSecureStorageWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterSecureStorageWindowsPlugin")); + PermissionHandlerWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..6f18371 --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,25 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_secure_storage_windows + permission_handler_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..9a30ccd --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "saba_secure_sms" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "saba_secure_sms" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "saba_secure_sms.exe" "\0" + VALUE "ProductName", "saba_secure_sms" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..08b8408 --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"saba_secure_sms", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/صبا بالا.png b/صبا بالا.png new file mode 100755 index 0000000..8d99a4e Binary files /dev/null and b/صبا بالا.png differ diff --git a/صبا-.png b/صبا-.png new file mode 100644 index 0000000..d608ca7 Binary files /dev/null and b/صبا-.png differ