From 0070ab141291720df4fc22df8360fb3d160037b2 Mon Sep 17 00:00:00 2001 From: Mani Vendhan M Date: Thu, 8 Jun 2023 15:52:08 +0530 Subject: [PATCH] #Version Update --- .idea/libraries/Dart_SDK.xml | 39 +- README.md | 24 +- android/app/build.gradle | 22 +- android/app/google-services.json | 98 - android/app/src/dev/google-services.json | 100 - android/app/src/main/AndroidManifest.xml | 2 +- android/app/src/prod/google-services.json | 92 - android/app/src/qa/google-services.json | 98 - android/build.gradle | 3 +- android/fastlane/Appfile | 2 - android/fastlane/Fastfile | 44 - android/fastlane/Pluginfile | 5 - android/fastlane/README.md | 40 - android/fastlane/report.xml | 18 - .../FlutterNotificationExtnsion.entitlements | 10 - ios/FlutterNotificationExtnsion/Info.plist | 13 - .../NotificationService.swift | 151 -- ios/Podfile | 29 - ios/Runner.xcodeproj/project.pbxproj | 10 +- ios/Runner/AppDelegate.swift | 128 +- ios/Runner/Commons.swift | 29 - ios/Runner/FlyBaseController.swift | 1308 ---------- ios/Runner/FlyEvents.swift | 665 ------ ios/Runner/FlySdkMethodCalls.swift | 2113 ----------------- ios/Runner/GoogleService-Info-dev.plist | 36 - ios/Runner/GoogleService-Info.plist | 36 - ios/Runner/GoogleService-Info_old.plist | 36 - ios/Runner/Info.plist | 28 +- ios/Runner/JsonSerializer.swift | 451 ---- ios/Runner/NetworkConnectivityManager.swift | 50 - ios/Runner/Runner.entitlements | 2 +- ios/Runner/UserDefaults.swift | 104 - lib/app/base_controller.dart | 22 +- lib/app/common/constants.dart | 11 +- lib/app/common/main_controller.dart | 18 +- lib/app/common/widgets.dart | 10 +- lib/app/data/helper.dart | 68 +- lib/app/data/permissions.dart | 81 +- lib/app/data/session_management.dart | 9 +- lib/app/model/chat_message_model.dart | 490 ++++ lib/app/model/group_media_model.dart | 22 + .../archived_chat_list_controller.dart | 74 +- .../archived_chat_list_view.dart | 3 + .../controllers/camera_pick_controller.dart | 12 +- .../camera_pick/views/camera_pick_view.dart | 51 +- lib/app/modules/chat/chat_widgets.dart | 850 +++---- .../chat/controllers/chat_controller.dart | 202 +- .../chat/controllers/contact_controller.dart | 32 +- .../controllers/forwardchat_controller.dart | 47 +- .../modules/chat/views/chat_search_view.dart | 5 +- lib/app/modules/chat/views/chat_view.dart | 336 ++- .../modules/chat/views/contact_list_view.dart | 4 +- .../chat/views/starred_message_header.dart | 9 +- .../controllers/dashboard_controller.dart | 41 +- .../dashboard/views/dashboard_view.dart | 8 +- lib/app/modules/dashboard/widgets.dart | 45 +- .../delete_account_controller.dart | 6 +- .../views/delete_account_view.dart | 12 +- .../gallery_picker/src/core/functions.dart | 10 +- .../pages/gallery_media_picker.dart | 2 +- .../views/gallery_picker_view.dart | 3 +- .../group_creation_controller.dart | 1 - .../controllers/group_info_controller.dart | 14 +- .../login/controllers/login_controller.dart | 105 +- .../login/views/country_list_view.dart | 4 +- lib/app/modules/login/views/login_view.dart | 2 +- lib/app/modules/login/views/otp_view.dart | 2 +- .../controllers/media_preview_controller.dart | 6 +- .../views/media_preview_view.dart | 44 +- .../controllers/message_info_controller.dart | 32 +- .../controllers/profile_controller.dart | 96 +- .../modules/profile/views/profile_view.dart | 280 ++- .../scanner/web_login_result_view.dart | 4 +- .../controllers/settings_controller.dart | 18 +- .../views/app_lock/app_lock_controller.dart | 204 +- .../app_lock/app_lock_settings_view.dart | 6 +- .../settings/views/app_lock/pin_view.dart | 12 +- .../chat_settings_controller.dart | 16 +- .../chat_settings/chat_settings_view.dart | 6 +- .../modules/settings/views/settings_view.dart | 58 +- .../starred_messages_controller.dart | 146 +- .../views/starred_messages_view.dart | 4 +- .../controllers/video_play_controller.dart | 31 +- .../views/video_player_view.dart | 65 +- .../view_all_media_controller.dart | 8 +- .../views/view_all_media_view.dart | 3 +- .../views/view_all_media_preview_view.dart | 40 +- lib/app/widgets/video_player_widget.dart | 172 ++ lib/firebase_options.dart | 96 - lib/main.dart | 55 +- macos/Flutter/GeneratedPluginRegistrant.swift | 8 +- pubspec.lock | 384 +-- pubspec.yaml | 40 +- .../flutter/generated_plugin_registrant.cc | 3 + windows/flutter/generated_plugins.cmake | 1 + 95 files changed, 2614 insertions(+), 7621 deletions(-) delete mode 100644 android/app/google-services.json delete mode 100644 android/app/src/dev/google-services.json delete mode 100644 android/app/src/prod/google-services.json delete mode 100644 android/app/src/qa/google-services.json delete mode 100644 android/fastlane/Appfile delete mode 100644 android/fastlane/Fastfile delete mode 100644 android/fastlane/Pluginfile delete mode 100644 android/fastlane/README.md delete mode 100644 android/fastlane/report.xml delete mode 100644 ios/FlutterNotificationExtnsion/FlutterNotificationExtnsion.entitlements delete mode 100644 ios/FlutterNotificationExtnsion/Info.plist delete mode 100644 ios/FlutterNotificationExtnsion/NotificationService.swift delete mode 100644 ios/Runner/Commons.swift delete mode 100644 ios/Runner/FlyBaseController.swift delete mode 100644 ios/Runner/FlyEvents.swift delete mode 100644 ios/Runner/FlySdkMethodCalls.swift delete mode 100644 ios/Runner/GoogleService-Info-dev.plist delete mode 100755 ios/Runner/GoogleService-Info.plist delete mode 100644 ios/Runner/GoogleService-Info_old.plist delete mode 100644 ios/Runner/JsonSerializer.swift delete mode 100755 ios/Runner/NetworkConnectivityManager.swift delete mode 100755 ios/Runner/UserDefaults.swift create mode 100644 lib/app/model/chat_message_model.dart create mode 100644 lib/app/model/group_media_model.dart create mode 100644 lib/app/widgets/video_player_widget.dart delete mode 100644 lib/firebase_options.dart diff --git a/.idea/libraries/Dart_SDK.xml b/.idea/libraries/Dart_SDK.xml index 064833ec..cdb3b5d1 100644 --- a/.idea/libraries/Dart_SDK.xml +++ b/.idea/libraries/Dart_SDK.xml @@ -1,25 +1,26 @@ - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + diff --git a/README.md b/README.md index dbced63b..6f8020fb 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,33 @@ If you're looking for the fastest way in action with CONTUS TECH [MirrorFly Plug ## Configuration -Replace the `licence key` with yours in `main.dart` file. +Replace the `licence key` , `ios Container ID` with yours in `main.dart` file. ```dart Mirrorfly.init( baseUrl: 'https://api-preprod-sandbox.mirrorfly.com/api/v1/', licenseKey: 'Please enter your License key', - iOSContainerID: 'group.com.mirrorfly.qa') + iOSContainerID: 'Please enter your Container ID') //Container ID should be same as App Groups +``` +## Google Services + +If you are going to check Location sharing feature, + +# Android +Specify your API key in the application manifest android/app/src/main/AndroidManifest.xml: +```dart + +``` +Specify your API key in the application Constant dart file lib/app/common/constants.dart +```dart + static const String googleMapKey = "YOUR GOOGLE KEY HERE"; +``` +# iOS +Specify your API key in the AppDelegate.swift + +```dart + GMSServices.provideAPIKey("YOUR GOOGLE KEY HERE") ``` ## Run project diff --git a/android/app/build.gradle b/android/app/build.gradle index b652b8cd..aa8e1587 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -25,7 +25,6 @@ apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" apply plugin: 'kotlin-kapt' -apply plugin: 'com.google.gms.google-services' android { compileSdkVersion flutter.compileSdkVersion @@ -49,7 +48,7 @@ android { applicationId "com.mirrorfly.uikit_flutter.qa" // You can update the following values to match your application needs. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration. - minSdkVersion flutter.minSdkVersion + minSdkVersion 21 targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName @@ -104,30 +103,11 @@ dependencies { implementation 'androidx.appcompat:appcompat:1.5.1' implementation 'com.google.android.material:material:1.4.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' -// implementation ('com.fly.sdk:appbase:0.0.5') configurations { all { exclude group: 'org.json', module: 'json' exclude group: 'xpp3', module: 'xpp3' } } -// implementation 'com.mirrorfly.sdk:appbase:0.0.12' - - /*// Import the Firebase BoM - implementation platform('com.google.firebase:firebase-bom:30.2.0') - - // Add the dependency for the Firebase SDK for Google Analytics - // When using the BoM, don't specify versions in Firebase dependencies - implementation 'com.google.firebase:firebase-analytics' - implementation 'com.google.firebase:firebase-messaging' - - //Glide - versions.gradle - implementation "com.github.bumptech.glide:glide:4.14.2" - kapt "com.github.bumptech.glide:compiler:4.11.0" - - //KTX Depenedency - implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1' - implementation 'androidx.fragment:fragment-ktx:1.5.5' - implementation 'androidx.activity:activity-ktx:1.7.0-alpha02'*/ } diff --git a/android/app/google-services.json b/android/app/google-services.json deleted file mode 100644 index 5f4175a1..00000000 --- a/android/app/google-services.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "project_info": { - "project_number": "235373697524", - "project_id": "mirrorfly-uikit-qa", - "storage_bucket": "mirrorfly-uikit-qa.appspot.com" - }, - "client": [ - { - "client_info": { - "mobilesdk_app_id": "1:235373697524:android:6003ca46ab3fd6ada0c1a1", - "android_client_info": { - "package_name": "com.mirrorfly.uikit.qa" - } - }, - "oauth_client": [ - { - "client_id": "235373697524-00ffa2b0fnuqiaq8lrsm4dngutag4gsi.apps.googleusercontent.com", - "client_type": 1, - "android_info": { - "package_name": "com.mirrorfly.uikit.qa", - "certificate_hash": "f2e6cce5db55425b8fb5e6da0db05cd82bd76a48" - } - }, - { - "client_id": "235373697524-lnprhrs93p068q2fempp75f5t00u39ga.apps.googleusercontent.com", - "client_type": 1, - "android_info": { - "package_name": "com.mirrorfly.uikit.qa", - "certificate_hash": "e31756556a43b89c8b95f22eb86f47af53baa7fb" - } - }, - { - "client_id": "235373697524-3tl5e1eoqvqmv51qcqhgmcg2nkndfgu7.apps.googleusercontent.com", - "client_type": 3 - } - ], - "api_key": [ - { - "current_key": "AIzaSyDfIqmrHFXEvJgE29tWr3Ps1bFJ-sOd2Go" - } - ], - "services": { - "appinvite_service": { - "other_platform_oauth_client": [ - { - "client_id": "235373697524-3tl5e1eoqvqmv51qcqhgmcg2nkndfgu7.apps.googleusercontent.com", - "client_type": 3 - }, - { - "client_id": "235373697524-2na45jkmpo3vu58u26m96huimhjkrrgi.apps.googleusercontent.com", - "client_type": 2, - "ios_info": { - "bundle_id": "com.mirrorfly.uikit.qa" - } - } - ] - } - } - }, - { - "client_info": { - "mobilesdk_app_id": "1:235373697524:android:8c60557f4f35c990a0c1a1", - "android_client_info": { - "package_name": "com.mirrorfly.uikit_flutter.qa" - } - }, - "oauth_client": [ - { - "client_id": "235373697524-3tl5e1eoqvqmv51qcqhgmcg2nkndfgu7.apps.googleusercontent.com", - "client_type": 3 - } - ], - "api_key": [ - { - "current_key": "AIzaSyDfIqmrHFXEvJgE29tWr3Ps1bFJ-sOd2Go" - } - ], - "services": { - "appinvite_service": { - "other_platform_oauth_client": [ - { - "client_id": "235373697524-3tl5e1eoqvqmv51qcqhgmcg2nkndfgu7.apps.googleusercontent.com", - "client_type": 3 - }, - { - "client_id": "235373697524-2na45jkmpo3vu58u26m96huimhjkrrgi.apps.googleusercontent.com", - "client_type": 2, - "ios_info": { - "bundle_id": "com.mirrorfly.uikit.qa" - } - } - ] - } - } - } - ], - "configuration_version": "1" -} \ No newline at end of file diff --git a/android/app/src/dev/google-services.json b/android/app/src/dev/google-services.json deleted file mode 100644 index af12443b..00000000 --- a/android/app/src/dev/google-services.json +++ /dev/null @@ -1,100 +0,0 @@ -{ - "project_info": { - "project_number": "1045831384770", - "project_id": "mirrorfly-uikit-dev", - "storage_bucket": "mirrorfly-uikit-dev.appspot.com" - }, - "client": [ - { - "client_info": { - "mobilesdk_app_id": "1:1045831384770:android:a55d04707f21bc2411455b", - "android_client_info": { - "package_name": "com.mirrorfly.uikit.dev" - } - }, - "oauth_client": [ - { - "client_id": "1045831384770-aa561p9dbh0467tsg3395ufeleu162k4.apps.googleusercontent.com", - "client_type": 1, - "android_info": { - "package_name": "com.mirrorfly.uikit.dev", - "certificate_hash": "5b7680dba9f17499d23141415c13745fd4f07e49" - } - }, - { - "client_id": "1045831384770-cn9q7gvgbpkn84rhcii70dai65kloovn.apps.googleusercontent.com", - "client_type": 1, - "android_info": { - "package_name": "com.mirrorfly.uikit.dev", - "certificate_hash": "f2e6cce5db55425b8fb5e6da0db05cd82bd76a48" - } - }, - { - "client_id": "1045831384770-poaavfuqpdujcp8a660do0slg6a92big.apps.googleusercontent.com", - "client_type": 1, - "android_info": { - "package_name": "com.mirrorfly.uikit.dev", - "certificate_hash": "9cc3a748151b891ffdc9ca776601ba020f25ca20" - } - }, - { - "client_id": "1045831384770-dja80m0ncgornapu8gc5pl42p1a3mtn5.apps.googleusercontent.com", - "client_type": 3 - } - ], - "api_key": [ - { - "current_key": "AIzaSyCfG5u1-XDZhWD8vOZGK5hTKyqsVOjHSSM" - } - ], - "services": { - "appinvite_service": { - "other_platform_oauth_client": [ - { - "client_id": "1045831384770-dja80m0ncgornapu8gc5pl42p1a3mtn5.apps.googleusercontent.com", - "client_type": 3 - } - ] - } - } - }, - { - "client_info": { - "mobilesdk_app_id": "1:1045831384770:android:cfdf83b6e0ada96911455b", - "android_client_info": { - "package_name": "com.mirrorfly.uikit_flutter.dev" - } - }, - "oauth_client": [ - { - "client_id": "1045831384770-acrljslm6312d4gepbbd5qifop5gj2dl.apps.googleusercontent.com", - "client_type": 1, - "android_info": { - "package_name": "com.mirrorfly.uikit_flutter.dev", - "certificate_hash": "2f49f60104e620b96e545f8ec71b59e22db50fc8" - } - }, - { - "client_id": "1045831384770-dja80m0ncgornapu8gc5pl42p1a3mtn5.apps.googleusercontent.com", - "client_type": 3 - } - ], - "api_key": [ - { - "current_key": "AIzaSyCfG5u1-XDZhWD8vOZGK5hTKyqsVOjHSSM" - } - ], - "services": { - "appinvite_service": { - "other_platform_oauth_client": [ - { - "client_id": "1045831384770-dja80m0ncgornapu8gc5pl42p1a3mtn5.apps.googleusercontent.com", - "client_type": 3 - } - ] - } - } - } - ], - "configuration_version": "1" -} \ No newline at end of file diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 714c105f..2156a123 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -56,7 +56,7 @@ android:name="flutterEmbedding" android:value="2" /> + android:value="YOUR GOOGLE KEY HERE"/> diff --git a/android/app/src/prod/google-services.json b/android/app/src/prod/google-services.json deleted file mode 100644 index b7a6eef4..00000000 --- a/android/app/src/prod/google-services.json +++ /dev/null @@ -1,92 +0,0 @@ -{ - "project_info": { - "project_number": "1045831384770", - "project_id": "mirrorfly-uikit-dev", - "storage_bucket": "mirrorfly-uikit-dev.appspot.com" - }, - "client": [ - { - "client_info": { - "mobilesdk_app_id": "1:1045831384770:android:a55d04707f21bc2411455b", - "android_client_info": { - "package_name": "com.mirrorfly.uikit.dev" - } - }, - "oauth_client": [ - { - "client_id": "1045831384770-aa561p9dbh0467tsg3395ufeleu162k4.apps.googleusercontent.com", - "client_type": 1, - "android_info": { - "package_name": "com.mirrorfly.uikit.dev", - "certificate_hash": "5b7680dba9f17499d23141415c13745fd4f07e49" - } - }, - { - "client_id": "1045831384770-cn9q7gvgbpkn84rhcii70dai65kloovn.apps.googleusercontent.com", - "client_type": 1, - "android_info": { - "package_name": "com.mirrorfly.uikit.dev", - "certificate_hash": "f2e6cce5db55425b8fb5e6da0db05cd82bd76a48" - } - }, - { - "client_id": "1045831384770-poaavfuqpdujcp8a660do0slg6a92big.apps.googleusercontent.com", - "client_type": 1, - "android_info": { - "package_name": "com.mirrorfly.uikit.dev", - "certificate_hash": "9cc3a748151b891ffdc9ca776601ba020f25ca20" - } - }, - { - "client_id": "1045831384770-dja80m0ncgornapu8gc5pl42p1a3mtn5.apps.googleusercontent.com", - "client_type": 3 - } - ], - "api_key": [ - { - "current_key": "AIzaSyCfG5u1-XDZhWD8vOZGK5hTKyqsVOjHSSM" - } - ], - "services": { - "appinvite_service": { - "other_platform_oauth_client": [ - { - "client_id": "1045831384770-dja80m0ncgornapu8gc5pl42p1a3mtn5.apps.googleusercontent.com", - "client_type": 3 - } - ] - } - } - }, - { - "client_info": { - "mobilesdk_app_id": "1:1045831384770:android:cfdf83b6e0ada96911455b", - "android_client_info": { - "package_name": "com.mirrorfly.uikit_flutter.dev" - } - }, - "oauth_client": [ - { - "client_id": "1045831384770-dja80m0ncgornapu8gc5pl42p1a3mtn5.apps.googleusercontent.com", - "client_type": 3 - } - ], - "api_key": [ - { - "current_key": "AIzaSyCfG5u1-XDZhWD8vOZGK5hTKyqsVOjHSSM" - } - ], - "services": { - "appinvite_service": { - "other_platform_oauth_client": [ - { - "client_id": "1045831384770-dja80m0ncgornapu8gc5pl42p1a3mtn5.apps.googleusercontent.com", - "client_type": 3 - } - ] - } - } - } - ], - "configuration_version": "1" -} \ No newline at end of file diff --git a/android/app/src/qa/google-services.json b/android/app/src/qa/google-services.json deleted file mode 100644 index 5f4175a1..00000000 --- a/android/app/src/qa/google-services.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "project_info": { - "project_number": "235373697524", - "project_id": "mirrorfly-uikit-qa", - "storage_bucket": "mirrorfly-uikit-qa.appspot.com" - }, - "client": [ - { - "client_info": { - "mobilesdk_app_id": "1:235373697524:android:6003ca46ab3fd6ada0c1a1", - "android_client_info": { - "package_name": "com.mirrorfly.uikit.qa" - } - }, - "oauth_client": [ - { - "client_id": "235373697524-00ffa2b0fnuqiaq8lrsm4dngutag4gsi.apps.googleusercontent.com", - "client_type": 1, - "android_info": { - "package_name": "com.mirrorfly.uikit.qa", - "certificate_hash": "f2e6cce5db55425b8fb5e6da0db05cd82bd76a48" - } - }, - { - "client_id": "235373697524-lnprhrs93p068q2fempp75f5t00u39ga.apps.googleusercontent.com", - "client_type": 1, - "android_info": { - "package_name": "com.mirrorfly.uikit.qa", - "certificate_hash": "e31756556a43b89c8b95f22eb86f47af53baa7fb" - } - }, - { - "client_id": "235373697524-3tl5e1eoqvqmv51qcqhgmcg2nkndfgu7.apps.googleusercontent.com", - "client_type": 3 - } - ], - "api_key": [ - { - "current_key": "AIzaSyDfIqmrHFXEvJgE29tWr3Ps1bFJ-sOd2Go" - } - ], - "services": { - "appinvite_service": { - "other_platform_oauth_client": [ - { - "client_id": "235373697524-3tl5e1eoqvqmv51qcqhgmcg2nkndfgu7.apps.googleusercontent.com", - "client_type": 3 - }, - { - "client_id": "235373697524-2na45jkmpo3vu58u26m96huimhjkrrgi.apps.googleusercontent.com", - "client_type": 2, - "ios_info": { - "bundle_id": "com.mirrorfly.uikit.qa" - } - } - ] - } - } - }, - { - "client_info": { - "mobilesdk_app_id": "1:235373697524:android:8c60557f4f35c990a0c1a1", - "android_client_info": { - "package_name": "com.mirrorfly.uikit_flutter.qa" - } - }, - "oauth_client": [ - { - "client_id": "235373697524-3tl5e1eoqvqmv51qcqhgmcg2nkndfgu7.apps.googleusercontent.com", - "client_type": 3 - } - ], - "api_key": [ - { - "current_key": "AIzaSyDfIqmrHFXEvJgE29tWr3Ps1bFJ-sOd2Go" - } - ], - "services": { - "appinvite_service": { - "other_platform_oauth_client": [ - { - "client_id": "235373697524-3tl5e1eoqvqmv51qcqhgmcg2nkndfgu7.apps.googleusercontent.com", - "client_type": 3 - }, - { - "client_id": "235373697524-2na45jkmpo3vu58u26m96huimhjkrrgi.apps.googleusercontent.com", - "client_type": 2, - "ios_info": { - "bundle_id": "com.mirrorfly.uikit.qa" - } - } - ] - } - } - } - ], - "configuration_version": "1" -} \ No newline at end of file diff --git a/android/build.gradle b/android/build.gradle index d61c23e1..ca918179 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -9,7 +9,6 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:7.1.2' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10" - classpath 'com.google.gms:google-services:4.3.14' } } @@ -33,6 +32,6 @@ subprojects { project.evaluationDependsOn(':app') } -task clean(type: Delete) { +tasks.register("clean", Delete) { delete rootProject.buildDir } diff --git a/android/fastlane/Appfile b/android/fastlane/Appfile deleted file mode 100644 index 37c34d48..00000000 --- a/android/fastlane/Appfile +++ /dev/null @@ -1,2 +0,0 @@ -json_key_file("") # Path to the json secret file - Follow https://docs.fastlane.tools/actions/supply/#setup to get one -package_name("com.mirrorfly.uikit_flutter.dev") # e.g. com.krausefx.app diff --git a/android/fastlane/Fastfile b/android/fastlane/Fastfile deleted file mode 100644 index 2110a880..00000000 --- a/android/fastlane/Fastfile +++ /dev/null @@ -1,44 +0,0 @@ -default_platform(:android) - -platform :android do - # Release Notes Filepath - # release_notes = File.read("../releasenote.txt") - # Changelogs Filepath - # changelogs = File.read("../changelogs.txt") - # Production Firebase App ID - appID = "" - # DEV Firebase App ID - appID_DEV = "1:1045831384770:android:cfdf83b6e0ada96911455b" - # QA Firebase App ID - appID_QA = "1:235373697524:android:8c60557f4f35c990a0c1a1" - # UAT Firebase App ID - appID_UAT = "1:719522206274:android:df54ba1969d80aeba2d3db" - - # DEV Release Notes - change_Log = "bug fixes" - - - desc "Upload dev version to distributes in firebase" - lane :deploy_dev_debug do - firebase_app_distribution( - app: appID_DEV, - groups: "mirrorflydev---flutter", - release_notes: change_Log, - apk_path: "../build/app/outputs/flutter-apk/app-dev-debug.apk", - firebase_cli_path: "/usr/local/bin/firebase", - firebase_cli_token: "1//0gca4tG-kR13uCgYIARAAGBASNwF-L9Irt1O8cK62NJe-EO1eh4Vvibu-ThnUDK2jZnz0B-6RZkHC-u34Zvg_E1hnXhgmh2C3KzY" - ) - end - - desc "Upload qa version to distributes in firebase" - lane :deploy_qa_debug do - firebase_app_distribution( - app: appID_QA, - groups: " mirrorflyqa-flutter", - release_notes: change_Log, - apk_path: "../build/app/outputs/flutter-apk/app-qa-debug.apk", - firebase_cli_token: "1//0gfTJ_oWJ0mHNCgYIARAAGBASNwF-L9IrYZM4cUIV5EB8gVnSvtMC6Q7aAtgrgG8R1ybhSY1Np_5r5UuZu28N144_weOQDyONcW4", - ) - end - -end diff --git a/android/fastlane/Pluginfile b/android/fastlane/Pluginfile deleted file mode 100644 index b18539bc..00000000 --- a/android/fastlane/Pluginfile +++ /dev/null @@ -1,5 +0,0 @@ -# Autogenerated by fastlane -# -# Ensure this file is checked in to source control! - -gem 'fastlane-plugin-firebase_app_distribution' diff --git a/android/fastlane/README.md b/android/fastlane/README.md deleted file mode 100644 index 9c4c3556..00000000 --- a/android/fastlane/README.md +++ /dev/null @@ -1,40 +0,0 @@ -fastlane documentation ----- - -# Installation - -Make sure you have the latest version of the Xcode command line tools installed: - -```sh -xcode-select --install -``` - -For _fastlane_ installation instructions, see [Installing _fastlane_](https://docs.fastlane.tools/#installing-fastlane) - -# Available Actions - -## Android - -### android deploy_dev_debug - -```sh -[bundle exec] fastlane android deploy_dev -``` - -Upload dev version to distributes in firebase - -### android deploy_qa_debug - -```sh -[bundle exec] fastlane android deploy_qa -``` - -Upload dev version to distributes in firebase - ----- - -This README.md is auto-generated and will be re-generated every time [_fastlane_](https://fastlane.tools) is run. - -More information about _fastlane_ can be found on [fastlane.tools](https://fastlane.tools). - -The documentation of _fastlane_ can be found on [docs.fastlane.tools](https://docs.fastlane.tools). diff --git a/android/fastlane/report.xml b/android/fastlane/report.xml deleted file mode 100644 index 84b06c14..00000000 --- a/android/fastlane/report.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/ios/FlutterNotificationExtnsion/FlutterNotificationExtnsion.entitlements b/ios/FlutterNotificationExtnsion/FlutterNotificationExtnsion.entitlements deleted file mode 100644 index 636d3097..00000000 --- a/ios/FlutterNotificationExtnsion/FlutterNotificationExtnsion.entitlements +++ /dev/null @@ -1,10 +0,0 @@ - - - - - com.apple.security.application-groups - - group.com.mirrorfly.qa - - - diff --git a/ios/FlutterNotificationExtnsion/Info.plist b/ios/FlutterNotificationExtnsion/Info.plist deleted file mode 100644 index 57421ebf..00000000 --- a/ios/FlutterNotificationExtnsion/Info.plist +++ /dev/null @@ -1,13 +0,0 @@ - - - - - NSExtension - - NSExtensionPointIdentifier - com.apple.usernotifications.service - NSExtensionPrincipalClass - $(PRODUCT_MODULE_NAME).NotificationService - - - diff --git a/ios/FlutterNotificationExtnsion/NotificationService.swift b/ios/FlutterNotificationExtnsion/NotificationService.swift deleted file mode 100644 index 4a4206ac..00000000 --- a/ios/FlutterNotificationExtnsion/NotificationService.swift +++ /dev/null @@ -1,151 +0,0 @@ -// -// NotificationService.swift -// FlutterNotificationExtnsion -// -// Created by User on 20/12/22. -// - -import UserNotifications - -import FlyXmpp -import FlyCore -import FlyCommon -import AVFoundation -import FlyDatabase -import AudioToolbox - -//let BASE_URL = "https://api-preprod-sandbox.mirrorfly.com/api/v1/" -let BASE_URL = "https://api-uikit-qa.contus.us/api/v1/" -//let LICENSE_KEY = "lu3Om85JYSghcsB6vgVoSgTlSQArL5" -let LICENSE_KEY = "ckIjaccWBoMNvxdbql8LJ2dmKqT5bp" - -let CONTAINER_ID = "group.com.mirrorfly.qa" - -let IS_LIVE = false - -let APP_NAME = "UiKit" - -class NotificationService: UNNotificationServiceExtension { - - var contentHandler: ((UNNotificationContent) -> Void)? - var bestAttemptContent: UNMutableNotificationContent? - - var notificationIDs = [String]() - - override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { - self.contentHandler = contentHandler - bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) - let payloadType = bestAttemptContent?.userInfo["type"] as? String - try? ChatSDK.Builder.setAppGroupContainerID(containerID: CONTAINER_ID) - .isTrialLicense(isTrial: !IS_LIVE) - .setLicenseKey(key: LICENSE_KEY) - .setDomainBaseUrl(baseUrl: BASE_URL) - .buildAndInitialize() - print("#push-api withContentHandler received") - if payloadType == "media_call" { -// NotificationExtensionSupport.shared.didReceiveNotificationRequest(request.content.mutableCopy() as? UNMutableNotificationContent, appName: FlyDefaults.appName, onCompletion: { [self] bestAttemptContent in -// if FlyDefaults.hideNotificationContent{ -// bestAttemptContent?.title = FlyDefaults.appName -// }else{ -// if let userInfo = bestAttemptContent?.userInfo["message_id"] { -// bestAttemptContent?.title = encryptDecryptData(key: userInfo as? String ?? "", data: bestAttemptContent?.title ?? "", encrypt: false) -// print("Push Show title: \(bestAttemptContent?.title ?? "") body: \(bestAttemptContent?.body ?? ""), ID - \(userInfo)") -// } -// } -// self.bestAttemptContent = bestAttemptContent -// contentHandler(self.bestAttemptContent!) -// }) - } else if payloadType == "adminblock" { - ChatSDK.Builder.initializeDelegate() - NotificationMessageSupport.shared.handleAdminBlockNotification(request.content.mutableCopy() as? UNMutableNotificationContent) { bestAttemptContent in - contentHandler(bestAttemptContent!) - } - } - else { - /// Handle Push messages - ChatSDK.Builder.initializeDelegate() - NotificationMessageSupport.shared.didReceiveNotificationRequest(request.content.mutableCopy() as? UNMutableNotificationContent, onCompletion: { [self] bestAttemptContents in - FlyLog.DLog(param1: "#notification request ID", param2: "\(request.identifier)") - let center = UNUserNotificationCenter.current() - let (messageCount, chatCount) = FlyDatabaseController.shared.recentManager.getUnreadMessageAndChatCountForUnmutedUsers() - if FlyDefaults.hideNotificationContent{ - var titleContent = emptyString() - if chatCount == 1{ - titleContent = "\(messageCount) \(messageCount == 1 ? "message" : "messages")" - } else { - titleContent = "\(messageCount) messages from \(chatCount) chats" - } - bestAttemptContents?.title = FlyDefaults.appName + " (\(titleContent))" - bestAttemptContents?.body = "New Message" - } else { - if let userInfo = bestAttemptContents?.userInfo["message_id"] { - print("Push Show title: \(bestAttemptContents?.title ?? "") body: \(bestAttemptContents?.body ?? ""), ID - \(userInfo)") - FlyLog.DLog(param1: "NotificationMessageSupport id ", param2: "\(bestAttemptContents?.title ?? "") body: \(bestAttemptContents?.body ?? "")") - } - } -// bestAttemptContent?.badge = messageCount as? NSNumber -// self.bestAttemptContent = bestAttemptContent -// contentHandler(self.bestAttemptContent!) -// FlyDefaults.lastNotificationId = request.identifier - - var canVibrate = true - if !FlyCoreController.shared.isContactMuted(jid: bestAttemptContents?.userInfo["from_user"] as? String ?? "") || !(FlyDefaults.isArchivedChatEnabled && ChatManager.getRechtChat(jid: bestAttemptContents?.userInfo["from_user"] as? String ?? "")?.isChatArchived ?? false){ - bestAttemptContents?.badge = messageCount as? NSNumber - } - - let chatType = (bestAttemptContents?.userInfo["chat_type"] as? String ?? "") - let messageId = (self.bestAttemptContent?.userInfo["message_id"] as? String ?? "").components(separatedBy: ",").last ?? "" - - self.bestAttemptContent = bestAttemptContents - - if FlyDatabaseController.shared.messageManager.getMessageFor(id: messageId)?.senderUserJid == FlyDefaults.myJid && (chatType == "chat" || chatType == "normal") { - if !FlyUtils.isValidGroupJid(groupJid: FlyDatabaseController.shared.messageManager.getMessageFor(id: messageId)?.chatUserJid) { - self.bestAttemptContent?.title = "You" - } - canVibrate = false - self.bestAttemptContent?.sound = .none - } else if FlyDatabaseController.shared.messageManager.getMessageFor(id: messageId)?.senderUserJid != FlyDefaults.myJid { - if FlyCoreController.shared.isContactMuted(jid: bestAttemptContents?.userInfo["from_user"] as? String ?? "") || (FlyDefaults.isArchivedChatEnabled && ChatManager.getRechtChat(jid: bestAttemptContents?.userInfo["from_user"] as? String ?? "")?.isChatArchived ?? false) { - self.bestAttemptContent?.sound = .none - canVibrate = false - } else if !FlyDefaults.notificationSoundUrl.contains("Default") && !FlyDefaults.notificationSoundUrl.contains("None") && FlyDefaults.notificationSoundEnable { - self.bestAttemptContent?.sound = .default - } else if FlyDefaults.notificationSoundUrl.contains("Default") && FlyDefaults.notificationSoundEnable { - self.bestAttemptContent?.sound = .default - } else if FlyDefaults.notificationSoundEnable == false || FlyDefaults.notificationSoundUrl.contains("None") { - self.bestAttemptContent?.sound = nil - } - } else if self.bestAttemptContent?.userInfo["sent_from"] as? String ?? "" == FlyDefaults.myJid && self.bestAttemptContent?.userInfo["group_id"] != nil { - self.bestAttemptContent?.sound = nil - canVibrate = false - } else if self.bestAttemptContent?.userInfo["sent_from"] as? String ?? "" != FlyDefaults.myJid && self.bestAttemptContent?.userInfo["group_id"] != nil { - if !FlyDefaults.notificationSoundUrl.contains("Default") && !FlyDefaults.notificationSoundUrl.contains("None") && FlyDefaults.notificationSoundEnable { - self.bestAttemptContent?.sound = .default - } else if FlyDefaults.notificationSoundUrl.contains("Default") && FlyDefaults.notificationSoundEnable { - self.bestAttemptContent?.sound = .default - } else if FlyDefaults.notificationSoundEnable == false || FlyDefaults.notificationSoundUrl.contains("None") { - self.bestAttemptContent?.sound = nil - } - } - - if FlyDefaults.vibrationEnable && canVibrate { - AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) - } - - contentHandler(self.bestAttemptContent!) - FlyDefaults.lastNotificationId = request.identifier - - }) - } - } - - override func serviceExtensionTimeWillExpire() { - // Called just before the extension will be terminated by the system. - // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. - if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { - contentHandler(bestAttemptContent) - } - } - - -} diff --git a/ios/Podfile b/ios/Podfile index 89ac3757..9f65e8c2 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -33,38 +33,9 @@ target 'Runner' do use_modular_headers! -# pod 'libPhoneNumber-iOS' -# pod 'Alamofire' -# pod 'RealmSwift', '10.20.1' -# pod 'XMPPFramework/Swift' -# pod 'SocketRocket' -# pod 'Socket.IO-Client-Swift' -# pod 'GoogleWebRTC' -# pod 'Mirrorfly-ios-framework', :git => 'https://github.com/MirrorFly/Mirrorfly-ios-framework.git', :branch => 'pod_qa' -# pod 'Mirrorfly-ios-framework', :git => 'https://github.com/MirrorFly/Mirrorfly-ios-framework.git', :branch => 'qa' flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) end -#def notification_pods -# -## pod 'Mirrorfly-ios-framework', :git => 'https://github.com/MirrorFly/Mirrorfly-ios-framework.git', :tag => '0.0.5' -# pod 'libPhoneNumber-iOS' #, '~> 0.8' -# pod 'Alamofire' #, '~> 5.3' -# #Pods for FlyCall -# pod 'SocketRocket' -# pod 'Socket.IO-Client-Swift' # To communicte Socket I/O server -# pod 'GoogleWebRTC' # WebRTC for Calls -# pod 'RealmSwift', '10.20.1' -# pod 'XMPPFramework/Swift' -## pod 'Mirrorfly-ios-framework', :git => 'https://github.com/MirrorFly/Mirrorfly-ios-framework.git', :branch => 'master' -## flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) -# -# -#end -# -#target 'FlutterNotificationExtnsion' do -# notification_pods -#end post_install do |installer| installer.pods_project.targets.each do |target| diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index e95f9426..9c482513 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -13,7 +13,6 @@ 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 */; }; - CEB9F2DB2948F9E10080BC48 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = CEB9F2DA2948F9E10080BC48 /* GoogleService-Info.plist */; }; F7B9F37EDD0413A83048DD9E /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6F5A254ABC70ADA22C4DC0C9 /* Pods_Runner.framework */; }; /* End PBXBuildFile section */ @@ -48,7 +47,6 @@ 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 = ""; }; - CEB9F2DA2948F9E10080BC48 /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; }; CED95E2229472EC900B02558 /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; /* End PBXFileReference section */ @@ -115,7 +113,6 @@ 97C146F01CF9000F007C117D /* Runner */ = { isa = PBXGroup; children = ( - CEB9F2DA2948F9E10080BC48 /* GoogleService-Info.plist */, CED95E2229472EC900B02558 /* Runner.entitlements */, 97C146FA1CF9000F007C117D /* Main.storyboard */, 97C146FD1CF9000F007C117D /* Assets.xcassets */, @@ -196,7 +193,6 @@ files = ( 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, - CEB9F2DB2948F9E10080BC48 /* GoogleService-Info.plist in Resources */, 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, ); @@ -396,7 +392,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = com.mirrorfly.qa; + PRODUCT_BUNDLE_IDENTIFIER = com.mirrorfly.uikitflutter.qa; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = "Mirror Fly Qa Development Profile"; "PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = "Mirror Fly Qa Development Profile"; @@ -541,7 +537,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = com.mirrorfly.qa; + PRODUCT_BUNDLE_IDENTIFIER = com.mirrorfly.uikitflutter.qa; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = "Mirror Fly Qa Development Profile"; "PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = "Mirror Fly Qa Development Profile"; @@ -578,7 +574,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = com.mirrorfly.qa; + PRODUCT_BUNDLE_IDENTIFIER = com.mirrorfly.uikitflutter.qa; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = "Mirror Fly Qa Development Profile"; "PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = "Mirror Fly Qa Development Profile"; diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index b2b2442f..48d9e8bf 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -1,51 +1,28 @@ import UIKit import Flutter -import FlyCore -import FlyCommon -import GoogleMaps -import UserNotifications -import FirebaseAuth -import Firebase +// import FlyCore +// import FlyCommon + import GoogleMaps +// import UserNotifications +// import FirebaseAuth +// import Firebase @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate{ - - - var postNotificationdidEnterBackground : NotificationCenter? = nil + override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { - let _ : FlutterViewController = window?.rootViewController as! FlutterViewController - -// GMSServices.provideAPIKey(googleApiKey) - - // MARK:- Push Notification -// clearPushNotifications() -// registerForPushNotifications() + GMSServices.provideAPIKey("YOUR GOOGLE KEY HERE") - FirebaseApp.configure() - if #available(iOS 10.0, *) { - // For iOS 10 display notification (sent via APNS) - UNUserNotificationCenter.current().delegate = self - - let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] - UNUserNotificationCenter.current().requestAuthorization( - options: authOptions, - completionHandler: { val, error in - } - ) - } else { - let settings: UIUserNotificationSettings = - UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) - application.registerUserNotificationSettings(settings) - } + let _ : FlutterViewController = window?.rootViewController as! FlutterViewController + - application.registerForRemoteNotifications() GeneratedPluginRegistrant.register(with: self) @@ -56,90 +33,5 @@ import Firebase } -extension AppDelegate { - /// Register for APNS Notifications - func registerForPushNotifications() { - print("###Registering push notification") - UNUserNotificationCenter.current().delegate = self - let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] - UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { granted, error in - if granted { - self.getNotificationSettings() - DispatchQueue.main.async { - UIApplication.shared.registerForRemoteNotifications() -// FlyUtils.setBaseUrl(BASE_URL) - } - } - } -// registerForVOIPNotifications() - } - /// This method is used to clear notifications and badge count - func clearPushNotifications() { - -// print("###Clearing push notification") -// UNUserNotificationCenter.current().removeAllDeliveredNotifications() -// UNUserNotificationCenter.current().removeAllPendingNotificationRequests() - } - - override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { - //Mark:- Added for swizzling - Auth.auth().setAPNSToken(deviceToken, type: .unknown) - - print("###didRegisterForRemoteNotificationsWithDeviceToken") - - let token = deviceToken.map { String(format: "%.2hhx", $0) }.joined() - if token.count == 0 { - print("Push Status Credentials APNS:") - return; - } - print("#token appDelegate \(token)") - print("#token application DT => \(token)") -// VOIPManager.sharedInstance.saveAPNSToken(token: token) -// Utility.saveInPreference(key: googleToken, value: token) -// VOIPManager.sharedInstance.updateDeviceToken() -// return super.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken) - } - - override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { - print("###didFailToRegisterForRemoteNotificationsWithError") - print("Push didFailToRegisterForRemoteNotificationsWithError)") - } - override func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { - completionHandler([.alert, .sound]) - } - override func application(_ application: UIApplication, didReceiveRemoteNotification notification: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { - print("Push userInfo \(notification)") - if Auth.auth().canHandleNotification(notification) { - completionHandler(.noData) - return - }else{ - print("###canHandleNotification issue") - } - - } - func getNotificationSettings() { - UNUserNotificationCenter.current().getNotificationSettings { settings in - print("Notification settings: \(settings)") - } - } - override func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { - print("###userNotificationCenter withCompletionHandler") - let chatId = response.notification.request.content.threadIdentifier - print("chat ID ---> \(chatId)") - if let profileDetails = ContactManager.shared.getUserProfileDetails(for: chatId) , chatId != FlyDefaults.myJid{ -// Utility.saveInPreference(key: notificationUserJid, value: profileDetails.jid ?? "") - - } - -// if response.notification.request.content.threadIdentifier.contains(XMPP_DOMAIN){ -// if FlyDefaults.isBlockedByAdmin { -// navigateToBlockedScreen() -// } else { -// navigateToChatScreen(chatId: response.notification.request.content.threadIdentifier, completionHandler: completionHandler) -// } -// } - } - -} diff --git a/ios/Runner/Commons.swift b/ios/Runner/Commons.swift deleted file mode 100644 index c8f2ad9f..00000000 --- a/ios/Runner/Commons.swift +++ /dev/null @@ -1,29 +0,0 @@ -// -// Commons.swift -// Runner -// -// Created by ManiVendhan on 09/11/22. -// - -import Foundation - - -let isLoggedIn = "isLoggedIn" -let muteNotification = "muteNotification" -let didEnterBackground = "DidEnterBackground" -let isProfileSaved = "isProfileSaved" -let googleToken = "googleToken" -let notificationUserJid = "" -let voipToken = "voipToken" - -class Commons{ - - - static func json(from object:Any) -> String? { - guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else { - return nil - } - return String(data: data, encoding: String.Encoding.utf8) - } - -} diff --git a/ios/Runner/FlyBaseController.swift b/ios/Runner/FlyBaseController.swift deleted file mode 100644 index e69e1d38..00000000 --- a/ios/Runner/FlyBaseController.swift +++ /dev/null @@ -1,1308 +0,0 @@ -// -// FlyBaseController.swift -// Runner -// -// Created by ManiVendhan on 10/11/22. -// - -import Foundation -import Flutter -import FlyCore -import FlyCommon - - -let MIRRORFLY_METHOD_CHANNEL = "contus.mirrorfly/sdkCall" - -let MESSAGE_ONRECEIVED_CHANNEL = "contus.mirrorfly/onMessageReceived" -let MESSAGE_STATUS_UPDATED_CHANNEL = "contus.mirrorfly/onMessageStatusUpdated" -let MEDIA_STATUS_UPDATED_CHANNEL = "contus.mirrorfly/onMediaStatusUpdated" -let UPLOAD_DOWNLOAD_PROGRESS_CHANGED_CHANNEL = - "contus.mirrorfly/onUploadDownloadProgressChanged" -let SHOW_UPDATE_CANCEL_NOTIFICTION_CHANNEL = - "contus.mirrorfly/showOrUpdateOrCancelNotification"//dependency issue - -let onGroupProfileFetched_channel = "contus.mirrorfly/onGroupProfileFetched" -let onNewGroupCreated_channel = "contus.mirrorfly/onNewGroupCreated" -let onGroupProfileUpdated_channel = "contus.mirrorfly/onGroupProfileUpdated" -let onNewMemberAddedToGroup_channel = "contus.mirrorfly/onNewMemberAddedToGroup" -let onMemberRemovedFromGroup_channel = "contus.mirrorfly/onMemberRemovedFromGroup" -let onFetchingGroupMembersCompleted_channel = - "contus.mirrorfly/onFetchingGroupMembersCompleted" -let onDeleteGroup_channel = "contus.mirrorfly/onDeleteGroup"//not found -let onFetchingGroupListCompleted_channel = - "contus.mirrorfly/onFetchingGroupListCompleted"//not found -let onMemberMadeAsAdmin_channel = "contus.mirrorfly/onMemberMadeAsAdmin" -let onMemberRemovedAsAdmin_channel = "contus.mirrorfly/onMemberRemovedAsAdmin" -let onLeftFromGroup_channel = "contus.mirrorfly/onLeftFromGroup" -let onGroupNotificationMessage_channel = "contus.mirrorfly/onGroupNotificationMessage"//not found -let onGroupDeletedLocally_channel = "contus.mirrorfly/onGroupDeletedLocally" - -let blockedThisUser_channel = "contus.mirrorfly/blockedThisUser" -let myProfileUpdated_channel = "contus.mirrorfly/myProfileUpdated" -let onAdminBlockedOtherUser_channel = "contus.mirrorfly/onAdminBlockedOtherUser" -let onAdminBlockedUser_channel = "contus.mirrorfly/onAdminBlockedUser" -let onContactSyncComplete_channel = "contus.mirrorfly/onContactSyncComplete"//need to verify with ios team -let onLoggedOut_channel = "contus.mirrorfly/onLoggedOut" -let unblockedThisUser_channel = "contus.mirrorfly/unblockedThisUser" -let userBlockedMe_channel = "contus.mirrorfly/userBlockedMe" -let userCameOnline_channel = "contus.mirrorfly/userCameOnline" -let userDeletedHisProfile_channel = "contus.mirrorfly/userDeletedHisProfile" -let userProfileFetched_channel = "contus.mirrorfly/userProfileFetched" -let userUnBlockedMe_channel = "contus.mirrorfly/userUnBlockedMe" -let userUpdatedHisProfile_channel = "contus.mirrorfly/userUpdatedHisProfile" -let userWentOffline_channel = "contus.mirrorfly/userWentOffline" -let usersIBlockedListFetched_channel = "contus.mirrorfly/usersIBlockedListFetched" -let usersProfilesFetched_channel = "contus.mirrorfly/usersProfilesFetched" -let usersWhoBlockedMeListFetched_channel = "contus.mirrorfly/usersWhoBlockedMeListFetched" -let onConnected_channel = "contus.mirrorfly/onConnected" -let onDisconnected_channel = "contus.mirrorfly/onDisconnected" -let onConnectionNotAuthorized_channel = "contus.mirrorfly/onConnectionNotAuthorized" -let connectionFailed_channel = "contus.mirrorfly/connectionFailed" -let connectionSuccess_channel = "contus.mirrorfly/connectionSuccess" -let onWebChatPasswordChanged_channel = "contus.mirrorfly/onWebChatPasswordChanged" -let setTypingStatus_channel = "contus.mirrorfly/setTypingStatus" -let onChatTypingStatus_channel = "contus.mirrorfly/onChatTypingStatus" -let onGroupTypingStatus_channel = "contus.mirrorfly/onGroupTypingStatus" -let onFailure_channel = "contus.mirrorfly/onFailure" -let onProgressChanged_channel = "contus.mirrorfly/onProgressChanged" -let onSuccess_channel = "contus.mirrorfly/onSuccess" - -var networkConnected = false; - - -class FlyBaseController: NSObject{ - - - var messageReceivedStreamHandler: MessageReceivedStreamHandler? - var messageStatusUpdatedStreamHandler: MessageStatusUpdatedStreamHandler? - var mediaStatusUpdatedStreamHandler: MediaStatusUpdatedStreamHandler? - var uploadDownloadProgressChangedStreamHandler: UploadDownloadProgressChangedStreamHandler? - var showOrUpdateOrCancelNotificationStreamHandler: ShowOrUpdateOrCancelNotificationStreamHandler? - var groupProfileFetchedStreamHandler: GroupProfileFetchedStreamHandler? - var newGroupCreatedStreamHandler: NewGroupCreatedStreamHandler? - var groupProfileUpdatedStreamHandler: GroupProfileUpdatedStreamHandler? - var newMemberAddedToGroupStreamHandler: NewMemberAddedToGroupStreamHandler? - var memberRemovedFromGroupStreamHandler: MemberRemovedFromGroupStreamHandler? - var fetchingGroupMembersCompletedStreamHandler: FetchingGroupMembersCompletedStreamHandler? - var deleteGroupStreamHandler: DeleteGroupStreamHandler? - var fetchingGroupListCompletedStreamHandler: FetchingGroupListCompletedStreamHandler?// - var memberMadeAsAdminStreamHandler: MemberMadeAsAdminStreamHandler? - var memberRemovedAsAdminStreamHandler: MemberRemovedAsAdminStreamHandler? - var userWentOfflineStreamHandler: UserWentOfflineStreamHandler? - - var leftFromGroupStreamHandler: LeftFromGroupStreamHandler? - var onGroupNotificationMessageStreamHandler: GroupNotificationMessageStreamHandler? - var onGroupDeletedLocallyStreamHandler: GroupDeletedLocallyStreamHandler? - var blockedThisUserStreamHandler: BlockedThisUserStreamHandler? - var myProfileUpdatedStreamHandler: MyProfileUpdatedStreamHandler? - var onAdminBlockedOtherUserStreamHandler: OnAdminBlockedOtherUserStreamHandler? - var onAdminBlockedUserStreamHandler: OnAdminBlockedUserStreamHandler? - var onContactSyncCompleteStreamHandler: OnContactSyncCompleteStreamHandler? - var onLoggedOutStreamHandler: OnLoggedOutStreamHandler? - var unblockedThisUserStreamHandler: UnblockedThisUserStreamHandler? - var userBlockedMeStreamHandler: UserBlockedMeStreamHandler? - var userCameOnlineStreamHandler: UserCameOnlineStreamHandler? - var userDeletedHisProfileStreamHandler: UserDeletedHisProfileStreamHandler? - var userProfileFetchedStreamHandler: UserProfileFetchedStreamHandler? - var userUnBlockedMeStreamHandler: UserUnBlockedMeStreamHandler? - var userUpdatedHisProfileStreamHandler: UserUpdatedHisProfileStreamHandler? - var usersIBlockedListFetchedStreamHandler: UsersIBlockedListFetchedStreamHandler? - var usersProfilesFetchedStreamHandler: UsersProfilesFetchedStreamHandler? - var usersWhoBlockedMeListFetchedStreamHandler: UsersWhoBlockedMeListFetchedStreamHandler? - var onConnectedStreamHandler: OnConnectedStreamHandler? - var onDisconnectedStreamHandler: OnDisconnectedStreamHandler? - var onConnectionNotAuthorizedStreamHandler: OnConnectionNotAuthorizedStreamHandler? - var connectionFailedStreamHandler: ConnectionFailedStreamHandler? - var connectionSuccessStreamHandler: ConnectionSuccessStreamHandler? - var onWebChatPasswordChangedStreamHandler: OnWebChatPasswordChangedStreamHandler? - var onFailureStreamHandler: OnFailureStreamHandler? - var onProgressChangedStreamHandler: OnProgressChangedStreamHandler? - var onSuccessStreamHandler: OnSuccessStreamHandler? - - var onChatTypingStatusStreamHandler: OnChatTypingStatusStreamHandler? - var onsetTypingStatusStreamHandler: OnsetTypingStatusStreamHandler? - var onGroupTypingStatusStreamHandler: OnGroupTypingStatusStreamHandler? - - - func initSDK(controller: FlutterViewController, licenseKey: String, isTrial: Bool, baseUrl: String, containerID: String){ - - print("Initializing SDK") - - let groupConfig = try? GroupConfig.Builder.enableGroupCreation(groupCreation: true) - .onlyAdminCanAddOrRemoveMembers(adminOnly: true) - .setMaximumMembersInAGroup(membersCount: 200) - .build() - assert(groupConfig != nil) - - try? ChatSDK.Builder.setAppGroupContainerID(containerID: containerID) - .setLicenseKey(key: licenseKey) - .isTrialLicense(isTrial: isTrial) - .setDomainBaseUrl(baseUrl: baseUrl) - .setGroupConfiguration(groupConfig: groupConfig!) - .buildAndInitialize() - - - - let methodChannel = FlutterMethodChannel(name: MIRRORFLY_METHOD_CHANNEL, binaryMessenger: controller.binaryMessenger) - - prepareMethodHandler(methodChannel: methodChannel) - - registerEventChannels(controller: controller) - - ChatManager.shared.logoutDelegate = self - FlyMessenger.shared.messageEventsDelegate = self - ChatManager.shared.messageEventsDelegate = self - GroupManager.shared.groupDelegate = self - ChatManager.shared.connectionDelegate = self - ChatManager.shared.adminBlockCurrentUserDelegate = self - ChatManager.shared.typingStatusDelegate = self - - ContactManager.shared.profileDelegate = self - ChatManager.shared.adminBlockDelegate = self - ChatManager.shared.availableFeaturesDelegate = self - BackupManager.shared.backupDelegate = self - BackupManager.shared.restoreDelegate = self - ChatManager.disableLocalNotification() -// iCloudmanager.iCloudDelegate = self - - NetworkMonitor.shared.startMonitoring() - NotificationCenter.default.addObserver(self, selector: #selector(showOfflineDeviceUI(notification:)), name: NSNotification.Name.connectivityStatus, object: nil) - - } - - func applicationWillTerminate(){ - NetworkMonitor.shared.stopMonitoring() - NotificationCenter.default.removeObserver(self, name: NSNotification.Name.connectivityStatus, object: nil) - } - - @objc func showOfflineDeviceUI(notification: Notification) { - print("AppDelegate Internet listener called") - if NetworkMonitor.shared.isConnected { -// if(!networkConnected){ - print("calling Auto Download") - ChatManager.shared.startAutoDownload() -// } - networkConnected = true; - } else { - networkConnected = false; - } - } - - func registerEventChannels(controller: FlutterViewController){ - if (self.messageReceivedStreamHandler == nil) { - self.messageReceivedStreamHandler = MessageReceivedStreamHandler() - } - - FlutterEventChannel(name: MESSAGE_ONRECEIVED_CHANNEL, binaryMessenger: controller.binaryMessenger).setStreamHandler((self.messageReceivedStreamHandler as! FlutterStreamHandler & NSObjectProtocol)) - - if (self.messageStatusUpdatedStreamHandler == nil) { - self.messageStatusUpdatedStreamHandler = MessageStatusUpdatedStreamHandler() - } - FlutterEventChannel(name: MESSAGE_STATUS_UPDATED_CHANNEL, binaryMessenger: controller.binaryMessenger).setStreamHandler((self.messageStatusUpdatedStreamHandler as! FlutterStreamHandler & NSObjectProtocol)) - - if (self.mediaStatusUpdatedStreamHandler == nil) { - self.mediaStatusUpdatedStreamHandler = MediaStatusUpdatedStreamHandler() - } - - FlutterEventChannel(name: MEDIA_STATUS_UPDATED_CHANNEL, binaryMessenger: controller.binaryMessenger).setStreamHandler((self.mediaStatusUpdatedStreamHandler as! FlutterStreamHandler & NSObjectProtocol)) - - if (self.onAdminBlockedOtherUserStreamHandler == nil) { - self.onAdminBlockedOtherUserStreamHandler = OnAdminBlockedOtherUserStreamHandler() - } - - FlutterEventChannel(name: onAdminBlockedOtherUser_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler((self.onAdminBlockedOtherUserStreamHandler as! FlutterStreamHandler & NSObjectProtocol)) - - if (self.uploadDownloadProgressChangedStreamHandler == nil) { - self.uploadDownloadProgressChangedStreamHandler = UploadDownloadProgressChangedStreamHandler() - } - FlutterEventChannel(name: UPLOAD_DOWNLOAD_PROGRESS_CHANGED_CHANNEL, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.uploadDownloadProgressChangedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.showOrUpdateOrCancelNotificationStreamHandler == nil) { - self.showOrUpdateOrCancelNotificationStreamHandler = ShowOrUpdateOrCancelNotificationStreamHandler() - } - - FlutterEventChannel(name: SHOW_UPDATE_CANCEL_NOTIFICTION_CHANNEL, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.showOrUpdateOrCancelNotificationStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.groupProfileFetchedStreamHandler == nil) { - self.groupProfileFetchedStreamHandler = GroupProfileFetchedStreamHandler() - } - - FlutterEventChannel(name: onGroupProfileFetched_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.groupProfileFetchedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.newGroupCreatedStreamHandler == nil) { - self.newGroupCreatedStreamHandler = NewGroupCreatedStreamHandler() - } - - FlutterEventChannel(name: onNewGroupCreated_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.newGroupCreatedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.groupProfileUpdatedStreamHandler == nil) { - self.groupProfileUpdatedStreamHandler = GroupProfileUpdatedStreamHandler() - } - - FlutterEventChannel(name: onGroupProfileUpdated_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.groupProfileUpdatedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.newMemberAddedToGroupStreamHandler == nil) { - self.newMemberAddedToGroupStreamHandler = NewMemberAddedToGroupStreamHandler() - } - - FlutterEventChannel(name: onNewMemberAddedToGroup_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.newMemberAddedToGroupStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - - if (self.memberRemovedFromGroupStreamHandler == nil) { - self.memberRemovedFromGroupStreamHandler = MemberRemovedFromGroupStreamHandler() - } - - FlutterEventChannel(name: onMemberRemovedFromGroup_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.memberRemovedFromGroupStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.fetchingGroupMembersCompletedStreamHandler == nil) { - self.fetchingGroupMembersCompletedStreamHandler = FetchingGroupMembersCompletedStreamHandler() - } - - FlutterEventChannel(name: onFetchingGroupMembersCompleted_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.fetchingGroupMembersCompletedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.deleteGroupStreamHandler == nil) { - self.deleteGroupStreamHandler = DeleteGroupStreamHandler() - } - - FlutterEventChannel(name: onDeleteGroup_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.deleteGroupStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.fetchingGroupListCompletedStreamHandler == nil) { - self.fetchingGroupListCompletedStreamHandler = FetchingGroupListCompletedStreamHandler() - } - - - FlutterEventChannel(name: onFetchingGroupListCompleted_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.fetchingGroupListCompletedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.memberMadeAsAdminStreamHandler == nil) { - self.memberMadeAsAdminStreamHandler = MemberMadeAsAdminStreamHandler() - } - - FlutterEventChannel(name: onMemberMadeAsAdmin_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.memberMadeAsAdminStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.memberRemovedAsAdminStreamHandler == nil) { - self.memberRemovedAsAdminStreamHandler = MemberRemovedAsAdminStreamHandler() - } - - FlutterEventChannel(name: onMemberRemovedAsAdmin_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.memberRemovedAsAdminStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.leftFromGroupStreamHandler == nil) { - self.leftFromGroupStreamHandler = LeftFromGroupStreamHandler() - } - - FlutterEventChannel(name: onLeftFromGroup_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.leftFromGroupStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.userWentOfflineStreamHandler == nil) { - self.userWentOfflineStreamHandler = UserWentOfflineStreamHandler() - } - - FlutterEventChannel(name: userWentOffline_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.userWentOfflineStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - - if (self.onGroupNotificationMessageStreamHandler == nil) { - self.onGroupNotificationMessageStreamHandler = GroupNotificationMessageStreamHandler() - } - - FlutterEventChannel(name: onGroupNotificationMessage_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.onGroupNotificationMessageStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.onGroupDeletedLocallyStreamHandler == nil) { - self.onGroupDeletedLocallyStreamHandler = GroupDeletedLocallyStreamHandler() - } - - FlutterEventChannel(name: onGroupDeletedLocally_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.onGroupDeletedLocallyStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.blockedThisUserStreamHandler == nil) { - self.blockedThisUserStreamHandler = BlockedThisUserStreamHandler() - } - - FlutterEventChannel(name: blockedThisUser_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.blockedThisUserStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - - if (self.myProfileUpdatedStreamHandler == nil) { - self.myProfileUpdatedStreamHandler = MyProfileUpdatedStreamHandler() - } - - FlutterEventChannel(name: myProfileUpdated_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.myProfileUpdatedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.onAdminBlockedUserStreamHandler == nil) { - self.onAdminBlockedUserStreamHandler = OnAdminBlockedUserStreamHandler() - } - - FlutterEventChannel(name: onAdminBlockedUser_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.onAdminBlockedUserStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - - if (self.onContactSyncCompleteStreamHandler == nil) { - self.onContactSyncCompleteStreamHandler = OnContactSyncCompleteStreamHandler() - } - - FlutterEventChannel(name: onContactSyncComplete_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.onContactSyncCompleteStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.onLoggedOutStreamHandler == nil) { - self.onLoggedOutStreamHandler = OnLoggedOutStreamHandler() - } - - FlutterEventChannel(name: onLoggedOut_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.onLoggedOutStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - - if (self.unblockedThisUserStreamHandler == nil) { - self.unblockedThisUserStreamHandler = UnblockedThisUserStreamHandler() - } - - FlutterEventChannel(name: unblockedThisUser_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.unblockedThisUserStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.userBlockedMeStreamHandler == nil) { - self.userBlockedMeStreamHandler = UserBlockedMeStreamHandler() - } - - FlutterEventChannel(name: userBlockedMe_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.userBlockedMeStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - - if (self.userCameOnlineStreamHandler == nil) { - self.userCameOnlineStreamHandler = UserCameOnlineStreamHandler() - } - - FlutterEventChannel(name: userCameOnline_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.userCameOnlineStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - - if (self.userDeletedHisProfileStreamHandler == nil) { - self.userDeletedHisProfileStreamHandler = UserDeletedHisProfileStreamHandler() - } - - FlutterEventChannel(name: userDeletedHisProfile_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.userDeletedHisProfileStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.userProfileFetchedStreamHandler == nil) { - self.userProfileFetchedStreamHandler = UserProfileFetchedStreamHandler() - } - - FlutterEventChannel(name: userProfileFetched_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.userProfileFetchedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - - if (self.userUnBlockedMeStreamHandler == nil) { - self.userUnBlockedMeStreamHandler = UserUnBlockedMeStreamHandler() - } - - FlutterEventChannel(name: userUnBlockedMe_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.userUnBlockedMeStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.userUpdatedHisProfileStreamHandler == nil) { - self.userUpdatedHisProfileStreamHandler = UserUpdatedHisProfileStreamHandler() - } - - FlutterEventChannel(name: userUpdatedHisProfile_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.userUpdatedHisProfileStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.usersIBlockedListFetchedStreamHandler == nil) { - self.usersIBlockedListFetchedStreamHandler = UsersIBlockedListFetchedStreamHandler() - } - - FlutterEventChannel(name: usersIBlockedListFetched_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.usersIBlockedListFetchedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - - - if (self.usersProfilesFetchedStreamHandler == nil) { - self.usersProfilesFetchedStreamHandler = UsersProfilesFetchedStreamHandler() - } - - FlutterEventChannel(name: userProfileFetched_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.usersProfilesFetchedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - - - if (self.usersWhoBlockedMeListFetchedStreamHandler == nil) { - self.usersWhoBlockedMeListFetchedStreamHandler = UsersWhoBlockedMeListFetchedStreamHandler() - } - - FlutterEventChannel(name: usersWhoBlockedMeListFetched_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.usersWhoBlockedMeListFetchedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - - if (self.onConnectedStreamHandler == nil) { - self.onConnectedStreamHandler = OnConnectedStreamHandler() - } - - FlutterEventChannel(name: onConnected_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.onConnectedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.onDisconnectedStreamHandler == nil) { - self.onDisconnectedStreamHandler = OnDisconnectedStreamHandler() - } - - FlutterEventChannel(name: onDisconnected_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.onDisconnectedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.onConnectionNotAuthorizedStreamHandler == nil) { - self.onConnectionNotAuthorizedStreamHandler = OnConnectionNotAuthorizedStreamHandler() - } - - FlutterEventChannel(name: onConnectionNotAuthorized_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.onConnectionNotAuthorizedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - - if (self.connectionFailedStreamHandler == nil) { - self.connectionFailedStreamHandler = ConnectionFailedStreamHandler() - } - - FlutterEventChannel(name: connectionFailed_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.connectionFailedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - - if (self.connectionSuccessStreamHandler == nil) { - self.connectionSuccessStreamHandler = ConnectionSuccessStreamHandler() - } - - FlutterEventChannel(name: connectionSuccess_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.connectionSuccessStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - - if (self.onWebChatPasswordChangedStreamHandler == nil) { - self.onWebChatPasswordChangedStreamHandler = OnWebChatPasswordChangedStreamHandler() - } - - FlutterEventChannel(name: onWebChatPasswordChanged_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.onWebChatPasswordChangedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.onFailureStreamHandler == nil) { - self.onFailureStreamHandler = OnFailureStreamHandler() - } - - FlutterEventChannel(name: onFailure_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.onFailureStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.onProgressChangedStreamHandler == nil) { - self.onProgressChangedStreamHandler = OnProgressChangedStreamHandler() - } - - FlutterEventChannel(name: onProgressChanged_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.onProgressChangedStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - if (self.onSuccessStreamHandler == nil) { - self.onSuccessStreamHandler = OnSuccessStreamHandler() - } - - FlutterEventChannel(name: onSuccess_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler(self.onSuccessStreamHandler as? FlutterStreamHandler & NSObjectProtocol) - - - if (self.onChatTypingStatusStreamHandler == nil) { - self.onChatTypingStatusStreamHandler = OnChatTypingStatusStreamHandler() - } - - FlutterEventChannel(name: onChatTypingStatus_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler((self.onChatTypingStatusStreamHandler!)) - - if (self.onsetTypingStatusStreamHandler == nil) { - self.onsetTypingStatusStreamHandler = OnsetTypingStatusStreamHandler() - } - - FlutterEventChannel(name: setTypingStatus_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler((self.onsetTypingStatusStreamHandler!)) - - if (self.onGroupTypingStatusStreamHandler == nil) { - self.onGroupTypingStatusStreamHandler = OnGroupTypingStatusStreamHandler() - } - - FlutterEventChannel(name: onGroupTypingStatus_channel, binaryMessenger: controller.binaryMessenger).setStreamHandler((self.onGroupTypingStatusStreamHandler!)) - - - } - func prepareMethodHandler(methodChannel: FlutterMethodChannel){ - methodChannel.setMethodCallHandler({ - (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in - switch call.method { - case "syncContacts": - FlySdkMethodCalls.syncContacts(call: call, result: result) - case "contactSyncStateValue": - FlySdkMethodCalls.contactSyncStateValue(call: call, result: result) - case "contactSyncState": - FlySdkMethodCalls.contactSyncState(call: call, result: result) - case "revokeContactSync": - FlySdkMethodCalls.revokeContactSync(call: call, result: result) - case "getUsersWhoBlockedMe": - FlySdkMethodCalls.getUsersWhoBlockedMe(call: call, result: result) - case "getUnKnownUserProfiles": - FlySdkMethodCalls.getUnKnownUserProfiles(call: call, result: result) - case "getMyProfileStatus": - FlySdkMethodCalls.getMyProfileStatus(call: call, result: result) - case "getMyBusyStatus": - FlySdkMethodCalls.getMyBusyStatus(call: call, result: result) - case "setMyBusyStatus": - FlySdkMethodCalls.setMyBusyStatus(call: call, result: result) - case "enableDisableBusyStatus": - FlySdkMethodCalls.enableDisableBusyStatus(call: call, result: result) - case "getBusyStatusList": - FlySdkMethodCalls.getBusyStatusList(call: call, result: result) - case "deleteProfileStatus": - FlySdkMethodCalls.deleteProfileStatus(call: call, result: result) - case "deleteBusyStatus": - FlySdkMethodCalls.deleteBusyStatus(call: call, result: result) - case "enableDisableHideLastSeen": - FlySdkMethodCalls.enableDisableHideLastSeen(call: call, result: result) - case "isHideLastSeenEnabled": - FlySdkMethodCalls.isHideLastSeenEnabled(call: call, result: result) - case "deleteMessagesForMe": - FlySdkMethodCalls.deleteMessagesForMe(call: call, result: result) - case "deleteMessagesForEveryone": - FlySdkMethodCalls.deleteMessagesForEveryone(call: call, result: result) - case "markAsRead": - FlySdkMethodCalls.markAsRead(call: call, result: result) - case "deleteUnreadMessageSeparatorOfAConversation": - FlySdkMethodCalls.deleteUnreadMessageSeparatorOfAConversation(call: call, result: result) - case "getRecalledMessagesOfAConversation": - FlySdkMethodCalls.getRecalledMessagesOfAConversation(call: call, result: result) - case "uploadMedia": - FlySdkMethodCalls.uploadMedia(call: call, result: result) - case "getMessagesUsingIds": - FlySdkMethodCalls.getMessagesUsingIds(call: call, result: result) - case "updateMediaDownloadStatus": - FlySdkMethodCalls.updateMediaDownloadStatus(call: call, result: result) - case "updateMediaUploadStatus": - FlySdkMethodCalls.updateMediaUploadStatus(call: call, result: result) - case "cancelMediaUploadOrDownload": - FlySdkMethodCalls.cancelMediaUploadOrDownload(call: call, result: result) - case "setMediaEncryption": - FlySdkMethodCalls.setMediaEncryption(call: call, result: result) - case "deleteAllMessages": - FlySdkMethodCalls.deleteAllMessages(call: call, result: result) - case "getGroupJid": - FlySdkMethodCalls.getGroupJid(call: call, result: result) - case "getProfileDetails": - FlySdkMethodCalls.getProfileDetails(call: call, result: result) - case "getProfileStatusList": - FlySdkMethodCalls.getProfileStatusList(call: call, result: result) - case "insertDefaultStatus": - FlySdkMethodCalls.insertDefaultStatus(call: call, result: result) - case "getRingtoneName": - FlySdkMethodCalls.getRingtoneName(call: call, result: result) - - case "setOnGoingChatUser": - FlySdkMethodCalls.setOnGoingChatUser(call: call, result: result) - - case "markAsReadDeleteUnreadSeparator": - FlySdkMethodCalls.markAsReadDeleteUnreadSeparator(call: call, result: result) - case "getMessagesOfJid": - FlySdkMethodCalls.getMessagesOfJid(call: call, result: result) - - - case "updateRecentChatPinStatus": - FlySdkMethodCalls.updateRecentChatPinStatus(call: call, result: result) - - case "deleteRecentChat": - FlySdkMethodCalls.deleteRecentChat(call: call, result: result) - case "recentChatPinnedCount": - FlySdkMethodCalls.recentChatPinnedCount(call: call, result: result) - case "getRecentChatList": - FlySdkMethodCalls.getRecentChatList(call: call, result: result) -// case "get_recent_chat_of": -// FlySdkMethodCalls.getRecentChatOf(call: call, result: result) - case "getRecentChatListIncludingArchived": - FlySdkMethodCalls.getRecentChatListIncludingArchived(call: call, result: result) - case "getRecentChatOf": - FlySdkMethodCalls.getRecentChatOf(call: call, result: result) - - case "register_user": - FlySdkMethodCalls.registerUser(call: call, result: result) - case "authtoken": - FlySdkMethodCalls.refreshAndGetAuthToken(call: call, result: result) - case "refreshAuthToken": - FlySdkMethodCalls.refreshAndGetAuthToken(call: call, result: result) - case "verifyToken": - FlySdkMethodCalls.verifyToken(call: call, result: result) - case "get_jid": - FlySdkMethodCalls.getJid(call: call, result: result) - case "send_text_msg": - FlySdkMethodCalls.sendTextMessage(call: call, result: result) - case "sendLocationMessage": - FlySdkMethodCalls.sendLocationMessage(call: call, result: result) - case "send_image_message": - FlySdkMethodCalls.sendImageMessage(call: call, result: result) - case "send_video_message": - FlySdkMethodCalls.sendVideoMessage(call: call, result: result) - case "sendContactMessage": - FlySdkMethodCalls.sendContactMessage(call: call, result: result) - case "sendDocumentMessage": - FlySdkMethodCalls.sendDocumentMessage(call: call, result: result) - case "sendAudioMessage": - FlySdkMethodCalls.sendAudioMessage(call: call, result: result) - case "get_user_list": - FlySdkMethodCalls.getUserList(call: call, result: result) - case "getRegisteredUsers"://In Android we call getRegisteredUsers -// FlySdkMethodCalls.getUserList(call: call, result: result) - FlySdkMethodCalls.getRegisteredUsers(call: call, result: result) - - case "getUserProfile": - FlySdkMethodCalls.getUserProfile(call: call, result: result) - case "clear_chat": - FlySdkMethodCalls.clearChat(call: call, result: result) - - case "updateMyProfile": - FlySdkMethodCalls.updateMyProfile(call: call, result: result) - - case "media_endpoint": - FlySdkMethodCalls.getMediaEndPoint(call: call, result: result) - - case "reportUserOrMessages": - FlySdkMethodCalls.reportUserOrMessages(call: call, result: result) - case "block_user": - FlySdkMethodCalls.blockUser(call: call, result: result) - case "un_block_user": - FlySdkMethodCalls.unblockUser(call: call, result: result) - case "createGroup": - FlySdkMethodCalls.createGroup(call: call, result: result) - case "getUserLastSeenTime": - FlySdkMethodCalls.getUserLastSeenTime(call: call, result: result) - case "getUsersIBlocked": - FlySdkMethodCalls.getUsersIBlocked(call: call, result: result) - case "setMyProfileStatus": - FlySdkMethodCalls.setMyProfileStatus(call: call, result: result) - case "sendData": - let UserJid = Utility.getStringFromPreference(key: notificationUserJid) - Utility.saveInPreference(key: notificationUserJid, value: "") - result(UserJid) - case "getMediaMessages": - FlySdkMethodCalls.getMediaMessages(call: call, result: result) - case "isMemberOfGroup": - FlySdkMethodCalls.isMemberOfGroup(call: call, result: result) - case "updateArchiveUnArchiveChat": - FlySdkMethodCalls.updateArchiveUnArchiveChat(call: call, result: result) - case "getArchivedChatList": - FlySdkMethodCalls.getArchivedChatList(call: call, result: result) - case "updateChatMuteStatus": - FlySdkMethodCalls.updateChatMuteStatus(call: call, result: result) - case "sendTypingStatus": - FlySdkMethodCalls.sendTypingStatus(call: call, result: result) - case "sendTypingGoneStatus": - FlySdkMethodCalls.sendTypingGoneStatus(call: call, result: result) - case "setNotificationSound": - FlySdkMethodCalls.setNotificationSound(call: call, result: result) - case "isBusyStatusEnabled": - FlySdkMethodCalls.isBusyStatusEnabled(call: call, result: result) - case "updateMyProfileImage": - FlySdkMethodCalls.updateMyProfileImage(call: call, result: result) - case "isUserUnArchived": - FlySdkMethodCalls.isUserUnArchived(call: call, result: result) - case "forwardMessagesToMultipleUsers": - FlySdkMethodCalls.forwardMessagesToMultipleUsers(call: call, result: result) - case "removeProfileImage": - FlySdkMethodCalls.removeProfileImage(call: call, result: result) - case "isArchivedSettingsEnabled": - FlySdkMethodCalls.isArchivedSettingsEnabled(call: call, result: result) - case "getGroupMembersList": - FlySdkMethodCalls.getGroupMembersList(call: call, result: result) - case "enableDisableArchivedSettings": - FlySdkMethodCalls.enableDisableArchivedSettings(call: call, result: result) - case "clearAllConversation": - FlySdkMethodCalls.clearAllConversation(call: call, result: result) - case "cancelNotifications": - FlySdkMethodCalls.cancelNotifications(call: call, result: result) - case "insertBusyStatus": - FlySdkMethodCalls.insertBusyStatus(call: call, result: result) - case "getDocsMessages": - FlySdkMethodCalls.getDocsMessages(call: call, result: result) - case "getLinkMessages": - FlySdkMethodCalls.getLinkMessages(call: call, result: result) - case "isAdmin": - FlySdkMethodCalls.isAdmin(call: call, result: result) - case "leaveFromGroup": - FlySdkMethodCalls.leaveFromGroup(call: call, result: result) - case "getMediaAutoDownload": - FlySdkMethodCalls.getMediaAutoDownload(call: call, result: result) - case "setMediaAutoDownload": - FlySdkMethodCalls.setMediaAutoDownload(call: call, result: result) - case "getMediaSetting": - FlySdkMethodCalls.getMediaSetting(call: call, result: result) - case "saveMediaSettings": - FlySdkMethodCalls.saveMediaSettings(call: call, result: result) - case "downloadMedia": - FlySdkMethodCalls.downloadMedia(call: call, result: result) - case "updateFavouriteStatus": - FlySdkMethodCalls.updateFavouriteStatus(call: call, result: result) - case "iOSFileExist": - FlySdkMethodCalls.iOSFileExist(call: call, result: result) - case "get_favourite_messages": - FlySdkMethodCalls.getFavouriteMessages(call: call, result: result) - case "getUnsentMessageOfAJid": - FlySdkMethodCalls.getUnsentMessageOfAJid(call: call, result: result) - case "saveUnsentMessage": - FlySdkMethodCalls.saveUnsentMessage(call: call, result: result) - case "deleteRecentChats": - FlySdkMethodCalls.deleteRecentChats(call: call, result: result) - case "getDefaultNotificationUri": - FlySdkMethodCalls.getDefaultNotificationUri(call: call, result: result) - case "logoutOfChatSDK": - FlySdkMethodCalls.logoutOfChatSDK(call: call, result: result) - case "getMessageOfId": - FlySdkMethodCalls.getMessageOfId(call: call, result: result) - case "insertNewProfileStatus": - FlySdkMethodCalls.insertNewProfileStatus(call: call, result: result) - case "IS_TRIAL_LICENSE": - FlySdkMethodCalls.isTrailLicence(call: call, result: result) - case "makeAdmin": - FlySdkMethodCalls.makeAdmin(call: call, result: result) - case "updateGroupName": - FlySdkMethodCalls.updateGroupName(call: call, result: result) - case "updateGroupProfileImage": - FlySdkMethodCalls.updateGroupProfileImage(call: call, result: result) - case "removeGroupProfileImage": - FlySdkMethodCalls.removeGroupProfileImage(call: call, result: result) - case "addUsersToGroup": - FlySdkMethodCalls.addUsersToGroup(call: call, result: result) - case "removeMemberFromGroup": - FlySdkMethodCalls.removeMemberFromGroup(call: call, result: result) - default: - result(FlutterMethodNotImplemented) - } - - }) - } - - func applicationDidBecomeActive(){ - if Utility.getBoolFromPreference(key: isLoggedIn) && (FlyDefaults.isLoggedIn) { - print("connecting chat manager") - ChatManager.connect() - ChatManager.shared.startAutoDownload() - }else{ - print(Utility.getBoolFromPreference(key: isLoggedIn)) - print(FlyDefaults.isLoggedIn) - print("Unable to connect chat manager") - } - } - - func applicationDidEnterBackground(){ - if (FlyDefaults.isLoggedIn) { - print("Disconnecting Chat Manager") - ChatManager.disconnect() - } - } - - func applicationWillResignActive(_ application: UIApplication) { - - } - -} - - -extension FlyBaseController : MessageEventsDelegate, ConnectionEventDelegate, LogoutDelegate, GroupEventsDelegate, - AdminBlockCurrentUserDelegate, TypingStatusDelegate, ProfileEventsDelegate, - AdminBlockDelegate,AvailableFeaturesDelegate, BackupEventDelegate, RestoreEventDelegate { - func clearAllConversationForSyncedDevice() { - - } - - - func onMessagesCleared(toJid: String, deleteType: String?) { - - } - - func restoreProgressDidReceive(completedCount: Double, completedPercentage: String, completedSize: String) { - - } - - func restoreDidFinish() { - - } - - func restoreDidFailed(errorMessage: String) { - - } - - - func didUpdateAvailableFeatures(features: FlyCommon.AvailableFeaturesModel) { - - } - func backupProgressDidReceive(completedCount: String, completedSize: String) { - - } - - func backupDidFinish(fileUrl: String) { - - } - - func backupDidFailed(errorMessage: String) { - - } - - func userCameOnline(for jid: String) { - - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(jid, forKey: "jid") - let jsonString = Commons.json(from: jsonObject) - if(userCameOnlineStreamHandler?.userCameOnline != nil){ - userCameOnlineStreamHandler?.userCameOnline?(jsonString) - }else{ - print("Chat Typing Stream Handler is Nil") - } - - } - - func userWentOffline(for jid: String) { - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(jid, forKey: "jid") - let jsonString = Commons.json(from: jsonObject) - if(userWentOfflineStreamHandler?.userWentOffline != nil){ - userWentOfflineStreamHandler?.userWentOffline?(jsonString) - }else{ - print("userWentOffline Stream Handler is Nil") - } - } - - func userProfileFetched(for jid: String, profileDetails: FlyCommon.ProfileDetails?) { -// var userProfileJson = JSONSerializer.toJson(profileDetails as Any) - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(jid, forKey: "jid") - jsonObject.setValue(profileDetails, forKey: "profileDetails") - let jsonString = JSONSerializer.toJson(jsonObject) - if(userProfileFetchedStreamHandler?.userProfileFetched != nil){ - userProfileFetchedStreamHandler?.userProfileFetched?(jsonString) - }else{ - print("userProfileFetched Stream Handler is Nil") - } - } - - func myProfileUpdated() { - if(myProfileUpdatedStreamHandler?.myProfileUpdated != nil){ - myProfileUpdatedStreamHandler?.myProfileUpdated?(true) - }else{ - print("myProfileUpdated Stream Handler is Nil") - } - } - - func usersProfilesFetched() { - if(usersProfilesFetchedStreamHandler?.usersProfilesFetched != nil){ - usersProfilesFetchedStreamHandler?.usersProfilesFetched?(true) - }else{ - print("usersProfilesFetched Stream Handler is Nil") - } - } - - func blockedThisUser(jid: String) { - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(jid, forKey: "jid") - let jsonString = Commons.json(from: jsonObject) - if(blockedThisUserStreamHandler?.blockedThisUser != nil){ - blockedThisUserStreamHandler?.blockedThisUser?(jsonString) - }else{ - print("blockedThisUser Stream Handler is Nil") - } - } - - func unblockedThisUser(jid: String) { - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(jid, forKey: "jid") - let jsonString = Commons.json(from: jsonObject) - if(unblockedThisUserStreamHandler?.unblockedThisUser != nil){ - unblockedThisUserStreamHandler?.unblockedThisUser?(jsonString) - }else{ - print("unblockedThisUser Stream Handler is Nil") - } - } - - func usersIBlockedListFetched(jidList: [String]) { - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(jidList, forKey: "jidlist") - let jsonString = Commons.json(from: jsonObject) - if(usersIBlockedListFetchedStreamHandler?.usersIBlockedListFetched != nil){ - usersIBlockedListFetchedStreamHandler?.usersIBlockedListFetched?(jsonString) - }else{ - print("usersIBlockedListFetched Stream Handler is Nil") - } - } - - func usersBlockedMeListFetched(jidList: [String]) { - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(jidList, forKey: "jidlist") - let jsonString = Commons.json(from: jsonObject) - if(usersWhoBlockedMeListFetchedStreamHandler?.usersWhoBlockedMeListFetched != nil){ - usersWhoBlockedMeListFetchedStreamHandler?.usersWhoBlockedMeListFetched?(jsonString) - }else{ - print("usersBlockedMeListFetched Stream Handler is Nil") - } - } - - func userUpdatedTheirProfile(for jid: String, profileDetails: FlyCommon.ProfileDetails) { - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(jid, forKey: "jid") - let jsonString = Commons.json(from: jsonObject) - if(userUpdatedHisProfileStreamHandler?.userUpdatedHisProfile != nil){ - userUpdatedHisProfileStreamHandler?.userUpdatedHisProfile?(jsonString) - }else{ - print("userUpdatedTheirProfile Stream Handler is Nil") - } - - } - - func userBlockedMe(jid: String) { - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(jid, forKey: "jid") - let jsonString = Commons.json(from: jsonObject) - if(userBlockedMeStreamHandler?.userBlockedMe != nil){ - userBlockedMeStreamHandler?.userBlockedMe?(jsonString) - }else{ - print("userBlockedMe Stream Handler is Nil") - } - } - - func userUnBlockedMe(jid: String) { - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(jid, forKey: "jid") - let jsonString = Commons.json(from: jsonObject) - if(userUnBlockedMeStreamHandler?.userUnBlockedMe != nil){ - userUnBlockedMeStreamHandler?.userUnBlockedMe?(jsonString) - }else{ - print("userUnBlockedMe Stream Handler is Nil") - } - } - - func hideUserLastSeen() { - - } - - func getUserLastSeen() { - - } - - func userDeletedTheirProfile(for jid: String, profileDetails: FlyCommon.ProfileDetails) { - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(jid, forKey: "jid") - let jsonString = Commons.json(from: jsonObject) - if(userDeletedHisProfileStreamHandler?.userDeletedHisProfile != nil){ - userDeletedHisProfileStreamHandler?.userDeletedHisProfile?(jsonString) - }else{ - print("userDeletedTheirProfile Stream Handler is Nil") - } - } - - func didBlockOrUnblockSelf(userJid: String, isBlocked: Bool) { - - } - - func onChatTypingStatus(userJid: String, status: FlyCommon.TypingStatus) { - - print("onChatTypingStatus") - let jsonObject: NSMutableDictionary = NSMutableDictionary() - - - jsonObject.setValue(userJid, forKey: "singleOrgroupJid") - jsonObject.setValue(userJid, forKey: "userId") - jsonObject.setValue(status == TypingStatus.composing ? "composing" : "Gone", forKey: "composing") - - print("json data-->\(jsonObject)") - - - let jsonString = Commons.json(from: jsonObject) - print("json-->\(String(describing: jsonString))") - - if(onsetTypingStatusStreamHandler?.onSetTyping != nil){ - onsetTypingStatusStreamHandler?.onSetTyping?(jsonString) - - }else{ - print("Chat Typing Stream Handler is Nil") - } - - } - - func onGroupTypingStatus(groupJid: String, groupUserJid: String, status: FlyCommon.TypingStatus) { - - print("onGroupTypingStatus") - - let jsonObject: NSMutableDictionary = NSMutableDictionary() -// jsonObject.setValue(groupJid, forKey: "groupJid") -// jsonObject.setValue(groupUserJid, forKey: "groupUserJid") -// jsonObject.setValue(status.rawValue, forKey: "status") - jsonObject.setValue(groupJid, forKey: "singleOrgroupJid") - jsonObject.setValue(groupUserJid, forKey: "userId") - jsonObject.setValue(status == TypingStatus.composing ? "composing" : "Gone", forKey: "composing") - let jsonString = Commons.json(from: jsonObject) - - if(onsetTypingStatusStreamHandler?.onSetTyping != nil){ - onsetTypingStatusStreamHandler?.onSetTyping?(jsonString) - }else{ - print("Group Chat Typing Stream Handler is Nil") - } - } - - func onMessageReceived(message: FlyCommon.ChatMessage, chatJid: String) { - - print("Message Received Update--->") - print("Message Received Update--->\(message.messageId)") - print("Message Received Update--->\(message.messageTextContent)") - print(JSONSerializer.toJson(message)) - - var messageReceivedJson = JSONSerializer.toJson(message) - messageReceivedJson = messageReceivedJson.replacingOccurrences(of: "{\"some\":", with: "") - messageReceivedJson = messageReceivedJson.replacingOccurrences(of: "}}", with: "}") - - if(messageReceivedStreamHandler?.onMessageReceived != nil){ - messageReceivedStreamHandler?.onMessageReceived?(messageReceivedJson) - - }else{ - print("Message Stream Handler is Nil") - } - - } - - func onMessageStatusUpdated(messageId: String, chatJid: String, status: FlyCommon.MessageStatus) { - - print("====Message status update====") - print("messageID-->\(messageId)") - -// var tempSaveContact = ContactManager.shared.saveTempContact(userId: chatJid) -// print(tempSaveContact as Any) - -// FlyMessenger.database.messageManager.getMessageDetailFor(id: messageId)!) - - let chatMessage = ChatManager.getMessageOfId(messageId: messageId) - print("Message Status Update--->\(String(describing: chatMessage))") - print("getMessageOfId==>", chatMessage?.messageTextContent as Any) - - if(chatMessage == nil){ - return - } - var chatMessageJson = JSONSerializer.toJson(chatMessage as Any) - - chatMessageJson = chatMessageJson.replacingOccurrences(of: "{\"some\":", with: "") - chatMessageJson = chatMessageJson.replacingOccurrences(of: "}}", with: "}") - print(chatMessageJson) - - if(messageStatusUpdatedStreamHandler?.onMessageStatusUpdated != nil){ - messageStatusUpdatedStreamHandler?.onMessageStatusUpdated?(chatMessageJson) - - }else{ - print("Message status Stream Handler is Nil") - } - - } - - func onMediaStatusUpdated(message : FlyCommon.ChatMessage) { - print("Media Status Update--->") - var chatMediaJson = JSONSerializer.toJson(message as Any) - chatMediaJson = chatMediaJson.replacingOccurrences(of: "{\"some\":", with: "") - chatMediaJson = chatMediaJson.replacingOccurrences(of: "}}", with: "}") - print(chatMediaJson) - - if(mediaStatusUpdatedStreamHandler?.onMediaStatusUpdated != nil){ - mediaStatusUpdatedStreamHandler?.onMediaStatusUpdated?(chatMediaJson) - }else{ - print("chatMediaJson Stream Handler is Nil") - } - } - - func onMediaStatusFailed(error: String, messageId: String) { - print("Media Status Failed--->\(error)") - } - - func onMediaProgressChanged(message: FlyCommon.ChatMessage, progressPercentage: Float) { - print("Media Status Onprogress changed---> \(progressPercentage)") - - } - - func onMessagesClearedOrDeleted(messageIds: Array) { - print("Message Cleared--->") - } - - func onMessagesDeletedforEveryone(messageIds: Array) { - print("Message Deleted For Everyone--->") - } - - func showOrUpdateOrCancelNotification() { - print("Message showOrUpdateOrCancelNotification--->") - - } - - func onMessagesCleared(toJid: String) { - print("Message onMessagesCleared--->") - } - - func setOrUpdateFavourite(messageId: String, favourite: Bool, removeAllFavourite: Bool) { - print("Message setOrUpdateFavourite--->") - } - - func onMessageTranslated(message: FlyCommon.ChatMessage, jid: String) { - print("Message onMessageTranslated--->") - } - - func didBlockOrUnblockCurrentUser(userJid: String, isBlocked: Bool) { - - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(userJid, forKey: "jid") - jsonObject.setValue(isBlocked, forKey: "status") - let jsonString = Commons.json(from: jsonObject) - if(onAdminBlockedUserStreamHandler?.onAdminBlockedUser != nil){ - onAdminBlockedUserStreamHandler?.onAdminBlockedUser?(jsonString) - }else{ - print("didBlockOrUnblockContact Stream Handler is Nil") - } - - } - - func didBlockOrUnblockGroup(groupJid: String, isBlocked: Bool) { - - } - - func didBlockOrUnblockContact(userJid: String, isBlocked: Bool) { - - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(userJid, forKey: "jid") - jsonObject.setValue("", forKey: "type") - jsonObject.setValue(isBlocked, forKey: "status") - let jsonString = Commons.json(from: jsonObject) - if(onAdminBlockedOtherUserStreamHandler?.onAdminBlockedOtherUser != nil){ - onAdminBlockedOtherUserStreamHandler?.onAdminBlockedOtherUser?(jsonString) - }else{ - print("didBlockOrUnblockContact Stream Handler is Nil") - } - - } - - func didAddNewMemeberToGroup(groupJid: String, newMemberJid: String, addedByMemberJid: String) { - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(groupJid, forKey: "groupJid") - jsonObject.setValue(newMemberJid, forKey: "newMemberJid") - jsonObject.setValue(addedByMemberJid, forKey: "addedByMemberJid") - let jsonString = Commons.json(from: jsonObject) - if(newMemberAddedToGroupStreamHandler?.onNewMemberAddedToGroup != nil){ - newMemberAddedToGroupStreamHandler?.onNewMemberAddedToGroup?(jsonString) - }else{ - print("didAddNewMemeberToGroup Stream Handler is Nil") - } - } - - func didRemoveMemberFromGroup(groupJid: String, removedMemberJid: String, removedByMemberJid: String) { - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(groupJid, forKey: "groupJid") - jsonObject.setValue(removedMemberJid, forKey: "removedMemberJid") - jsonObject.setValue(removedByMemberJid, forKey: "removedByMemberJid") - let jsonString = Commons.json(from: jsonObject) - if(memberRemovedFromGroupStreamHandler?.onMemberRemovedFromGroup != nil){ - memberRemovedFromGroupStreamHandler?.onMemberRemovedFromGroup?(jsonString) - }else{ - print("didRemoveMemberFromGroup Stream Handler is Nil") - } - - } - - func didFetchGroupProfile(groupJid: String) { - - if(groupProfileFetchedStreamHandler?.onGroupProfileFetched != nil){ - groupProfileFetchedStreamHandler?.onGroupProfileFetched?(groupJid) - }else{ - print("didFetchGroupProfile Stream Handler is Nil") - } - - } - - func didUpdateGroupProfile(groupJid: String) { - - if(groupProfileUpdatedStreamHandler?.onGroupProfileUpdated != nil){ - groupProfileUpdatedStreamHandler?.onGroupProfileUpdated?(groupJid) - }else{ - print("didUpdateGroupProfile Stream Handler is Nil") - } - - } - - func didMakeMemberAsAdmin(groupJid: String, newAdminMemberJid: String, madeByMemberJid: String) { - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(groupJid, forKey: "groupJid") - jsonObject.setValue(newAdminMemberJid, forKey: "newAdminMemberJid") - jsonObject.setValue(madeByMemberJid, forKey: "madeByMemberJid") - let jsonString = Commons.json(from: jsonObject) - if(memberMadeAsAdminStreamHandler?.onMemberMadeAsAdmin != nil){ - memberMadeAsAdminStreamHandler?.onMemberMadeAsAdmin?(jsonString) - }else{ - print("didMakeMemberAsAdmin Stream Handler is Nil") - } - - } - - func didRemoveMemberFromAdmin(groupJid: String, removedAdminMemberJid: String, removedByMemberJid: String) { - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(groupJid, forKey: "groupJid") - jsonObject.setValue(removedAdminMemberJid, forKey: "removedAdminMemberJid") - jsonObject.setValue(removedByMemberJid, forKey: "removedByMemberJid") - let jsonString = Commons.json(from: jsonObject) - if(memberRemovedAsAdminStreamHandler?.onMemberRemovedAsAdmin != nil){ - memberRemovedAsAdminStreamHandler?.onMemberRemovedAsAdmin?(jsonString) - }else{ - print("didRemoveMemberFromAdmin Stream Handler is Nil") - } - - } - - func didDeleteGroupLocally(groupJid: String) { - if(onGroupDeletedLocallyStreamHandler?.onGroupDeletedLocally != nil){ - onGroupDeletedLocallyStreamHandler?.onGroupDeletedLocally?(groupJid) - }else{ - print("didDeleteGroupLocally Stream Handler is Nil") - } - - } - - func didLeftFromGroup(groupJid: String, leftUserJid: String) { - let jsonObject: NSMutableDictionary = NSMutableDictionary() - jsonObject.setValue(groupJid, forKey: "groupJid") - jsonObject.setValue(leftUserJid, forKey: "leftUserJid") - let jsonString = Commons.json(from: jsonObject) - if(leftFromGroupStreamHandler?.onLeftFromGroup != nil){ - leftFromGroupStreamHandler?.onLeftFromGroup?(jsonString) - }else{ - print("didRemoveMemberFromAdmin Stream Handler is Nil") - } - } - - func didCreateGroup(groupJid: String) { - if(newGroupCreatedStreamHandler?.onNewGroupCreated != nil){ - newGroupCreatedStreamHandler?.onNewGroupCreated?(groupJid) - }else{ - print("didCreateGroup Stream Handler is Nil") - } - } - - func didFetchGroups(groups: [FlyCommon.ProfileDetails]) { - - } - - func didFetchGroupMembers(groupJid: String) { - if(fetchingGroupMembersCompletedStreamHandler?.onFetchingGroupMembersCompleted != nil){ - fetchingGroupMembersCompletedStreamHandler?.onFetchingGroupMembersCompleted?(groupJid) - }else{ - print("didFetchGroupMembers Stream Handler is Nil") - } - } - - func didReceiveGroupNotificationMessage(message: FlyCommon.ChatMessage) { - - var groupNotificationJson = JSONSerializer.toJson(message) - groupNotificationJson = groupNotificationJson.replacingOccurrences(of: "{\"some\":", with: "") - groupNotificationJson = groupNotificationJson.replacingOccurrences(of: "}}", with: "}") - - if(onGroupNotificationMessageStreamHandler?.onGroupNotificationMessage != nil){ - onGroupNotificationMessageStreamHandler?.onGroupNotificationMessage?(groupNotificationJson) - }else{ - print("on group notification Stream Handler is Nil") - } - - } - - func didReceiveLogout() { - print("logout delegate received") - print("AppDelegate LogoutDelegate ===> LogoutDelegate") - - if(onLoggedOutStreamHandler?.onLoggedOut != nil){ - onLoggedOutStreamHandler?.onLoggedOut?(true) - }else{ - print("logout Stream Handler is Nil") - } - } - - func onConnected() { - print("====== sdk connected=======") - if(onConnectedStreamHandler?.onConnected != nil){ - onConnectedStreamHandler?.onConnected?(true) - }else{ - print("onConnected Stream Handler is Nil") - } - } - - func onDisconnected() { - print("====== sdk Disconnected======") - if(onDisconnectedStreamHandler?.onDisconnected != nil){ - onDisconnectedStreamHandler?.onDisconnected?(true) - }else{ - print("onDisconnected Stream Handler is Nil") - } - } - - func onConnectionNotAuthorized() { - print("====== sdk Not Authorized=======") - if(onConnectionNotAuthorizedStreamHandler?.onConnectionNotAuthorized != nil){ - onConnectionNotAuthorizedStreamHandler?.onConnectionNotAuthorized?(true) - }else{ - print("onConnectionNotAuthorized Stream Handler is Nil") - } - } - -} diff --git a/ios/Runner/FlyEvents.swift b/ios/Runner/FlyEvents.swift deleted file mode 100644 index 1cbaad8f..00000000 --- a/ios/Runner/FlyEvents.swift +++ /dev/null @@ -1,665 +0,0 @@ -// -// FlyEvents.swift -// Runner -// -// Created by User on 01/12/22. -// - -import Foundation -import Flutter - - - -public class MessageReceivedStreamHandler: FlutterStreamHandler { - public var onMessageReceived: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - self.onMessageReceived = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - self.onMessageReceived = nil - return nil - } - -} -class MessageStatusUpdatedStreamHandler: NSObject, FlutterStreamHandler { - public var onMessageStatusUpdated: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - self.onMessageStatusUpdated = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - self.onMessageStatusUpdated = nil - return nil - } -} -class MediaStatusUpdatedStreamHandler: NSObject, FlutterStreamHandler { - public var onMediaStatusUpdated: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - self.onMediaStatusUpdated = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - self.onMediaStatusUpdated = nil - return nil - } -} -class UploadDownloadProgressChangedStreamHandler: NSObject, FlutterStreamHandler { - public var onUploadDownloadProgressChanged: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onUploadDownloadProgressChanged = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onUploadDownloadProgressChanged = nil - return nil - } -} -class ShowOrUpdateOrCancelNotificationStreamHandler: NSObject, FlutterStreamHandler { - public var showOrUpdateOrCancelNotification: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - showOrUpdateOrCancelNotification = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - showOrUpdateOrCancelNotification = nil - return nil - } -} -class GroupProfileFetchedStreamHandler: NSObject, FlutterStreamHandler { - public var onGroupProfileFetched: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onGroupProfileFetched = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onGroupProfileFetched = nil - return nil - } -} - -class NewGroupCreatedStreamHandler: NSObject, FlutterStreamHandler { - public var onNewGroupCreated: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onNewGroupCreated = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onNewGroupCreated = nil - return nil - } -} -class GroupProfileUpdatedStreamHandler: NSObject, FlutterStreamHandler { - public var onGroupProfileUpdated: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onGroupProfileUpdated = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onGroupProfileUpdated = nil - return nil - } -} -class NewMemberAddedToGroupStreamHandler: NSObject, FlutterStreamHandler { - public var onNewMemberAddedToGroup: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onNewMemberAddedToGroup = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onNewMemberAddedToGroup = nil - return nil - } -} -class MemberRemovedFromGroupStreamHandler: NSObject, FlutterStreamHandler { - public var onMemberRemovedFromGroup: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onMemberRemovedFromGroup = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onMemberRemovedFromGroup = nil - return nil - } -} -class FetchingGroupMembersCompletedStreamHandler: NSObject, FlutterStreamHandler { - public var onFetchingGroupMembersCompleted: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onFetchingGroupMembersCompleted = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onFetchingGroupMembersCompleted = nil - return nil - } -} -class DeleteGroupStreamHandler: NSObject, FlutterStreamHandler { - public var onDeleteGroup: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onDeleteGroup = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onDeleteGroup = nil - return nil - } -} -class FetchingGroupListCompletedStreamHandler: NSObject, FlutterStreamHandler { - public var onFetchingGroupListCompleted: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onFetchingGroupListCompleted = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onFetchingGroupListCompleted = nil - return nil - } -} -class MemberMadeAsAdminStreamHandler: NSObject, FlutterStreamHandler { - public var onMemberMadeAsAdmin: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onMemberMadeAsAdmin = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onMemberMadeAsAdmin = nil - return nil - } -} -class MemberRemovedAsAdminStreamHandler: NSObject, FlutterStreamHandler { - public var onMemberRemovedAsAdmin: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onMemberRemovedAsAdmin = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onMemberRemovedAsAdmin = nil - return nil - } -} -class LeftFromGroupStreamHandler: NSObject, FlutterStreamHandler { - public var onLeftFromGroup: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onLeftFromGroup = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onLeftFromGroup = nil - return nil - } -} - -class GroupNotificationMessageStreamHandler: NSObject, FlutterStreamHandler { - public var onGroupNotificationMessage: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onGroupNotificationMessage = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onGroupNotificationMessage = nil - return nil - } -} -class GroupDeletedLocallyStreamHandler: NSObject, FlutterStreamHandler { - public var onGroupDeletedLocally: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onGroupDeletedLocally = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onGroupDeletedLocally = nil - return nil - } -} -class BlockedThisUserStreamHandler: NSObject, FlutterStreamHandler { - public var blockedThisUser: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - blockedThisUser = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - blockedThisUser = nil - return nil - } -} -class MyProfileUpdatedStreamHandler: NSObject, FlutterStreamHandler { - public var myProfileUpdated: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - myProfileUpdated = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - myProfileUpdated = nil - return nil - } -} -class OnAdminBlockedOtherUserStreamHandler: NSObject, FlutterStreamHandler { - public var onAdminBlockedOtherUser: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onAdminBlockedOtherUser = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onAdminBlockedOtherUser = nil - return nil - } -} -class OnAdminBlockedUserStreamHandler: NSObject, FlutterStreamHandler { - public var onAdminBlockedUser: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onAdminBlockedUser = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onAdminBlockedUser = nil - return nil - } -} -class OnContactSyncCompleteStreamHandler: NSObject, FlutterStreamHandler { - public var onContactSyncComplete: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onContactSyncComplete = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onContactSyncComplete = nil - return nil - } -} -class OnLoggedOutStreamHandler: NSObject, FlutterStreamHandler { - public var onLoggedOut: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onLoggedOut = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onLoggedOut = nil - return nil - } -} -class UnblockedThisUserStreamHandler: NSObject, FlutterStreamHandler { - public var unblockedThisUser: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - unblockedThisUser = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - unblockedThisUser = nil - return nil - } -} -class UserBlockedMeStreamHandler: NSObject, FlutterStreamHandler { - public var userBlockedMe: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - userBlockedMe = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - userBlockedMe = nil - return nil - } -} -class UserCameOnlineStreamHandler: NSObject, FlutterStreamHandler { - public var userCameOnline: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - userCameOnline = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - userCameOnline = nil - return nil - } -} -class UserDeletedHisProfileStreamHandler: NSObject, FlutterStreamHandler { - public var userDeletedHisProfile: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - userDeletedHisProfile = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - userDeletedHisProfile = nil - return nil - } -} -class UserProfileFetchedStreamHandler: NSObject, FlutterStreamHandler { - public var userProfileFetched: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - userProfileFetched = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - userProfileFetched = nil - return nil - } -} -class UserUnBlockedMeStreamHandler: NSObject, FlutterStreamHandler { - public var userUnBlockedMe: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - userUnBlockedMe = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - userUnBlockedMe = nil - return nil - } -} -class UserUpdatedHisProfileStreamHandler: NSObject, FlutterStreamHandler { - public var userUpdatedHisProfile: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - userUpdatedHisProfile = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - userUpdatedHisProfile = nil - return nil - } -} -class UserWentOfflineStreamHandler: NSObject, FlutterStreamHandler { - public var userWentOffline: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - userWentOffline = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - userWentOffline = nil - return nil - } -} -class UsersIBlockedListFetchedStreamHandler: NSObject, FlutterStreamHandler { - public var usersIBlockedListFetched: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - usersIBlockedListFetched = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - usersIBlockedListFetched = nil - return nil - } -} -class UsersProfilesFetchedStreamHandler: NSObject, FlutterStreamHandler { - public var usersProfilesFetched: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - usersProfilesFetched = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - usersProfilesFetched = nil - return nil - } -} -class UsersWhoBlockedMeListFetchedStreamHandler: NSObject, FlutterStreamHandler { - public var usersWhoBlockedMeListFetched: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - usersWhoBlockedMeListFetched = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - usersWhoBlockedMeListFetched = nil - return nil - } -} -class OnConnectedStreamHandler: NSObject, FlutterStreamHandler { - public var onConnected: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onConnected = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onConnected = nil - return nil - } -} -class OnDisconnectedStreamHandler: NSObject, FlutterStreamHandler { - public var onDisconnected: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onDisconnected = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onDisconnected = nil - return nil - } -} -class OnConnectionNotAuthorizedStreamHandler: NSObject, FlutterStreamHandler { - public var onConnectionNotAuthorized: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onConnectionNotAuthorized = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onConnectionNotAuthorized = nil - return nil - } -} -class ConnectionFailedStreamHandler: NSObject, FlutterStreamHandler { - public var connectionFailed: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - connectionFailed = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - connectionFailed = nil - return nil - } -} -class ConnectionSuccessStreamHandler: NSObject, FlutterStreamHandler { - public var connectionSuccess: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - connectionSuccess = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - connectionSuccess = nil - return nil - } -} -class OnWebChatPasswordChangedStreamHandler: NSObject, FlutterStreamHandler { - public var onWebChatPasswordChanged: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onWebChatPasswordChanged = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onWebChatPasswordChanged = nil - return nil - } -} -class setTypingStatusStreamHandler: NSObject, FlutterStreamHandler { - public var setTypingStatus: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - setTypingStatus = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - setTypingStatus = nil - return nil - } -} -class onChatTypingStatusStreamHandler: NSObject, FlutterStreamHandler { - public var onChatTypingStatus: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onChatTypingStatus = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onChatTypingStatus = nil - return nil - } -} -class onGroupTypingStatusStreamHandler: NSObject, FlutterStreamHandler { - public var onGroupTypingStatus: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onGroupTypingStatus = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onGroupTypingStatus = nil - return nil - } -} -class OnFailureStreamHandler: NSObject, FlutterStreamHandler { - public var onFailure: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onFailure = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onFailure = nil - return nil - } -} -class OnProgressChangedStreamHandler: NSObject, FlutterStreamHandler { - public var onProgressChanged: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onProgressChanged = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onProgressChanged = nil - return nil - } -} -class OnSuccessStreamHandler: NSObject, FlutterStreamHandler { - public var onSuccess: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - onSuccess = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - onSuccess = nil - return nil - } -} -class OnChatTypingStatusStreamHandler: NSObject, FlutterStreamHandler { - public var onChatTyping: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - self.onChatTyping = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - self.onChatTyping = nil - return nil - } -} -class OnsetTypingStatusStreamHandler: NSObject, FlutterStreamHandler { - public var onSetTyping: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - self.onSetTyping = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - self.onSetTyping = nil - return nil - } -} -class OnGroupTypingStatusStreamHandler: NSObject, FlutterStreamHandler { - public var onGroupTyping: FlutterEventSink? - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - self.onGroupTyping = events - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - self.onGroupTyping = nil - return nil - } -} diff --git a/ios/Runner/FlySdkMethodCalls.swift b/ios/Runner/FlySdkMethodCalls.swift deleted file mode 100644 index f090334b..00000000 --- a/ios/Runner/FlySdkMethodCalls.swift +++ /dev/null @@ -1,2113 +0,0 @@ -// -// FlySDKMethodCalls.swift -// Runner -// -// Created by User on 10/11/22. -// - -import Foundation -import FlyCore -import FlyCommon -import Flutter -import Photos -import FlyDatabase -//import DSON - -@objc class FlySdkMethodCalls : NSObject{ - - - static func registerUser(call: FlutterMethodCall, result: @escaping FlutterResult){ - - let args = call.arguments as! Dictionary - - var userIdentifier = args["userIdentifier"] as? String ?? "" - userIdentifier = userIdentifier.replacingOccurrences(of: "+", with: "") - - let deviceToken = Utility.getStringFromPreference(key: googleToken) - var voipToken = Utility.getStringFromPreference(key: voipToken) - - voipToken = voipToken.isEmpty ? deviceToken : voipToken - - if(userIdentifier == nil){ - result(FlutterError(code: "500", - message: "User Name is Empty", - details: nil)) - return - } - - try! ChatManager.registerApiService(for: userIdentifier ?? "", deviceToken: deviceToken, voipDeviceToken: voipToken, isExport: false) { isSuccess, flyError, flyData in - var data = flyData - if isSuccess { - - print("Register Response") - - let registerResponse = [ - "data": data, - "is_new_user": data["newLogin"] as Any, - "message" : "Register Trial API Success" - ] as [String : Any] - - FlyDefaults.isLoggedIn = true - Utility.saveInPreference(key: isLoggedIn, value: true) - FlyDefaults.myXmppPassword = data["password"] as! String - FlyDefaults.myXmppUsername = data["username"] as! String - FlyDefaults.myMobileNumber = userIdentifier - FlyDefaults.isProfileUpdated = data["isProfileUpdated"] as! Int == 1 - - - ChatManager.connect() - - DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) { - result(Commons.json(from: registerResponse)) - } - - - }else{ - let error = data.getMessage() - result(FlutterError(code: "500", - message: error as? String, - details: nil)) - print("#chatSDK \(error)") - } - } - } - - static func refreshAndGetAuthToken(call: FlutterMethodCall, result: @escaping FlutterResult){ - ChatManager.refreshToken { (isSuccess, flyError, resultDict) in - if (isSuccess) { - var resp = resultDict - let tokendata = resp.getData() - let refreshToken = tokendata as AnyObject - - let newToken = refreshToken["token"] as Any - - print("ios refreshAndGetAuthToken-->\(newToken)") - - result(newToken) - - } else { - result(FlutterError(code: "500", message: "Unable to refresh token", details: flyError?.description)) - - } - } - } - - static func getJid(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let userName = args["username"] as? String - if(userName == nil){ - result(FlutterError(code: "500", - message: "User Name is Empty", - details: nil)) - return - } - do{ - try result(FlyUtils.getJid(from: userName!)) - }catch let jidError{ - result(FlutterError(code: "500", message: "Unable to get JID", details: jidError.localizedDescription)) - } - - } - - - static func sendTextMessage(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let txtMessage = args["message"] as? String ?? nil - let receiverJID = args["JID"] as? String ?? nil - let replyMessageID = args["replyMessageId"] as? String ?? "" - - if(txtMessage == nil || receiverJID == nil){ - result(FlutterError(code: "500", message: "Parameters Missing", details: nil)) - return - } - - FlyMessenger.sendTextMessage(toJid: receiverJID!, message: txtMessage!.trimmingCharacters(in: .whitespacesAndNewlines), replyMessageId: replyMessageID) { isSuccess,error,chatMessage in - if isSuccess { - print("sending text messages-->\(chatMessage?.messageTextContent)") - var chatMsg = JSONSerializer.toJson(chatMessage as Any) - chatMsg = chatMsg.replacingOccurrences(of: "{\"some\":", with: "") - chatMsg = chatMsg.replacingOccurrences(of: "}}", with: "}") - print(chatMsg) - result(chatMsg) - }else{ - result(FlutterError(code: "500", message: Commons.json(from: error as Any), details: nil)) - } - } - - } - - static func sendLocationMessage(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let latitude = args["latitude"] as? Double ?? 00.0 - let longitude = args["longitude"] as? Double ?? 00.0 - let userJid = args["jid"] as? String ?? nil - let replyMessageID = args["replyMessageId"] as? String ?? "" - - if(latitude == 00.0 || longitude == 00.0){ - result(FlutterError(code: "500", message: "Location is Empty", details: nil)) - return - } - if(userJid == nil){ - result(FlutterError(code: "500", message: "Location is Empty", details: nil)) - return - } - - FlyMessenger.sendLocationMessage(toJid: userJid!, latitude: latitude, longitude: longitude, replyMessageId: replyMessageID) { isSuccess,error,chatMessage in - if isSuccess { - var locationResponse = JSONSerializer.toJson(chatMessage as Any) - - locationResponse = locationResponse.replacingOccurrences(of: "{\"some\":", with: "") - locationResponse = locationResponse.replacingOccurrences(of: "}}", with: "}") - print(locationResponse) - - result(locationResponse) - }else{ - result(FlutterError(code: "500", message: Commons.json(from: error as Any), details: nil)) - } - } - } - - static func sendImageMessage(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let userJid = args["jid"] as? String ?? nil - let filePath = args["filePath"] as? String ?? "" - let replyMessageId = args["replyMessageId"] as? String ?? "" - - let caption = args["caption"] as? String ?? "" - print("====File Path====") - - print(filePath) - print("====File Path====") - - let imagefileUrl = URL(fileURLWithPath: filePath) - - print("====imagefileUrl Path====") - - print(imagefileUrl) - print("====imagefileUrl Path====") - - var selectedImage : UIImage? - - - let selectedImageData = NSData(contentsOf: imagefileUrl) - - if(selectedImageData != nil){ - selectedImage = UIImage(data: selectedImageData! as Data) - }else{ - print("Selected Image Data is null") - } - - - if(userJid == nil){ - result(FlutterError(code: "500", message: "User jid is Empty", details: nil)) - return - } - - var media = MediaData() - - if let (_, fileName ,localFilePath,fileKey,fileSize) = MediaUtils.compressImage(imageData : selectedImageData! as Data){ - print("#media size after \(fileSize)") - media.mediaType = .image - media.fileURL = localFilePath - media.fileName = fileName - media.fileSize = fileSize - media.fileKey = fileKey - media.base64Thumbnail = MediaUtils.convertImageToBase64String(img: selectedImage!) - media.caption = caption - - } - - FlyMessenger.sendImageMessage(toJid: userJid!, mediaData: media, replyMessageId: replyMessageId){isSuccess,error,message in - if isSuccess { - print("Send Image--->") -// print(message as Any) - - var response = JSONSerializer.toJson(message as Any) - response = response.replacingOccurrences(of: "{\"some\":", with: "") - response = response.replacingOccurrences(of: "}}", with: "}") -// print(response) - result(response) - }else{ - print("<---Send Image Failed--->") - } - } - } - - static func sendAudioMessage(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let userJid = args["jid"] as? String ?? "" - let replyMessageId = args["replyMessageId"] as? String ?? "" - let isRecorded = args["isRecorded"] as? Bool ?? false - let audiofilePath = args["filePath"] as? String ?? "" - let audiofileUrl = URL(fileURLWithPath: audiofilePath) - - print("audio File URL") - print(audiofilePath) - print(audiofileUrl.absoluteString as Any) - - MediaUtils.processAudio(url: audiofileUrl) { isSuccess, fileName ,localPath, fileSize, duration, fileKey in - print("#media \(duration)") - if let localPathURL = localPath, isSuccess{ - var mediaData = MediaData() - mediaData.fileName = fileName - mediaData.fileURL = localPathURL - mediaData.fileSize = fileSize - mediaData.duration = duration - mediaData.fileKey = fileKey - mediaData.mediaType = .audio - - FlyMessenger.sendAudioMessage(toJid: userJid, mediaData: mediaData, replyMessageId : replyMessageId, isRecorded : isRecorded) { isSuccess,error,message in - if message != nil { - print("CAPTURE_RESPONSE") - print("sendAudioMessage") - dump(message) - - var audioResponse = JSONSerializer.toJson(message as Any) - - audioResponse = audioResponse.replacingOccurrences(of: "{\"some\":", with: "") - audioResponse = audioResponse.replacingOccurrences(of: "}}", with: "}") - print(audioResponse) - - result(audioResponse) - - } - } - } - } - - } - - static func isArchivedSettingsEnabled(call: FlutterMethodCall, result: @escaping FlutterResult){ - result(FlyDefaults.isArchivedChatEnabled) - } - - static func cancelNotifications(call: FlutterMethodCall, result: @escaping FlutterResult){ - result("") - } - - static func downloadMedia(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let mediaMessageId = args["mediaMessage_id"] as? String ?? "" - - print("-->download Media id\(mediaMessageId)") - - FlyMessenger.downloadMedia(messageId: mediaMessageId){ isSuccess,error,message in - print("-->mediaMessageId \(isSuccess)") - if(!isSuccess){ - print("-->downloadMedia error \(error)") - print("-->downloadMedia message \(message)") - } - result(isSuccess) - } - } - static func iOSFileExist(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let filePath = args["file_path"] as? String ?? "" - - let fileManagerr = FileManager.default - - let existsOrNot = fileManagerr.fileExists(atPath: filePath) -// print("file check--> \(![fileManager fileExistsAtPath:[storeURL path]])") - print("file exists--> \(existsOrNot)") - result(existsOrNot) - } - static func updateFavouriteStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - - let messageID = args["messageID"] as? String ?? "" - let chatUserJID = args["chatUserJID"] as? String ?? "" - let chatType = args["chatType"] as? String ?? "" - let isFavourite = args["isFavourite"] as? Bool ?? false - - var favChatType : ChatType - if(chatType == "chat"){ - favChatType = .singleChat - }else{ - favChatType = .groupChat - } - - ChatManager.updateFavouriteStatus(messageId: messageID, chatUserId: chatUserJID, isFavourite: isFavourite, chatType: favChatType) { (isSuccess, flyError, data) in - - - result(isSuccess) - - } - } - - static func getUserList(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let pageNumber = args["page"] as? Int ?? 1 - let searchTerm = args["search"] as? String ?? "" - - ContactManager.shared.getUsersList(pageNo: pageNumber, pageSize: 20, search: searchTerm){ isSuccess,flyError,flyData in - if isSuccess { - var userlist = flyData - print(userlist) - print("-----") - dump(userlist) - let userData = JSONSerializer.toJson(userlist.getData()) - print("==========") - print("Json data--->\(userData)") - print("==========") - - let totalPages = userlist["totalPages"] as! Int - let message = userlist["message"] as! String - var userlistJson = "{\"total_pages\": " + String(totalPages) + ",\"message\" : \"" + message + "\",\"status\" : true,\"data\":" + userData + "}" - - userlistJson = userlistJson.replacingOccurrences(of: "{\"some\": {}}", with: "\"\"") - userlistJson = userlistJson.replacingOccurrences(of: "\"nickName\": {}", with: "\"nickName\": \"\"") - - - print("userlist json after replacing---> \(userlistJson)") - result(userlistJson) - }else{ - // result(FlutterError(code: "500", message: flyError?.description, details: nil)) - } - } - - } - - static func getRegisteredUsers(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as? Dictionary - let fromServer = args?["server"] as? Bool ?? false - - ContactManager.shared.getRegisteredUsers(fromServer: fromServer) { isSuccess, flyError, flyData in - var data = flyData - if isSuccess { - - print(data.getData()) - let userData = (data.getData() as? [ProfileDetails])?.count == 0 ? "[]" : JSONSerializer.toJson(data.getData()) - // let userData = data.getData() - print("user data---> \(userData)") - - - - let message = data["message"] as! String - var userlistJson = "{\"message\" : \"" + message + "\",\"status\" : true,\"data\":" + userData + "}" - - userlistJson = userlistJson.replacingOccurrences(of: "{\"some\": {}}", with: "\"\"") - userlistJson = userlistJson.replacingOccurrences(of: "\"nickName\": {}", with: "\"nickName\": \"\"") - - print("getRegisteredUsers---> \(userlistJson)") - result(userlistJson) - } else{ - //data.getMessage() - result(FlutterError(code: "500", message: flyError?.description, details: nil)) - } - } - } - - static func sendVideoMessage(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let userJid = args["jid"] as? String ?? "" - let caption = args["caption"] as? String ?? "" - - let filePath = args["filePath"] as? String ?? "" - - let replyMessageId = args["replyMessageId"] as? String ?? "" - - print("====File Path====") - - print(filePath) - print("====File Path====") - - let videoFileUrl = URL(fileURLWithPath: filePath) - print("====File URL====") - print(videoFileUrl) - print("====File URL====") - var thumbnail : UIImage? - do { - let asset = AVURLAsset(url: videoFileUrl, options: nil) - let imgGenerator = AVAssetImageGenerator(asset: asset) - imgGenerator.appliesPreferredTrackTransform = true - let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1), actualTime: nil) - thumbnail = UIImage(cgImage: cgImage) - // return thumbnail - } catch let error { - print("*** Error generating thumbnail: \(error.localizedDescription)") - // return nil - } - - let base64Img = MediaUtils.convertImageToBase64(img: thumbnail!) - - - var media = MediaData() - - MediaUtils.compressVideo(videoURL: videoFileUrl) { isSuccess, url, fileName, fileKey, fileSize , duration in - if let compressedURL = url{ - - media.mediaType = .video - media.fileURL = compressedURL - media.fileName = fileName - media.fileSize = fileSize - media.fileKey = fileKey - media.duration = duration - media.base64Thumbnail = base64Img - media.caption = caption - print("=====MEDIA DATA======") - print(compressedURL) - print(fileName) - print(fileSize) - print(fileKey) - print(duration) - print(base64Img) - print(caption) - FlyMessenger.sendVideoMessage(toJid: userJid, mediaData: media, replyMessageId: replyMessageId){ isSuccess,error,message in - if let chatMessage = message { - print("CAPTURE_RESPONSE") - print("sendVideoMessage") - dump(message) - - var sendVideoResposne = JSONSerializer.toJson(chatMessage) - - sendVideoResposne = sendVideoResposne.replacingOccurrences(of: "{\"some\":", with: "") - sendVideoResposne = sendVideoResposne.replacingOccurrences(of: "}}", with: "}") - print(sendVideoResposne) - result(sendVideoResposne) - - } - } - }else{ - print("Video Compression Error") - } - } - - - } - - func generateVideoThumnail(path: URL) -> UIImage? { - do { - let asset = AVURLAsset(url: path, options: nil) - let imgGenerator = AVAssetImageGenerator(asset: asset) - imgGenerator.appliesPreferredTrackTransform = true - let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1), actualTime: nil) - let thumbnail = UIImage(cgImage: cgImage) - return thumbnail - } catch let error { - print("*** Error generating thumbnail: \(error.localizedDescription)") - return nil - } - } - - static func sendContactMessage(call: FlutterMethodCall, result: @escaping FlutterResult){ - - let args = call.arguments as! Dictionary - let userJid = args["jid"] as? String ?? "" - let contactName = args["contact_name"] as? String ?? "" - let replyMessageId = args["replyMessageId"] as? String ?? "" - let contactList = args["contact_list"] as? [String] ?? [] - - FlyMessenger.sendContactMessage(toJid: userJid, contactName: contactName, contactNumbers: contactList, replyMessageId: replyMessageId){ isSuccess,error,message in - if isSuccess { - - var contactMessageResponse = JSONSerializer.toJson(message as Any) - - contactMessageResponse = contactMessageResponse.replacingOccurrences(of: "{\"some\":", with: "") - contactMessageResponse = contactMessageResponse.replacingOccurrences(of: "}}", with: "}") - - print("sendContactMessage \(contactMessageResponse)") - - result(contactMessageResponse) - - } - } - } - - - static func sendDocumentMessage(call: FlutterMethodCall, result: @escaping FlutterResult){ - - let args = call.arguments as! Dictionary - let userJid = args["jid"] as? String ?? "" - - let replyMessageId = args["replyMessageId"] as? String ?? "" - - let documentFilePath = args["file"] as? String ?? "" - let documentFileUrl = URL(fileURLWithPath: documentFilePath) - - - MediaUtils.processDocument(url: documentFileUrl){ isSuccess,localPath,fileSize,fileName, errorMessage in - if !isSuccess { - if !errorMessage.isEmpty { - print("Document Processing Issue") - } - return - } - if let localPathURL = localPath, isSuccess { - var mediaData = MediaData() - mediaData.fileName = fileName - mediaData.fileURL = localPathURL - mediaData.fileSize = fileSize - mediaData.mediaType = .document - - FlyMessenger.sendDocumentMessage(toJid: userJid,mediaData: mediaData,replyMessageId: replyMessageId) { isSuccess, error, message in - if message != nil { - print("sendDocumentMessage") - var documentMessageResponse = JSONSerializer.toJson(message as Any) - - documentMessageResponse = documentMessageResponse.replacingOccurrences(of: "{\"some\":", with: "") - documentMessageResponse = documentMessageResponse.replacingOccurrences(of: "}}", with: "}") - - result(documentMessageResponse) - - } - - } - - } else { - - } - } - } - - static func getProfileStatusList(call: FlutterMethodCall, result: @escaping FlutterResult){ - let profileStatus = ChatManager.getAllStatus() - print("Status list -->\(profileStatus)") - if(profileStatus.isEmpty){ - result(nil) - } - let profileStatusJson = JSONSerializer.toJson(profileStatus) - print(profileStatusJson) - result(profileStatusJson) - - } - static func insertDefaultStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let status = args["status"] as? String ?? "" - - print("Insert Status-->\(status)") - let insertStatus: () = ChatManager.saveProfileStatus(statusText: status, currentStatus: false) - print("Insert Status Result-->\(insertStatus)") - result(true) - - } - - static func insertNewProfileStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let status = args["status"] as? String ?? "" - print("Insert New Status ---> \(status)") - var getAllStatus: [ProfileStatus] = [] - getAllStatus = ChatManager.getAllStatus() - for status in getAllStatus { - ChatManager.updateStatus(statusId: status.id, statusText: status.status, currentStatus: false) - } - ChatManager.saveProfileStatus(statusText: status, currentStatus: true) - result("{\"status\" : true }") - - } - static func isTrailLicence(call: FlutterMethodCall, result: @escaping FlutterResult){ - result(true) - } - - static func setMyProfileStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let statusText = args["status"] as? String ?? "" - let statusId = args["statusId"] as? String ?? "" - - print("updating item details===>\(statusText)==>\(statusId)") - var getAllStatus: [ProfileStatus] = [] - getAllStatus = ChatManager.getAllStatus() - for status in getAllStatus { - print("checking status id--> \(status.id) --> \(statusId)") - if(status.id == statusId) { - print("setting status-->\(statusId)-->\(statusText)") - ChatManager.updateStatus(statusId: statusId ,statusText: statusText,currentStatus: true) - } - else{ - ChatManager.updateStatus(statusId: status.id, statusText: status.status, currentStatus: false) - } - } - -// var chatUpdateStatus = ChatManager.updateStatus(statusId: statusId, statusText: statusText, currentStatus: true) - - let statusUpdateJSON = "{\"message\": \"Status Update Success\",\"status\": true}" - - result(statusUpdateJSON) - - } - - static func getStatus() -> [ProfileStatus] { - let profileStatus = ChatManager.getAllStatus() - print("Get Status Started profileList Count \(profileStatus.count)") - return profileStatus - } - - static func deleteProfileStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let statusId = args["id"] as? String ?? "" - print("deleteing status ID-->\(statusId)") - ChatManager.deleteStatus(statusId: statusId) - - result(true) - - } - - static func isUserUnArchived(call: FlutterMethodCall, result: @escaping FlutterResult){ - - let args = call.arguments as! Dictionary - - let userJid = args["jid"] as? String ?? "" - - let isUserUnarchived : Bool = ChatManager.shared.isUserUnArchived(jid: userJid) - result(isUserUnarchived) - - } - static func forwardMessagesToMultipleUsers(call: FlutterMethodCall, result: @escaping FlutterResult){ - - let args = call.arguments as! Dictionary - - let messageIDList = args["message_ids"] as? [String] ?? [] - let userList = args["userList"] as? [String] ?? [] - - FlyMessenger.composeForwardMessage(messageIds: messageIDList, toJidList: userList) - - result("Message Forward Success") - - } - - static func isMemberOfGroup(call: FlutterMethodCall, result: @escaping FlutterResult){ - - let args = call.arguments as! Dictionary - - let groupJid = args["jid"] as? String ?? "" - let currentJid = FlyDefaults.myXmppUsername + "@" + FlyDefaults.xmppDomain - let participantJid = args["userjid"] as? String ?? currentJid - - - let isMember = GroupManager.shared.isParticiapntExistingIn(groupJid: groupJid, - participantJid: participantJid) - - print("isMemberOfGroup--> \(isMember.doesExist)") - result(isMember.doesExist) - - } - static func getGroupMembersList(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let groupJid = args["jid"] as? String ?? "" - var groupMembers = [GroupParticipantDetail]() - - groupMembers = GroupManager.shared.getGroupMemebersFromLocal(groupJid: groupJid).participantDetailArray.filter({$0.memberJid != FlyDefaults.myJid}) -// dump("groupMembers--> \(JSONSerializer.toJson(groupMembers))") - let myJid = GroupManager.shared.getGroupMemebersFromLocal(groupJid: groupJid).participantDetailArray.filter({$0.memberJid == FlyDefaults.myJid}) - groupMembers = groupMembers.sorted(by: { $0.profileDetail?.name.lowercased() ?? "" < $1.profileDetail?.name.lowercased() ?? "" }) - groupMembers.insert(contentsOf: myJid, at: 0) - - var groupMemberProfile: String = "[" - - groupMembers.forEach{groupMember in - print("groupMembers jid--> \(String(describing: groupMember.profileDetail?.jid))") - print("groupMembers--> \(groupMember.profileDetail?.image)") - print("groupMembers--> \(groupMember.profileDetail?.name)") - var profileDetailJson = JSONSerializer.toJson(groupMember.profileDetail as Any) - profileDetailJson = profileDetailJson.replacingOccurrences(of: "{\"some\":", with: "") - profileDetailJson = profileDetailJson.replacingOccurrences(of: "}}", with: "}") - - print("profileDetailJson--> \(profileDetailJson)") - - groupMemberProfile = groupMemberProfile + profileDetailJson + "," - - } - groupMemberProfile = groupMemberProfile.dropLast() + "]" - - print("groupMemberProfile \(groupMemberProfile)") - - result(groupMemberProfile) - } - static func enableDisableArchivedSettings(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let enableArchive = args["enable"] as? Bool ?? false - ChatManager.enableDisableArchivedSettings(enableArchive) { isSuccess, error, data in - if isSuccess { -// FlyDefaults.isArchivedChatEnabled = !FlyDefaults.isArchivedChatEnabled - result(isSuccess) - } - } - } - - static func getFavouriteMessages(call: FlutterMethodCall, result: @escaping FlutterResult){ - - var starredMessages = ChatManager.getFavouriteMessages() - - var starredMessagesJson = JSONSerializer.toJson(starredMessages) - - starredMessagesJson = starredMessagesJson.replacingOccurrences(of: "{\"some\":", with: "") - starredMessagesJson = starredMessagesJson.replacingOccurrences(of: "}}", with: "}") - result(starredMessagesJson) - } - - static func clearAllConversation(call: FlutterMethodCall, result: @escaping FlutterResult){ - - ChatManager.shared.clearAllConversation{ isSuccess, error, data in - result(isSuccess) - } - } - - static func getUnsentMessageOfAJid(call: FlutterMethodCall, result: @escaping FlutterResult){ - - result("") - - } - - static func saveUnsentMessage(call: FlutterMethodCall, result: @escaping FlutterResult){ - - result("") - - } - static func getRingtoneName(call: FlutterMethodCall, result: @escaping FlutterResult){ - - result("[]") - - } - static func getDefaultNotificationUri(call: FlutterMethodCall, result: @escaping FlutterResult){ - - result("[]") - - } - - static func verifyToken(call: FlutterMethodCall, result: @escaping FlutterResult){ -// let args = call.arguments as! Dictionary - -// let userName = args["userName"] as? String -// let token = args["googleToken"] as? String ?? "" - - result("") - - } - - static func getUserProfile(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let server = args["server"] as? Bool ?? false - let userjid = args["jid"] as? String ?? "" - // let JID = FlyDefaults.myXmppUsername + "@" + FlyDefaults.xmppDomain - - print("getting user profile from userjid-->\(userjid)") - print("getting user profile from server-->\(server)") - do { - try ContactManager.shared.getUserProfile(for: userjid, fetchFromServer: false, saveAsFriend: true){ isSuccess, flyError, flyData in - var data = flyData - if isSuccess { - - let profileJSON = "{\"data\" : " + JSONSerializer.toJson(data.getData() as Any) + ",\"status\": true}" - print(profileJSON) - result(profileJSON) - } else{ - print(flyError!.localizedDescription) - result(FlutterError(code: "500", message: flyError!.localizedDescription, details: nil)) - } - } - }catch{ - print("Error while calling User Profile Details") - } - - } - - static func updateMyProfile(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - // let jid = args["jid"] as? String ?? "" - let email = args["email"] as? String ?? "" - let mobile = args["mobile"] as? String ?? "" - let nickName = args["name"] as? String ?? "" - let status = args["status"] as? String ?? "" - let image = args["image"] as? String ?? nil - let userJid = FlyDefaults.myXmppUsername + "@" + FlyDefaults.xmppDomain - print("=====Response Capture=====") - print("jid===>" + userJid) - print("email===>" + email) - print("mobile===>" + mobile) - print("nickName===>" + nickName) - print("status===>" + status) - print("image===>" + (image ?? "Image is Nil")) - -// var isImagePicked = false - - var myProfile = FlyProfile(jid: userJid) - - myProfile.email = email - - myProfile.mobileNumber = mobile - - myProfile.nickName = nickName - myProfile.name = nickName - - myProfile.status = status - - if(image != nil){ - print("Image is not null if condition") - myProfile.image = image!//xyaz.jpeg -// isImagePicked = false - }else{ - print("Image is null else condition") -// isImagePicked = false - } - - print("Profile json ===>" + JSONSerializer.toJson(myProfile)) - - ContactManager.shared.updateMyProfile(for: myProfile){ isSuccess, flyError, flyData in - if isSuccess { - var data = flyData - - let profileData = data.getData() - let message = data.getMessage() - print("profile update response-->\(profileData)") - - let profileDataJson = JSONSerializer.toJson(profileData) - - - var profileResponseJson = "{\"status\": true ,\"message\" : \"\(message)\" ,\"data\": \(profileDataJson) }" - - print("Profile response-->\(profileResponseJson)") - - saveMyProfileDataToUserDefaults(profile: myProfile) - - result(profileResponseJson) - } else{ - print("Update Profile Issue==> " + flyError!.localizedDescription) - result(FlutterError(code: "500", message: flyError!.localizedDescription, details: nil)) - - } - } - - } - - static func removeProfileImage(call: FlutterMethodCall, result: @escaping FlutterResult){ - ContactManager.shared.removeProfileImage(){ isSuccess, flyError, flyData in - if isSuccess { - print("removeProfileImage raw data\(flyData)") - var data = flyData - -// let profileData = data.getData() -// let message = data.getMessage() -// print("profile Image update response-->\(profileData)") -// -// let profileDataJson = JSONSerializer.toJson(profileData) -// -// -// var profileResponseJson = "{\"status\": true ,\"message\" : \"\(message)\" ,\"data\": \(profileDataJson) }" -// -// print("removeProfileImage\(profileResponseJson)") - -// let responseJson = Commons.json(from: data) as Any -// print(responseJson) - result(isSuccess) - } else{ - print(flyError!.localizedDescription) - } - } - } - - static func saveMyProfileDataToUserDefaults(profile : FlyProfile){ - FlyDefaults.myName = profile.name - FlyDefaults.myImageUrl = profile.image - FlyDefaults.myMobileNumber = profile.mobileNumber - FlyDefaults.myStatus = profile.status - FlyDefaults.myEmail = profile.email - - self.saveMyJidAsContacts() - } - - static func saveMyJidAsContacts() { - print("saveMyJidAsContacts jid -->\(FlyDefaults.myJid)") - let profileData = ProfileDetails(jid: FlyDefaults.myJid) - profileData.name = FlyDefaults.myName - profileData.nickName = FlyDefaults.myNickName - profileData.mobileNumber = FlyDefaults.myMobileNumber - profileData.email = FlyDefaults.myEmail - profileData.status = FlyDefaults.myStatus - profileData.image = FlyDefaults.myImageUrl - - FlyDatabaseController.shared.rosterManager.saveContact(profileDetailsArray: [profileData], chatType: .singleChat, contactType: .live, saveAsTemp: false, calledBy: "") - } - - static func getMediaEndPoint(call: FlutterMethodCall, result: @escaping FlutterResult){ - - let urlString = FlyDefaults.baseURL + "" + "media" + "/" - - result(urlString) - - } - - static func syncContacts(call: FlutterMethodCall, result: @escaping FlutterResult){ - - ContactSyncManager.shared.syncContacts(){ isSuccess, flyError, flyData in - var data = flyData - if isSuccess { - // Contact synced successfully update the UI - } else{ - print(data.getMessage() as! String) - } - } - - } - static func updateMyProfileImage(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let profileImage = args["image"] as? String ?? "" - - ContactManager.shared.updateMyProfileImage(image: profileImage){ isSuccess, flyError, flyData in - if isSuccess { - - var data = flyData - - let profileData = data.getData() - let message = data.getMessage() - print("profile Image update response-->\(profileData)") - - let profileDataJson = JSONSerializer.toJson(profileData) - - - var profileResponseJson = "{\"status\": true ,\"message\" : \"\(message)\" ,\"data\": \(profileDataJson) }" - - print("Profile Image Update response-->\(profileResponseJson)") - - result(profileResponseJson) - - - } else{ - print("updateMyProfileImage Error-->\(flyError!.localizedDescription)") - result(FlutterError(code: "500", message: flyError!.localizedDescription, details: nil)) - } - } - - } - - static func contactSyncStateValue(call: FlutterMethodCall, result: @escaping FlutterResult){ - - } - - static func contactSyncState(call: FlutterMethodCall, result: @escaping FlutterResult){ - // NotificationCenter.default.addObserver(self, selector: #selector(self.contactSyncCompleted(notification:)), name: NSNotification.Name(FlyConstants.contactSyncState), object: nil) - // @objc func contactSyncCompleted(notification: Notification){ - // if let contactSyncState = notification.userInfo?[FlyConstants.contactSyncState] as? String { - // switch ContactSyncState(rawValue: contactSyncState) { - // case .inprogress: - // //Update the UI - // case .success: - // //Update the UI - // case .failed: - // //Update the UI - // } - // } - // } - - } - - - static func revokeContactSync(call: FlutterMethodCall, result: @escaping FlutterResult){ - - - } - static func getUsersWhoBlockedMe(call: FlutterMethodCall, result: @escaping FlutterResult){ - - let args = call.arguments as! Dictionary - - let isFetchFromServer = args["server"] as? Bool ?? false - - ContactManager.shared.getUsersWhoBlockedMe(fetchFromServer: isFetchFromServer){ isSuccess, flyError, flyData in - - var data = flyData - - if isSuccess { - let blockedprofileDetailsArray = data.getData() as! [ProfileDetails] - print("blockedprofileDetailsArray-->\(blockedprofileDetailsArray)") - } else{ - print(flyError!.localizedDescription) - } - } - } - static func getUnKnownUserProfiles(call: FlutterMethodCall, result: @escaping FlutterResult){ - - - } - static func getMyProfileStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ - - - } - - static func getMyBusyStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ - let profileStatus = ChatManager.shared.getMyBusyStatus() - result(JSONSerializer.toJson(profileStatus)) - } - - static func setMyBusyStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let userStatus = args["status"] as? String ?? "" - - ChatManager.shared.setMyBusyStatus(userStatus) - result(true) - } - static func enableDisableBusyStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ - - let args = call.arguments as! Dictionary - - let busyStatusVal = args["enable"] as? Bool ?? false - - ChatManager.shared.enableDisableBusyStatus(busyStatusVal) - - result(true) - - } - - static func insertBusyStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let busyStatus = args["busy_status"] as? String ?? "" - - - result(FlyDatabaseController.shared.userBusyStatusManager.saveStatus(busyStatus: BusyStatus(statusText: busyStatus))) - } - - static func getBusyStatusList(call: FlutterMethodCall, result: @escaping FlutterResult){ - let busyStatusList = ChatManager.shared.getBusyStatusList() - print("Get Status Started profileList Count \(busyStatusList.count)") - var busyStatusJsonList = JSONSerializer.toJson(busyStatusList) - result(busyStatusJsonList) - } - - static func deleteBusyStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let busyId = args["id"] as? String ?? "" - let status = args["status"] as? String ?? "" - let isCurrentStatus = args["isCurrentStatus"] as? Bool ?? false - - let busyStatus = BusyStatus(statusText: status, isCurrentStatus: isCurrentStatus) - - print(busyStatus) - -// ChatManager.shared.deleteBusyStatus(busyStatus) - ChatManager.shared.deleteBusyStatus(statusId: busyId) - - result(true) - - - } - static func enableDisableHideLastSeen(call: FlutterMethodCall, result: @escaping FlutterResult){ - - - let args = call.arguments as! Dictionary - - let enableLastSeen = args["enable"] as? Bool ?? false - - print("calling enableDisableHideLastSeen \(enableLastSeen)") - ChatManager.enableDisableHideLastSeen(EnableLastSeen: enableLastSeen) { isSuccess, flyError, flyData in - - print("enableDisableHideLastSeen response \(isSuccess)") - result(isSuccess) - } - } - static func isHideLastSeenEnabled(call: FlutterMethodCall, result: @escaping FlutterResult){ - - result(ChatManager.isLastSeenEnabled()) - } - static func deleteMessagesForMe(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let jid = args["jid"] as? String ?? "" - let chatType = args["chat_type"] as? String ?? "" - let isMediaDelete = args["isMediaDelete"] as? Bool ?? false - let messageIDList = args["message_ids"] as? [String] ?? [] - - var deleteChatType : ChatType - if(chatType == "chat"){ - deleteChatType = .singleChat - }else{ - deleteChatType = .groupChat - } - - ChatManager.deleteMessagesForMe(toJid: jid, messageIdList: messageIDList, deleteChatType: deleteChatType,isRevokeMediaAccess: isMediaDelete) { (isSuccess, error, data) in - - result(isSuccess) - } - - } - static func deleteMessagesForEveryone(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let jid = args["jid"] as? String ?? "" - let chatType = args["chat_type"] as? String ?? "" - let isMediaDelete = args["isMediaDelete"] as? Bool ?? false - let messageIDList = args["message_ids"] as? [String] ?? [] - - var deleteChatType : ChatType - if(chatType == "chat"){ - deleteChatType = .singleChat - }else{ - deleteChatType = .groupChat - } - - ChatManager.deleteMessagesForEveryone(toJid: jid, messageIdList: messageIDList, deleteChatType: deleteChatType,isRevokeMediaAccess: isMediaDelete) { (isSuccess, error, data) in - - result(isSuccess) - - } - - } - static func markAsRead(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let jid = args["jid"] as? String ?? "" - ChatManager.markConversationAsRead(for: [jid]) - result(true) - } - static func getMessagesOfJid(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let userJid = args["JID"] as? String ?? "" - print("Get Messages of JID --->") - print(userJid) - let messages : [ChatMessage] = FlyMessenger.getMessagesOf(jid: userJid) - - /* do { - let dic = messages.last?.toDictionary() - print(dic) - let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted) - // here "jsonData" is the dictionary encoded in JSON data - let convertedString1 = String(data: jsonData, encoding: .utf8) // the data will be converted to the string - - print("Converted String --> \(convertedString1)") - - let decoded = try JSONSerialization.jsonObject(with: jsonData, options: []) - // here "decoded" is of type Any, decoded from JSON data - print(decoded) - - let convertedString = String(data: decoded as! Data, encoding: .utf8) // the data will be converted to the string - print("Converted String \(convertedString)") - // you can now cast it with the right type - if let dictFromJSON = decoded as? [String:String] { - // use dictFromJSON - } - } catch { - print(error.localizedDescription) - } - - print("Get Messages of JID --->", messages.last?.mediaChatMessage?.mediaThumbImage) - var medmes = messages.last?.mediaChatMessage?.mediaThumbImage.replacingOccurrences(of: "\n", with: "") - var userChatHistory2 = JSONSerializer.toJson(medmes) - print(userChatHistory2)*/ - var userChatHistory = JSONSerializer.toJson(messages) -// dump(userChatHistory) - - userChatHistory = userChatHistory.replacingOccurrences(of: "{\"some\":", with: "") - userChatHistory = userChatHistory.replacingOccurrences(of: "}}", with: "}") - -// let json = try! DSON. -// print("====DSON=====") -// print(json) -// print("====DSON=====") - -// userChatHistory = userChatHistory.replacingOccurrences(of: "\"messageStatus\":", with: "\"iosMessageStatus\":") - print(userChatHistory) - result(userChatHistory) - - - } - - static func markAsReadDeleteUnreadSeparator(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let jid = args["jid"] as? String ?? "" - - ChatManager.markConversationAsRead(for: [jid]) -// FlyMessenger.deleteUnreadMessageSeparatorOfAConversation(jid)//not found need to implement here after adding - result(true) - } - - static func deleteUnreadMessageSeparatorOfAConversation(call: FlutterMethodCall, result: @escaping FlutterResult){ -// let args = call.arguments as! Dictionary - -// let jid = args["jid"] as? String ?? nil - - - } - static func getRecalledMessagesOfAConversation(call: FlutterMethodCall, result: @escaping FlutterResult){ -// let args = call.arguments as! Dictionary - -// let jid = args["jid"] as? String ?? nil - - - } - static func uploadMedia(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let messageid = args["messageid"] as? String ?? "" - - FlyMessenger.uploadMedia(messageId: messageid) { isSuccess, error, chatMessage in - if isSuccess{ - result(true) - }else{ - result(false) - } - } - - } - static func getMessagesUsingIds(call: FlutterMethodCall, result: @escaping FlutterResult){ -// let args = call.arguments as! Dictionary - -// var messages : [ChatMessage] = FlyMessenger.getMessagesUsingIds(MESSAGE_MIDS) - - - } - static func updateMediaDownloadStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ -// let args = call.arguments as! Dictionary - - - } - static func updateMediaUploadStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ -// let args = call.arguments as! Dictionary - - - } - static func cancelMediaUploadOrDownload(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let messageId = args["messageId"] as? String ?? "" - - FlyMessenger.cancelMediaUploadOrDownload(messageId: messageId){ isSuccess in - if isSuccess{ - print("cancel media upload true") - result(true) - }else{ - print("cancel media upload false") - result(false) - } - } - - } - static func setMediaEncryption(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let isEncryptionEnable = args["encryption"] as? Bool ?? true - - ChatManager.setMediaEncryption(isEnable: isEncryptionEnable) - } - static func deleteAllMessages(call: FlutterMethodCall, result: @escaping FlutterResult){ - _ = call.arguments as! Dictionary - - } - static func getGroupJid(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let groupId = args["groupId"] as? String ?? "" - - do - { - let groupIDResponse = try FlyUtils.getGroupJid(groupId: groupId) - result(groupIDResponse) - - }catch let sdkError{ - result(FlutterError(code: "500", message: "Unable to get JID", details: sdkError.localizedDescription)) - } - - } - static func updateRecentChatPinStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let userJID = args["jid"] as? String ?? "" - let pin_recent_chat = args["pin_recent_chat"] as? Bool ?? false - - ChatManager.updateRecentChatPinStatus(jid: userJID, pinRecentChat: pin_recent_chat) - } - - static func updateChatMuteStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ - - let args = call.arguments as! Dictionary - - let userJID = args["jid"] as? String ?? "" - let muteStatus = args["mute_status"] as? Bool ?? false - ChatManager.updateChatMuteStatus(jid: userJID, muteStatus: muteStatus) - } - static func sendTypingStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ - - let args = call.arguments as! Dictionary - - let toJid = args["to_jid"] as? String ?? "" - let chattype = args["chattype"] as? String ?? "" - - var chatType : ChatType - if(chattype == "chat"){ - chatType = .singleChat - }else{ - chatType = .groupChat - } - - ChatManager.sendTypingStatus(to: toJid, chatType: chatType) - } - - static func sendTypingGoneStatus(call: FlutterMethodCall, result: @escaping FlutterResult){ - - let args = call.arguments as! Dictionary - - let toJid = args["to_jid"] as? String ?? "" - let chattype = args["chattype"] as? String ?? "" - - var chatType : ChatType - if(chattype == "chat"){ - chatType = .singleChat - }else{ - chatType = .groupChat - } - - ChatManager.sendTypingGoneStatus(to: toJid, chatType: chatType) - } - - static func deleteRecentChat(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - var userJID = args["jid"] as? String ?? "" - - var userJIDs: [String] = [] - userJIDs.append(userJID) - - ChatManager.deleteRecentChats(jids: userJIDs, completionHandler: { isSuccess, flyError, flyData in - result(isSuccess) - }) - - } - static func deleteRecentChats(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let userJIDList = args["jidlist"] as? [String] ?? [] - - ChatManager.deleteRecentChats(jids: userJIDList, completionHandler: { isSuccess, FlyError, flyData in - result(isSuccess) - }) - - } - static func makeAdmin(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - var groupJID = args["jid"] as? String ?? "" - var userJID = args["userjid"] as? String ?? "" - - do{ - - try GroupManager.shared.makeAdmin(groupJid: groupJID, userJid: userJID, completionHandler: { isSuccess, flyError, flyData in - if isSuccess { - // update UI - result(isSuccess) - } else{ - result(FlutterError(code: "500", message: "Unable to Make User Admin", details: flyError)) - } - }) - }catch let error{ - - result(FlutterError(code: "500", message: "Unable to Make User Admin", details: error.localizedDescription)) - } - - } - - static func setNotificationSound(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let notification_sound = args["enable"] as? Bool ?? false - - Utility.saveInPreference(key: muteNotification, value: notification_sound) - } - - static func updateGroupName(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let groupJID = args["jid"] as? String ?? "" - let groupName = args["name"] as? String ?? "" - - do{ - try GroupManager.shared.updateGroupName(groupJid: groupJID, groupName: groupName, completionHandler: { isSuccess, flyError, flyData in - result(isSuccess) - }) - }catch let error{ - result(FlutterError(code: "500", message: "Unable to Make User Admin", details: error.localizedDescription)) - } - - } - static func updateGroupProfileImage(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let groupJID = args["jid"] as? String ?? "" - let groupImageFile = args["file"] as? String ?? "" - - do{ - try GroupManager.shared.updateGroupProfileImage(groupJid: groupJID, groupProfileImageUrl: groupImageFile, completionHandler: { isSuccess, flyError, flyData in - - result(isSuccess) - - }) - }catch let error{ - result(FlutterError(code: "500", message: "Unable to Update Group Image", details: error.localizedDescription)) - } - - } - static func removeGroupProfileImage(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let groupJID = args["jid"] as? String ?? "" - - do{ - try GroupManager.shared.removeGroupProfileImage(groupJid: groupJID, completionHandler: { isSuccess, flyError, flyData in - result(isSuccess) - }) - }catch let error{ - result(FlutterError(code: "500", message: "Unable to Remove Group Image", details: error.localizedDescription)) - } - - } - static func addUsersToGroup(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let groupJID = args["jid"] as? String ?? "" - let members = args["members"] as? [String] ?? [] - - do{ - try GroupManager.shared.addParticipantToGroup(groupId: groupJID, newUserJidList: members, completionHandler: { isSuccess, flyError, flyData in - result(isSuccess) - }) - }catch let error{ - result(FlutterError(code: "500", message: "Unable to Add Group Members", details: error.localizedDescription)) - } - - } - static func removeMemberFromGroup(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let groupJID = args["jid"] as? String ?? "" - let userJID = args["userjid"] as? String ?? "" - - do{ - try GroupManager.shared.removeParticipantFromGroup(groupId: groupJID, removeGroupMemberJid: userJID, completionHandler: { isSuccess, flyError, flyData in - result(isSuccess) - }) - }catch let error{ - result(FlutterError(code: "500", message: "Unable to remove member from group", details: error.localizedDescription)) - } - - } - - static func isBusyStatusEnabled(call: FlutterMethodCall, result: @escaping FlutterResult){ - result(ChatManager.shared.isBusyStatusEnabled()) - } - - static func getUserLastSeenTime(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let jid = args["jid"] as? String ?? "" - - print("getUserLastSeenTime called") - - ChatManager.getUserLastSeen( for: jid) { isSuccess, flyError, flyData in - var data = flyData - print("getUserLastSeenTime response \(isSuccess)") - print("getUserLastSeenTime response \(data)") - if isSuccess { - print(data.getMessage() as! String ) - print(data.getData() as! String ) - -// let dateReceived = data.getData() -// -// let dateFormat = DateFormatter() -// dateFormat.timeStyle = .short -// dateFormat.dateStyle = .short -// dateFormat.doesRelativeDateFormatting = true -// let dateString = dateFormat.string(from: Date(timeIntervalSinceNow: TimeInterval(-(Int(dateReceived) ?? 0)))) -// -// let timeDifference = "\(NSLocalizedString(dateReceived.localized, comment: "")) \(dateString)" -// let lastSeen = timeDifference.lowercased() -// -// print("getUserLastSeenTime response parsed \(lastSeen)") - - } else{ - print(data.getMessage() as! String ) - } - } - } - static func getRecentChatList(call: FlutterMethodCall, result: @escaping FlutterResult){ - - ChatManager.getRecentChatList { (isSuccess, flyError, resultDict) in - if (isSuccess) { - var recentChatList = resultDict - - let recentChatJson = JSONSerializer.toJson(recentChatList.getData()) - - print(recentChatJson) - - - let recentChatListJson = "{\"data\":" + recentChatJson + "}" - - print(recentChatListJson) - result(recentChatListJson) - - } else { - //Fetching recent chat list failed - - } - } - } - - static func getRecentChatListIncludingArchived(call: FlutterMethodCall, result: @escaping FlutterResult){ - - let recentChatList = ChatManager.getRecentChatListIncludingArchived() -// print("recent chat list including archived ---> \(recentChatList)") -// print("recent chat list including archived ---> \(JSONSerializer.toJson(recentChatList))") - result(JSONSerializer.toJson(recentChatList)) - } - static func getRecentChatOf(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let jid = args["jid"] as? String ?? nil - let recentChat = ChatManager.getRecentChatOf(jid:jid!) - - if(recentChat == nil){ - result(nil) - } - - print("recentChat-->\(recentChat)") - - var recentChatJson = JSONSerializer.toJson(recentChat as Any) - recentChatJson = recentChatJson.replacingOccurrences(of: "{\"some\":", with: "") - recentChatJson = recentChatJson.replacingOccurrences(of: "}}", with: "}") - result(recentChatJson) - } - static func recentChatPinnedCount(call: FlutterMethodCall, result: @escaping FlutterResult){ - let recentPinCount = ChatManager.recentChatPinnedCount() - result(recentPinCount) - } - - static func setOnGoingChatUser(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let userJid = args["jid"] as? String ?? "" - ChatManager.setOnGoingChatUser(jid: userJid) - } - static func reportUserOrMessages(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let userJid = args["jid"] as? String ?? "" - - let reportMessage : ReportMessage? = ChatManager.getMessagesForReporting(chatUserJid: userJid, messagesCount: 5) - - var reportMessageJson = JSONSerializer.toJson(reportMessage as Any) - reportMessageJson = reportMessageJson.replacingOccurrences(of: "{\"some\":", with: "") - reportMessageJson = reportMessageJson.replacingOccurrences(of: "}}", with: "}") - print("reportMessageJson=====>") - print(reportMessageJson) - result(reportMessageJson) - - } - static func blockUser(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let userJid = args["userJID"] as? String ?? "" - - do{ - - try ContactManager.shared.blockUser(for: userJid){ isSuccess, flyError, flyData in - - if isSuccess { - var blockUserResponseJson = JSONSerializer.toJson(flyData as Any) - print("before blockUserResponseJson===>") - print(blockUserResponseJson) - blockUserResponseJson = blockUserResponseJson.replacingOccurrences(of: "{\"some\":", with: "") - blockUserResponseJson = blockUserResponseJson.replacingOccurrences(of: "}}", with: "}") - print("blockUserResponseJson=====>") - print(blockUserResponseJson) - result(blockUserResponseJson) - } else{ - print(flyError!.localizedDescription) - result(FlutterError(code: "500", message: "Unable to Block User", details: flyError?.localizedDescription)) - } - } - }catch let error{ - - result(FlutterError(code: "500", message: "Unable to Block User", details: error.localizedDescription)) - } - - } - static func unblockUser(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let userJid = args["userJID"] as? String ?? "" - - do{ - - try ContactManager.shared.unblockUser(for: userJid){ isSuccess, flyError, flyData in - - if isSuccess { - result(true) - } else{ - print(flyError!.localizedDescription) - result(FlutterError(code: "500", message: "Unable to Un-Block User", details: flyError?.localizedDescription)) - } - } - }catch let error{ - result(FlutterError(code: "500", message: "Unable to Un-Block User", details: error.localizedDescription)) - } - - } - static func createGroup(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let groupName = args["group_name"] as? String ?? "" - let file = args["file"] as? String ?? "" - let members = args["members"] as? [String] ?? [] - do{ - - try GroupManager.shared.createGroup(groupName: groupName, participantJidList: members, groupImageFileUrl: file, completionHandler: { isSuccess, flyError, flyData in - if isSuccess { - var createGroupResponseJson = JSONSerializer.toJson(flyData as Any) - print("before createGroupResponseJson===>") - print(createGroupResponseJson) - createGroupResponseJson = createGroupResponseJson.replacingOccurrences(of: "{\"some\":", with: "") - createGroupResponseJson = createGroupResponseJson.replacingOccurrences(of: "}}", with: "}") - print("createGroupResponseJson=====>") - print(createGroupResponseJson) - result(createGroupResponseJson) - } else{ - result(FlutterError(code: "500", message: "Unable to Create Group", details: flyError?.localizedDescription)) - } - }) - }catch let error{ - result(FlutterError(code: "500", message: "Unable to Create Group", details: error.localizedDescription)) - } - - } - - static func clearChat(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let userJid = args["jid"] as? String ?? "" - let userChatType = args["chat_type"] as? String ?? "" - let clearExceptStarred = args["clear_except_starred"] as? Bool ?? false - - var chatType : ChatType? - if(userChatType == "chat"){ - chatType = .singleChat - }else{ - chatType = .groupChat - } - - ChatManager.clearChat(toJid: userJid, chatType: chatType!, clearChatExceptStarred: clearExceptStarred) { (isSuccess, flyerror, resultDict) in - - if(isSuccess){ - result(true) - }else{ - result(false) - } - } - - } - static func getUsersIBlocked(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let fetchFromServer = args["serverCall"] as? Bool ?? false - - - ContactManager.shared.getUsersIBlocked(fetchFromServer: fetchFromServer){ isSuccess, flyError, flyData in - - var data = flyData - - if isSuccess { - let blockedprofileDetailsArray = data.getData() as! [ProfileDetails] - let blockedProfileJson = JSONSerializer.toJson(blockedprofileDetailsArray as Any) - print("Blocked Profile --> \(blockedProfileJson)") - result(blockedProfileJson) - } else{ - print(flyError!.localizedDescription) - result(FlutterError(code: "500", message: "Unable to Get Blocked List", details: flyError?.localizedDescription)) - } - } - - } - static func getMediaMessages(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let userJid = args["jid"] as? String ?? "" - - let mediaMessages : [ChatMessage] = FlyMessenger.getMediaMessagesOf(jid: userJid) - - print("mediaMessages---> \(mediaMessages)") - if(mediaMessages.isEmpty){ - result(nil) - }else{ - - var mediaMsgJson = JSONSerializer.toJson(mediaMessages) - mediaMsgJson = mediaMsgJson.replacingOccurrences(of: "{\"some\":", with: "") - mediaMsgJson = mediaMsgJson.replacingOccurrences(of: "}}", with: "}") - - print(mediaMsgJson) - - result(mediaMsgJson) - } - - -// ChatManager.getVedioImageAudioMessageGroupByMonth(jid: userJid) { chatMessages in -// let mediaMessages : [[ChatMessage]] = chatMessages -// print("mediaMessages---> \(mediaMessages)") -// -// var mediaMsgJson = JSONSerializer.toJson(mediaMessages) -// mediaMsgJson = mediaMsgJson.replacingOccurrences(of: "{\"some\":", with: "") -// mediaMsgJson = mediaMsgJson.replacingOccurrences(of: "}}", with: "}") -// mediaMsgJson = mediaMsgJson.replacingOccurrences(of: "[[", with: "[") -// mediaMsgJson = mediaMsgJson.replacingOccurrences(of: "]]", with: "]") -// -// print(mediaMsgJson) -// -// result(mediaMsgJson) -// } - - } - static func getDocsMessages(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let userJid = args["jid"] as? String ?? "" - - - ChatManager.getDocumentMessageGroupByMonth(jid: userJid) { _,_,data in - var flydata = data - let mediaMessages : [[ChatMessage]] = flydata.getData() as? [[ChatMessage]] ?? [] -// ChatManager.getDocumentMessageGroupByMonth(jid: userJid) { chatMessages in -// let mediaMessages : [[ChatMessage]] = chatMessages - print("getDocsMessages-> \(mediaMessages)") - if (mediaMessages.isEmpty){ - result(nil) - }else{ - var mediaMsgJson = JSONSerializer.toJson(mediaMessages) - mediaMsgJson = mediaMsgJson.replacingOccurrences(of: "{\"some\":", with: "") - mediaMsgJson = mediaMsgJson.replacingOccurrences(of: "}}", with: "}") - mediaMsgJson = mediaMsgJson.replacingOccurrences(of: "[[", with: "[") - mediaMsgJson = mediaMsgJson.replacingOccurrences(of: "]]", with: "]") - print("getDocsMessages--> \(mediaMsgJson)") - result(mediaMsgJson) - } - } - -// print("mediaMessages---> \(mediaMessages)") -// -// var mediaMsgJson = JSONSerializer.toJson(mediaMessages) -// mediaMsgJson = mediaMsgJson.replacingOccurrences(of: "{\"some\":", with: "") -// mediaMsgJson = mediaMsgJson.replacingOccurrences(of: "}}", with: "}") -// -// print(mediaMsgJson) -// -// result(mediaMsgJson) - - } - - static func getLinkMessages(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let userJid = args["jid"] as? String ?? "" - - ChatManager.getLinkMessageGroupByMonth(jid: userJid) { _,_,data in - var flydata = data - let mediaLinkMessages = flydata.getData() as? [[LinkMessage]] ?? [] -// ChatManager.getLinkMessageGroupByMonth(jid: userJid) { linkMessages in -// let mediaLinkMessages = linkMessages - print("getLinkMessages-> \(mediaLinkMessages)") - - if (mediaLinkMessages.isEmpty){ - result(nil) - }else{ - var viewAllMediaLinkMessages: String = "[" - - mediaLinkMessages.forEach { mediaLinkMessage in - mediaLinkMessage.forEach{ linkChatMessage in - let mediaMsgJson = JSONSerializer.toJson(linkChatMessage.chatMessage) - - viewAllMediaLinkMessages = viewAllMediaLinkMessages + mediaMsgJson + "," - print("getLinkMessage--> \(mediaMsgJson)") - - } - - } - viewAllMediaLinkMessages = viewAllMediaLinkMessages.dropLast() + "]" - - print("getLinkMessages Array--> \(viewAllMediaLinkMessages)") - result(viewAllMediaLinkMessages) - } - } - } - - static func isAdmin(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let groupJid = args["group_jid"] as? String ?? "" - let userJid = args["jid"] as? String ?? "" - - result(GroupManager.shared.isAdmin(participantJid: userJid, groupJid: groupJid).isAdmin) - - } - static func leaveFromGroup(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let groupJid = args["groupJid"] as? String ?? "" - let userJid = args["userJid"] as? String ?? "" - - try! GroupManager.shared.leaveFromGroup(groupJid: groupJid, userJid: userJid) { isSuccess,error,data in - result(isSuccess) - } - - } - static func getMediaAutoDownload(call: FlutterMethodCall, result: @escaping FlutterResult){ - result(FlyDefaults.autoDownloadEnable) - } - static func setMediaAutoDownload(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - let autoDownloadEnable = args["enable"] as? Bool ?? false - FlyDefaults.autoDownloadEnable = autoDownloadEnable - result(true) - } - static func getMediaSetting(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let networkType = args["NetworkType"] as? Int ?? 0 - let type = args["type"] as? String ?? "" - - if (networkType == 0){ - switch (type) { - case "Photos": - result(FlyDefaults.autoDownloadMobile["photo"] ?? false) - case "Videos": - result(FlyDefaults.autoDownloadMobile["videos"] ?? false) - case "Audio": - result(FlyDefaults.autoDownloadMobile["audio"] ?? false) - case "Documents": - result(FlyDefaults.autoDownloadMobile["documents"] ?? false) - default: - result(false) - } - - }else{ - switch (type) { - case "Photos": - result(FlyDefaults.autoDownloadWifi["photo"] ?? false) - case "Videos": - result(FlyDefaults.autoDownloadWifi["videos"] ?? false) - case "Audio": - result(FlyDefaults.autoDownloadWifi["audio"] ?? false) - case "Documents": - result(FlyDefaults.autoDownloadWifi["documents"] ?? false) - default: - result(false) - } - } - } - - static func saveMediaSettings(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let photos = args["Photos"] as? Bool ?? false - let videos = args["Videos"] as? Bool ?? false - let audios = args["Audio"] as? Bool ?? false - let documents = args["Documents"] as? Bool ?? false - let networkType = args["NetworkType"] as? Int ?? 0 - - if (networkType == 0){ - FlyDefaults.autoDownloadMobile["photo"] = photos - FlyDefaults.autoDownloadMobile["videos"] = videos - FlyDefaults.autoDownloadMobile["audio"] = audios - FlyDefaults.autoDownloadMobile["documents"] = documents - - }else{ - FlyDefaults.autoDownloadWifi["photo"] = photos - FlyDefaults.autoDownloadWifi["videos"] = videos - FlyDefaults.autoDownloadWifi["audio"] = audios - FlyDefaults.autoDownloadWifi["documents"] = documents - } - - } - - static func updateArchiveUnArchiveChat(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let userJid = args["jid"] as? String ?? "" - let archive = args["isArchived"] as? Bool ?? false - - var userJidList = [] as [String] - userJidList.append(userJid) - - - if(archive){ - ChatManager.archiveChatConversation(jidsToArchive: userJidList) - }else{ - ChatManager.unarchiveChatConversation(jidsToUnarchive: userJidList) - } - - result(true) - - } - static func logoutOfChatSDK(call: FlutterMethodCall, result: @escaping FlutterResult){ - - Utility.saveInPreference(key: isProfileSaved, value: false) - Utility.saveInPreference(key: isLoggedIn, value: false) - - ChatManager.logoutApi { isSuccess, flyError, flyData in - if isSuccess { - print("requestLogout Logout api isSuccess") - - }else{ - print("Logout api error : \(String(describing: flyError))") - - } - } -// ChatManager.enableContactSync(isEnable: ENABLE_CONTACT_SYNC) - ChatManager.disconnect() - ChatManager.shared.resetFlyDefaults() - - result(true) - - } - - static func getMessageOfId(call: FlutterMethodCall, result: @escaping FlutterResult){ - - let args = call.arguments as! Dictionary - - let messageId = args["mid"] as? String ?? "" - - var message : ChatMessage? = FlyMessenger.getMessageOfId(messageId: messageId) - print("getMessageOfId--> \(message)") - - - - var messageJson = JSONSerializer.toJson(message) - messageJson = messageJson.replacingOccurrences(of: "{\"some\":", with: "") - messageJson = messageJson.replacingOccurrences(of: "}}", with: "}") - - print("getMessageOfId--> \(messageJson)") - result(messageJson) - - } - static func getArchivedChatList(call: FlutterMethodCall, result: @escaping FlutterResult){ - - ChatManager.getArchivedChatList { (isSuccess, flyError, resultDict) in - if isSuccess { - var flydata = resultDict - print(flydata.getData()) - - let archiveData = flydata.getData() as? [RecentChat] ?? [] - print("Archive chat list get") - if(archiveData.isEmpty){ - result("{\"data\": [] }") - }else{ - - let archiveChatJson = JSONSerializer.toJson(flydata.getData()) - - print("Archive Chat---> \(archiveChatJson)") - - - let archiveChatListJson = "{\"data\":" + archiveChatJson + "}" - - print("Archive Chat list json---> \(archiveChatListJson)") - result(archiveChatListJson) - } - }else{ - print(flyError!.localizedDescription) - result(FlutterError(code: "500", message: "Unable to Get Archived List", details: flyError?.localizedDescription)) - } - } - - result(true) - - } - - - - static func getProfileDetails(call: FlutterMethodCall, result: @escaping FlutterResult){ - let args = call.arguments as! Dictionary - - let userJid = args["jid"] as? String ?? "" - print(userJid) - let userProfile = ChatManager.profileDetaisFor(jid: userJid) - print("User Profile --->") - var userProfileJson = JSONSerializer.toJson(userProfile as Any) - userProfileJson = userProfileJson.replacingOccurrences(of: "{\"some\":", with: "") - userProfileJson = userProfileJson.replacingOccurrences(of: "}}", with: "}") - result(userProfileJson) -// do { -// try ContactManager.shared.getUserProfile(for: userJid, fetchFromServer: false, saveAsFriend: true){ isSuccess, flyError, flyData in -// var data = flyData -// if isSuccess { -// -// let profileJSON = "{\"data\" : " + JSONSerializer.toJson(data.getData() as Any) + ",\"status\": \"true\"}" -// print(profileJSON) -// result(profileJSON) -// } else{ -// print(flyError!.localizedDescription) -// result(FlutterError(code: "500", message: flyError!.localizedDescription, details: nil)) -// } -// } -// }catch{ -// print("Error while calling User Profile Details") -// } - } - - - -} -extension Array { - public func toDictionary(with selectKey: (Element) -> Key) -> [Key:Element] { - var dict = [Key:Element]() - for element in self { - dict[selectKey(element)] = element - } - return dict - } -} -extension ChatMessage: Serializable { - - var properties: Array { - return ["mediaChatMessage"] - } - func valueForKey(key: String) -> Any? { - switch key { - case "mediaChatMessage": - return mediaChatMessage - default: - return nil - } - } - -} -extension MediaChatMessage: Serializable { - var properties: Array { - return ["mediaThumbImage"] - } - func valueForKey(key: String) -> Any? { - switch key { - case "mediaThumbImage": - return mediaThumbImage - default: - return nil - } - } -} - -protocol Serializable { - var properties:Array { get } - func valueForKey(key: String) -> Any? - func toDictionary() -> [String:Any] -} -extension Serializable { - func toDictionary() -> [String:Any] { - var dict:[String:Any] = [:] - - for prop in self.properties { - if let val = self.valueForKey(key: prop) as? String { - dict[prop] = val - } else if let val = self.valueForKey(key: prop) as? Int { - dict[prop] = val - } else if let val = self.valueForKey(key: prop) as? Double { - dict[prop] = val - } else if let val = self.valueForKey(key: prop) as? Array { - dict[prop] = val - } else if let val = self.valueForKey(key: prop) as? Serializable { - dict[prop] = val.toDictionary() - } else if let val = self.valueForKey(key: prop) as? Array { - var arr = Array<[String:Any]>() - - for item in (val as Array) { - arr.append(item.toDictionary()) - } - - dict[prop] = arr - } else if prop == "mediaChatMessage" { - if let value = dict[prop] as? MediaChatMessage { - value.toDictionary() - } - } - } - - return dict - } -} diff --git a/ios/Runner/GoogleService-Info-dev.plist b/ios/Runner/GoogleService-Info-dev.plist deleted file mode 100644 index b4c085da..00000000 --- a/ios/Runner/GoogleService-Info-dev.plist +++ /dev/null @@ -1,36 +0,0 @@ - - - - - CLIENT_ID - 1045831384770-a90apqltl7dtlbaj4844235jgv8l1hfm.apps.googleusercontent.com - REVERSED_CLIENT_ID - com.googleusercontent.apps.1045831384770-a90apqltl7dtlbaj4844235jgv8l1hfm - ANDROID_CLIENT_ID - 1045831384770-aa561p9dbh0467tsg3395ufeleu162k4.apps.googleusercontent.com - API_KEY - AIzaSyBy7JDQj6Ar03dMXFCQ-SHgBdBPnKAteG4 - GCM_SENDER_ID - 1045831384770 - PLIST_VERSION - 1 - BUNDLE_ID - com.mirrorfly.uikitflutter.dev - PROJECT_ID - mirrorfly-uikit-dev - STORAGE_BUCKET - mirrorfly-uikit-dev.appspot.com - IS_ADS_ENABLED - - IS_ANALYTICS_ENABLED - - IS_APPINVITE_ENABLED - - IS_GCM_ENABLED - - IS_SIGNIN_ENABLED - - GOOGLE_APP_ID - 1:1045831384770:ios:eff2902ecda09bf911455b - - \ No newline at end of file diff --git a/ios/Runner/GoogleService-Info.plist b/ios/Runner/GoogleService-Info.plist deleted file mode 100755 index 406aa957..00000000 --- a/ios/Runner/GoogleService-Info.plist +++ /dev/null @@ -1,36 +0,0 @@ - - - - - CLIENT_ID - 695832127329-qno5q17plh1tdbif57jtf05sakmb9o08.apps.googleusercontent.com - REVERSED_CLIENT_ID - com.googleusercontent.apps.695832127329-qno5q17plh1tdbif57jtf05sakmb9o08 - API_KEY - AIzaSyA-CkUClIzea3nLWH-XoW-7bDyAKQExHK8 - GCM_SENDER_ID - 695832127329 - PLIST_VERSION - 1 - BUNDLE_ID - com.mirrorfly.qa - PROJECT_ID - mirror-fly-qa - STORAGE_BUCKET - mirror-fly-qa.appspot.com - IS_ADS_ENABLED - - IS_ANALYTICS_ENABLED - - IS_APPINVITE_ENABLED - - IS_GCM_ENABLED - - IS_SIGNIN_ENABLED - - GOOGLE_APP_ID - 1:695832127329:ios:f8b6b0fab296a800 - DATABASE_URL - https://mirror-fly-qa.firebaseio.com - - diff --git a/ios/Runner/GoogleService-Info_old.plist b/ios/Runner/GoogleService-Info_old.plist deleted file mode 100644 index 47292282..00000000 --- a/ios/Runner/GoogleService-Info_old.plist +++ /dev/null @@ -1,36 +0,0 @@ - - - - - CLIENT_ID - 235373697524-mlgfb575p2b6qo5n5nholplitf0d5k1f.apps.googleusercontent.com - REVERSED_CLIENT_ID - com.googleusercontent.apps.235373697524-mlgfb575p2b6qo5n5nholplitf0d5k1f - ANDROID_CLIENT_ID - 235373697524-00ffa2b0fnuqiaq8lrsm4dngutag4gsi.apps.googleusercontent.com - API_KEY - AIzaSyDhRJWHV0kpw0UE30ymMahK0Fzmq6OaYbQ - GCM_SENDER_ID - 235373697524 - PLIST_VERSION - 1 - BUNDLE_ID - com.mirrorfly.uikitflutter.qa - PROJECT_ID - mirrorfly-uikit-qa - STORAGE_BUCKET - mirrorfly-uikit-qa.appspot.com - IS_ADS_ENABLED - - IS_ANALYTICS_ENABLED - - IS_APPINVITE_ENABLED - - IS_GCM_ENABLED - - IS_SIGNIN_ENABLED - - GOOGLE_APP_ID - 1:235373697524:ios:2d40908026b55394a0c1a1 - - \ No newline at end of file diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 6a156580..1380d8f0 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -37,10 +37,24 @@ CFBundleVersion $(FLUTTER_BUILD_NUMBER) + FirebaseAppDelegateProxyEnabled + LICENSE_KEY $(LICENSE_KEY) + LSApplicationQueriesSchemes + + https + http + tel + mailto + LSRequiresIPhoneOS + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + NSCameraUsageDescription MirrorFly need to access to the Camera to Capture and share the image NSContactsUsageDescription @@ -88,19 +102,5 @@ UIViewControllerBasedStatusBarAppearance - FirebaseAppDelegateProxyEnabled - - LSApplicationQueriesSchemes - - https - http - tel - mailto - - NSAppTransportSecurity - - NSAllowsArbitraryLoads - - diff --git a/ios/Runner/JsonSerializer.swift b/ios/Runner/JsonSerializer.swift deleted file mode 100644 index febc4d2d..00000000 --- a/ios/Runner/JsonSerializer.swift +++ /dev/null @@ -1,451 +0,0 @@ -/*The MIT License (MIT) - -Copyright (c) 2015 Peter Helstrup Jensen - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE.*/ - -import Foundation -import FlyCore -import FlyCommon - -/// Handles Convertion from instances of objects to JSON strings. Also helps with casting strings of JSON to Arrays or Dictionaries. -open class JSONSerializer { - - /** - Errors that indicates failures of JSONSerialization - - JsonIsNotDictionary: - - - JsonIsNotArray: - - - JsonIsNotValid: - - */ - public enum JSONSerializerError: Error { - case jsonIsNotDictionary - case jsonIsNotArray - case jsonIsNotValid - } - - //http://stackoverflow.com/questions/30480672/how-to-convert-a-json-string-to-a-dictionary - /** - Tries to convert a JSON string to a NSDictionary. NSDictionary can be easier to work with, and supports string bracket referencing. E.g. personDictionary["name"]. - - parameter jsonString: JSON string to be converted to a NSDictionary. - - throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotDictionary. JsonIsNotDictionary will typically be thrown if you try to parse an array of JSON objects. - - returns: A NSDictionary representation of the JSON string. - */ - public static func toDictionary(_ jsonString: String) throws -> NSDictionary { - if let dictionary = try jsonToAnyObject(jsonString) as? NSDictionary { - return dictionary - } else { - throw JSONSerializerError.jsonIsNotDictionary - } - } - - /** - Tries to convert a JSON string to a NSArray. NSArrays can be iterated and each item in the array can be converted to a NSDictionary. - - parameter jsonString: The JSON string to be converted to an NSArray - - throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotArray. JsonIsNotArray will typically be thrown if you try to parse a single JSON object. - - returns: NSArray representation of the JSON objects. - */ - public static func toArray(_ jsonString: String) throws -> NSArray { - if let array = try jsonToAnyObject(jsonString) as? NSArray { - return array - } else { - throw JSONSerializerError.jsonIsNotArray - } - } - - /** - Tries to convert a JSON string to AnyObject. AnyObject can then be casted to either NSDictionary or NSArray. - - parameter jsonString: JSON string to be converted to AnyObject - - throws: Throws error of type JSONSerializerError. - - returns: Returns the JSON string as AnyObject - */ - fileprivate static func jsonToAnyObject(_ jsonString: String) throws -> Any? { - var any: Any? - - if let data = jsonString.data(using: String.Encoding.utf8) { - do { - any = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) - } - catch let error as NSError { - let sError = String(describing: error) - NSLog(sError) - throw JSONSerializerError.jsonIsNotValid - } - } - return any - } - - /** - Generates the JSON representation given any custom object of any custom class. Inherited properties will also be represented. - - parameter object: The instantiation of any custom class to be represented as JSON. - - returns: A string JSON representation of the object. - */ - public static func toJson(_ object: Any, prettify: Bool = false) -> String { - var json = "" - if (!(object is Array)) { - json += "{" - } - let mirror = Mirror(reflecting: object) - - var children = [(label: String?, value: Any)]() - - if let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children) { - children += mirrorChildrenCollection - } - else { - let mirrorIndexCollection = AnyCollection(mirror.children) - children += mirrorIndexCollection - } - - var currentMirror = mirror - while let superclassChildren = currentMirror.superclassMirror?.children { - - if let mirrorChildrenCollection = AnyRandomAccessCollection(superclassChildren) { - children += mirrorChildrenCollection - } - else { - let mirrorIndexCollection = AnyCollection(superclassChildren) - children += mirrorIndexCollection - } - let randomCollection = AnyRandomAccessCollection(superclassChildren)! - - // children += randomCollection - currentMirror = currentMirror.superclassMirror! - print("children count \(children.count)") - - } - - var filteredChildren = [(label: String?, value: Any)]() - - for (optionalPropertyName, value) in children { -// print("optionalPropertyName") - if optionalPropertyName == "mediaChatMessage" { - print("Media value") - } - - // for (optionalPropertyName, value) in children { -// if !optionalPropertyName!.contains("notMapped_") { -// filteredChildren += [(optionalPropertyName, value)] -// } - // } - - if let optionalPropertyName = optionalPropertyName { - - if !optionalPropertyName.contains("notMapped_") { - filteredChildren.append((optionalPropertyName, value)) - } - - } - else { - filteredChildren.append((nil, value)) - } - } - - - var skip = false - var hasChildren = false - let size = filteredChildren.count - var index = 0 - - var first = true - - for (optionalPropertyName, value) in filteredChildren { - skip = false - - let propertyName = optionalPropertyName - let property = Mirror(reflecting: value) - - if propertyName == "mediaChatMessage" { -// print("Media value \(value)") - } - - if propertyName == "mediaThumbImage" { -// print("mediaThumbImage value \(value)") - } - - if propertyName == "replyParentChatMessage"{ -// print("replyParentChatMessage--> \(value)") -// print("replyParentChatMessage--> \(String(describing: value))") - } - - -// if(propertyName == "nickName" && value as! String == "67890"){ -// print("property nickName-->\(propertyName)") -// print("property nickName-->\(value)") -// } - - if let mirrorChildrenCollection = AnyRandomAccessCollection(property.children), mirrorChildrenCollection.count > 0 { - // if let superclassChildren = property.superclassMirror?.children, superclassChildren.count > 0 { - // hasChildren = true - } - - -// var isObject = false -// let mirrorChildren = Mirror(reflecting: value) -// -// var childrenChildren = [(label: String?, value: Any)]() -// -// if let mirrorChildrenCollection = AnyRandomAccessCollection(mirrorChildren.children) { -// childrenChildren += mirrorChildrenCollection -// isObject = true -// } -// else { -// let mirrorIndexCollection = AnyCollection(mirrorChildren.children) -// childrenChildren += mirrorIndexCollection -// isObject = true -// } -// -// var currentMirror = mirror -// while let superclassChildren = currentMirror.superclassMirror?.children { -// let randomCollection = AnyRandomAccessCollection(superclassChildren)! -// childrenChildren += randomCollection -// currentMirror = currentMirror.superclassMirror! -// isObject = true -// } -// -// -// -// var filteredChildren = [(label: String?, value: Any)]() -// -// for (optionalPropertyName, value) in children { -// -// if let optionalPropertyName = optionalPropertyName { -// -// if !optionalPropertyName.contains("notMapped_") { -// filteredChildren.append((optionalPropertyName, value)) -// } -// -// } -// else { -// filteredChildren.append((nil, value)) -// } -// } - - - - var handledValue = String() - -// if isObject == true { -// JSONSerializer.toJson(value) -// skip = true -// } - -// print("property displaytype \(String(describing: property.displayStyle))") - if (propertyName != nil && propertyName == "some" && property.displayStyle == Mirror.DisplayStyle.struct){ - handledValue = toJson(value) - skip = true - } -// else if property.displayStyle == Mirror.DisplayStyle. { -// handledValue = toJson(value) -// skip = true -// } - else if (value is Int || - value is Int32 || - value is Int64 || - value is Double || - value is Float || - value is Bool) && property.displayStyle != Mirror.DisplayStyle.optional { - handledValue = String(describing: value) - } - else if property.displayStyle == Mirror.DisplayStyle.enum { - handledValue = "\"\(value)\"" - } - - else if let array = value as? [Int?] { - handledValue += "[" - for (index, value) in array.enumerated() { - handledValue += value != nil ? String(value!) : "null" - handledValue += (index < array.count-1 ? ", " : "") - } - handledValue += "]" - } - else if let array = value as? [Double?] { - handledValue += "[" - for (index, value) in array.enumerated() { - handledValue += value != nil ? String(value!) : "null" - handledValue += (index < array.count-1 ? ", " : "") - } - handledValue += "]" - } - else if let array = value as? [Float?] { - handledValue += "[" - for (index, value) in array.enumerated() { - handledValue += value != nil ? String(value!) : "null" - handledValue += (index < array.count-1 ? ", " : "") - } - handledValue += "]" - } - else if let array = value as? [Bool?] { - handledValue += "[" - for (index, value) in array.enumerated() { - handledValue += value != nil ? String(value!) : "null" - handledValue += (index < array.count-1 ? ", " : "") - } - handledValue += "]" - } - else if let array = value as? [String?] { - - handledValue += "[" - for (index, value) in array.enumerated() { - handledValue += value != nil ? "\"\(value!)\"" : "null" - handledValue += (index < array.count-1 ? ", " : "") - } - handledValue += "]" - } - else if let array = value as? [String] { - handledValue += "[" - for (index, value) in array.enumerated() { - handledValue += "\"\(value)\"" - handledValue += (index < array.count-1 ? ", " : "") - } - handledValue += "]" - } - else if let array = value as? NSArray { - handledValue += "[" - for (index, value) in array.enumerated() { - if !(value is Int) && - !(value is Int32) && - !(value is Int64) && - !(value is Double) && !(value is Float) && !(value is Bool) && !(value is String) { - handledValue += toJson(value) - } - else { - handledValue += "\(value)" - } - handledValue += (index < array.count-1 ? ", " : "") - } - handledValue += "]" - } - else if property.displayStyle == Mirror.DisplayStyle.class || - property.displayStyle == Mirror.DisplayStyle.struct || - String(describing: value).contains("#") { - handledValue = toJson(value) - } - else if(propertyName == "messageTextContent" || propertyName == "lastMessageContent") && String(describing: value) != "nil" { - let convert = String(describing: value).replacingOccurrences(of: "\n", with: "\\n") - handledValue = "\"\(convert)\"" - } - - else if (propertyName == "mediaChatMessage") && String(describing: value) != "nil" { - // let refined = String(describing: value).replacingOccurrences(of: "some", with: "") - print("mediaThumbImage check") - print("force-->\(value)") -// else { - var force = value as! MediaChatMessage - var image: String = "\(force.mediaThumbImage)" - force.mediaThumbImage = image.replacingOccurrences(of: "\n", with: "") - handledValue = toJson(force) - -// } - - - } - - else if(propertyName == "locationChatMessage") && String(describing: value) != "nil" { - let force = value - handledValue = toJson(force) - } - - else if(propertyName == "contactPhoneNumbers") && String(describing: value) != "nil" { - print("contactPhoneNumbers-----") -// print(value) - - } - else if (propertyName == "contactChatMessage") && String(describing: value) != "nil" { - // let refined = String(describing: value).replacingOccurrences(of: "some", with: "") - - let force = value - print("contactChatMessage block") -// print(force) - handledValue = toJson(force) - print("handledValue-----") -// print(handledValue) - - } - - else if (propertyName == "replyParentChatMessage" && String(describing: value) != "nil"){ - let force = value - handledValue = toJson(force) - } - else if property.displayStyle == Mirror.DisplayStyle.optional { - let str = String(describing: value) - if str != "nil" { - // Some optional values cannot be unpacked if type is "Any" - // We remove the "Optional(" and last ")" from the value by string manipulation - var d = String(str).dropFirst(9) - d = d.dropLast(1) -// handledValue = String(d) - handledValue = "\"\(d)\"" - handledValue = handledValue.replacingOccurrences(of: "\"\"", with: "\"") - } else { - handledValue = "null" - } - } - else { - - handledValue = String(describing: value) != "nil" ? "\"\(value)\"" : "null" - - } - if (propertyName == "mediaChatMessage" || propertyName == "locationChatMessage") && String(describing: value) != "nil" { -// print(handledValue) - } - - - if !skip { - - // if optional propertyName is populated we'll use it - if let propertyName = propertyName { - json += "\"\(propertyName)\": \(handledValue)" + (index < size-1 ? ", " : "") - } - // if not then we have a member an array - else { - // if it's the first member we need to prepend ] - if first { - json += "[" - first = false - } - // if it's not the last we need a comma. if it is the last we need to close ] - json += "\(handledValue)" + (index < size-1 ? ", " : "]") - } - - } else { - json = "\(handledValue)" + (index < size-1 ? ", " : "") - } - if (propertyName == "mediaChatMessage" || propertyName == "locationChatMessage") && String(describing: value) != "nil" { -// print(json) - } - index += 1 - } - - if !skip { - if (!(object is Array)) { - json += "}" - } - } - - if prettify { - let jsonData = json.data(using: String.Encoding.utf8)! - let jsonObject = try! JSONSerialization.jsonObject(with: jsonData, options: []) - let prettyJsonData = try! JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) - json = NSString(data: prettyJsonData, encoding: String.Encoding.utf8.rawValue)! as String - } - - return json - } - -} diff --git a/ios/Runner/NetworkConnectivityManager.swift b/ios/Runner/NetworkConnectivityManager.swift deleted file mode 100755 index 45d5b66c..00000000 --- a/ios/Runner/NetworkConnectivityManager.swift +++ /dev/null @@ -1,50 +0,0 @@ -// -// NetworkConnectivityManager.swift -// NetworkConnectivity -// -import Foundation -import Network - -extension Notification.Name { - static let connectivityStatus = Notification.Name(rawValue: "connectivityStatusChanged") -} - -extension NWInterface.InterfaceType: CaseIterable { - public static var allCases: [NWInterface.InterfaceType] = [ - .other, - .wifi, - .cellular, - .loopback, - .wiredEthernet - ] -} - -final class NetworkMonitor { - static let shared = NetworkMonitor() - - private let queue = DispatchQueue(label: "NetworkConnectivityMonitor") - private let monitor: NWPathMonitor - - private(set) var isConnected = false - private(set) var isExpensive = false - private(set) var currentConnectionType: NWInterface.InterfaceType? - - private init() { - monitor = NWPathMonitor() - } - - func startMonitoring() { - monitor.pathUpdateHandler = { [weak self] path in - self?.isConnected = path.status != .unsatisfied - self?.isExpensive = path.isExpensive - self?.currentConnectionType = NWInterface.InterfaceType.allCases.filter { path.usesInterfaceType($0) }.first - - NotificationCenter.default.post(name: .connectivityStatus, object: nil) - } - monitor.start(queue: queue) - } - - func stopMonitoring() { - monitor.cancel() - } -} diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlements index 06044c95..254e205f 100644 --- a/ios/Runner/Runner.entitlements +++ b/ios/Runner/Runner.entitlements @@ -6,7 +6,7 @@ development com.apple.security.application-groups - group.com.mirrorfly.qa + group.com.mirrorfly.flutter diff --git a/ios/Runner/UserDefaults.swift b/ios/Runner/UserDefaults.swift deleted file mode 100755 index 150906bf..00000000 --- a/ios/Runner/UserDefaults.swift +++ /dev/null @@ -1,104 +0,0 @@ -// -// UserDefaults.swift -// MirrorFly -// -// Created by User on 18/05/21. -// - -import UIKit -import FlyCommon -import FlyCore -import Alamofire -import CommonCrypto -import FlyCore - -class Utility: NSObject{ - - class func saveInPreference (key : String , value : Any) { - var stringaValue = "" - if let boolString = value as? Bool{ - stringaValue = boolString ? "true" : "false" - }else if let value = value as? String{ - stringaValue = value - } - if let encryptedData = encryptDecryptFlyDefaults(key: key, data: Data(stringaValue.utf8), encrypt: true){ - UserDefaults.standard.setValue(encryptedData, forKey: key) - UserDefaults.standard.synchronize() - } - } - - class func getStringFromPreference(key : String) -> String { - if let value = UserDefaults.standard.object(forKey: key) { - if let encryptedData = value as? Data{ - if let decryptedData = encryptDecryptFlyDefaults(key: key, data: encryptedData, encrypt: false){ - return String(data: decryptedData, encoding: .utf8)! - } - }else if let oldValue = value as? String { - saveInPreference(key: key, value: oldValue) - return oldValue - } - } - return "" - } - - class func getBoolFromPreference(key : String) -> Bool { - if let value = UserDefaults.standard.object(forKey: key) { - if let encryptedData = value as? Data{ - if let decryptedData = encryptDecryptFlyDefaults(key: key, data: encryptedData, encrypt: false){ - return (String(data: decryptedData, encoding: .utf8)! == "true" ) - } - } else if let oldValue = value as? Bool { - saveInPreference(key: key, value: oldValue) - return oldValue - } - } - return false - } - - - - public class func refreshToken(onCompletion: @escaping (_ isSuccess: Bool) -> Void) { - ChatManager.refreshToken { isSuccess, error, data in - onCompletion(isSuccess) - } - } - - - - public static func generateUniqueId() -> String { - return UUID.init().uuidString.replacingOccurrences(of: "-", with: "").lowercased() - } - - - class func clearUserDefaults(){ - let defaults = UserDefaults.standard - let dictionary = defaults.dictionaryRepresentation() - dictionary.keys.forEach { key in - defaults.removeObject(forKey: key) - } - } - - class func encryptDecryptFlyDefaults(key:String, data : Data, encrypt : Bool, iv : String = "ddc0f15cc2c90fca") -> Data?{ - guard let key = FlyEncryption.sha256(key, length: 32) else { - return data - } - guard let flyEncryption = FlyEncryption(encryptionKey: key, initializationVector: iv ) else { - return data - } - - if encrypt { - guard let encryptedData = flyEncryption.crypt(data: data, option: CCOperation(kCCEncrypt)) else { - return data - } - print("#ud encrypt \(key) \(encryptedData)") - return encryptedData - } else { - guard let decryptedData = flyEncryption.crypt(data: data, option: CCOperation(kCCDecrypt)) else { - return nil - } - print("#ud decrypt \(key) \(decryptedData)") - return decryptedData - } - } - -} diff --git a/lib/app/base_controller.dart b/lib/app/base_controller.dart index 0879ff2b..890b7fdd 100644 --- a/lib/app/base_controller.dart +++ b/lib/app/base_controller.dart @@ -3,7 +3,7 @@ import 'dart:convert'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; +import 'package:mirrorfly_plugin/mirrorflychat.dart'; import 'package:get/get.dart'; import 'package:mirror_fly_demo/app/common/constants.dart'; import 'package:mirror_fly_demo/app/data/helper.dart'; @@ -17,6 +17,7 @@ import 'package:mirror_fly_demo/app/routes/app_pages.dart'; import 'common/main_controller.dart'; import 'common/notification_service.dart'; +import 'model/chat_message_model.dart'; import 'modules/archived_chats/archived_chat_list_controller.dart'; import 'modules/chat/controllers/forwardchat_controller.dart'; import 'modules/chatInfo/controllers/chat_info_controller.dart'; @@ -34,10 +35,10 @@ abstract class BaseController { Mirrorfly.onMediaStatusUpdated.listen(onMediaStatusUpdated); Mirrorfly.onUploadDownloadProgressChanged.listen((event){ var data = json.decode(event.toString()); - // debugPrint("Media Status Onprogress changed---> flutter $data"); + debugPrint("Media Status Onprogress changed---> flutter $data"); var messageId = data["message_id"] ?? ""; - var progressPercentage = data["progress_percentage"] ?? "0"; - onUploadDownloadProgressChanged(messageId,progressPercentage); + var progressPercentage = data["progress_percentage"] ?? 0; + onUploadDownloadProgressChanged(messageId,progressPercentage.toString()); }); Mirrorfly.onGroupProfileFetched.listen(onGroupProfileFetched); Mirrorfly.onNewGroupCreated.listen(onNewGroupCreated); @@ -127,7 +128,8 @@ abstract class BaseController { Mirrorfly.usersWhoBlockedMeListFetched.listen(usersWhoBlockedMeListFetched); Mirrorfly.onConnected.listen(onConnected); Mirrorfly.onDisconnected.listen(onDisconnected); - Mirrorfly.onConnectionNotAuthorized.listen(onConnectionNotAuthorized); + // Mirrorfly.onConnectionNotAuthorized.listen(onConnectionNotAuthorized); + // Mirrorfly.onConnectionFailed.listen(onConnectionFailed); Mirrorfly.connectionFailed.listen(connectionFailed); Mirrorfly.connectionSuccess.listen(connectionSuccess); Mirrorfly.onWebChatPasswordChanged.listen(onWebChatPasswordChanged); @@ -182,7 +184,7 @@ abstract class BaseController { if(SessionManagement.getCurrentChatJID() == chatMessageModel.chatUserJid.checkNull()){ debugPrint("Message Status updated user chat screen is in online"); }else{ - if(chatMessageModel.isMessageRecalled){ + if(chatMessageModel.isMessageRecalled.value){ showLocalNotification(chatMessageModel); } } @@ -190,6 +192,9 @@ abstract class BaseController { if (Get.isRegistered()) { Get.find().onMessageStatusUpdated(chatMessageModel); } + if (Get.isRegistered()) { + Get.find().onMessageStatusUpdated(chatMessageModel); + } if (Get.isRegistered()) { Get.find().onMessageStatusUpdated(chatMessageModel); } @@ -487,7 +492,8 @@ abstract class BaseController { mirrorFlyLog('onDisconnected', result.toString()); } - void onConnectionNotAuthorized(result) {} + // void onConnectionNotAuthorized(result) {} + // void onConnectionFailed(result) {} void connectionFailed(result) {} @@ -554,7 +560,7 @@ abstract class BaseController { NotificationDetails(android: androidNotificationDetails, iOS: iosNotificationDetails); await flutterLocalNotificationsPlugin.show( int.parse(messageId), chatMessageModel.senderUserName, - chatMessageModel.isMessageRecalled ? "This message was deleted" : chatMessageModel.messageTextContent, notificationDetails, + chatMessageModel.isMessageRecalled.value ? "This message was deleted" : chatMessageModel.messageTextContent, notificationDetails, payload: chatMessageModel.chatUserJid); }else{ debugPrint("self sent message don't need notification"); diff --git a/lib/app/common/constants.dart b/lib/app/common/constants.dart index 14427e70..bd3c8c62 100644 --- a/lib/app/common/constants.dart +++ b/lib/app/common/constants.dart @@ -4,12 +4,12 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; import 'package:mirror_fly_demo/app/data/helper.dart'; import 'package:path_provider/path_provider.dart'; import 'package:url_launcher/url_launcher.dart'; import '../data/apputils.dart'; +import '../model/chat_message_model.dart'; //Colors const Color appBarColor = Color(0xffF2F2F2); @@ -277,7 +277,7 @@ class Constants { static const String package = 'com.mirrorfly.uikit_flutter'; static const String webChatLogin = 'https://webchat-uikit-qa.contus.us/'; static const String tag = 'Contus Fly'; - static const String googleMapKey = "AIzaSyBaKkrQnLT4nacpKblIE5d4QK6GpaX5luQ"; + static const String googleMapKey = "YOUR GOOGLE KEY HERE"; static const String googleMapPackageName = "com.google.android.apps.maps"; static const String packageName = "com.contus.flycommons."; @@ -477,6 +477,11 @@ class Constants { static const String privacyPolicy = "https://www.mirrorfly.com/privacy-policy.php"; + static const maxAudioFileSize = 30; + static const maxVideoFileSize = 30; + static const maxImageFileSize = 10; + static const maxDocFileSize = 20; + static const List defaultStatusList = [ "Available", "Sleeping...", @@ -621,7 +626,7 @@ class Constants { "Choose Translation Language"; static const String googleTranslationLanguageDoubleTap = "Double Tap the received messages to translate"; - static const String googleTranslateKey = "xxxxxxxxxxxxxxxxxx"; + static const String googleTranslateKey = ""; static const String editBusyStatus = "Edit Busy Status Message"; static const String yourBusyStatus = "Your Busy Status"; diff --git a/lib/app/common/main_controller.dart b/lib/app/common/main_controller.dart index d00b04ac..bf33ab33 100644 --- a/lib/app/common/main_controller.dart +++ b/lib/app/common/main_controller.dart @@ -11,7 +11,6 @@ import 'package:mirror_fly_demo/app/base_controller.dart'; import 'package:internet_connection_checker/internet_connection_checker.dart'; import 'package:mirror_fly_demo/app/common/constants.dart'; import 'package:mirror_fly_demo/app/common/received_notification.dart'; -import 'package:mirror_fly_demo/app/data/apputils.dart'; import 'package:mirror_fly_demo/app/data/pushnotification.dart'; import 'package:mirror_fly_demo/app/data/session_management.dart'; import 'package:mirror_fly_demo/app/data/helper.dart'; @@ -20,7 +19,6 @@ import 'package:mirror_fly_demo/app/modules/contact_sync/controllers/contact_syn import 'package:mirror_fly_demo/app/routes/app_pages.dart'; import 'package:mirrorfly_plugin/mirrorfly.dart'; -import 'package:permission_handler/permission_handler.dart'; import '../modules/chatInfo/controllers/chat_info_controller.dart'; import 'notification_service.dart'; @@ -140,12 +138,12 @@ class MainController extends FullLifeCycleController with BaseController, FullLi if(payload != null && payload.isNotEmpty){ if (Get.isRegistered()) { - Mirrorfly.getProfileDetails(payload, false).then((value) { - if (value != null) { + getProfileDetails(payload).then((value) { + if (value.jid != null) { debugPrint("notification group info controller"); - var profile = profiledata(value.toString()); + // var profile = profiledata(value.toString()); // Get.toNamed(Routes.chat, arguments: profile); - Get.back(result: profile); + Get.back(result: value); } }); }else { @@ -291,13 +289,13 @@ class MainController extends FullLifeCycleController with BaseController, FullLi void onResumed() { mirrorFlyLog('mainController', 'onResumed'); checkShouldShowPin(); - if(!SessionManagement.isTrailLicence()) { + if(!Mirrorfly.isTrialLicence) { syncContacts(); } } void syncContacts() async { - if(await Permission.contacts.isGranted) { + /*if(await Permission.contacts.isGranted) { if (await AppUtils.isNetConnected() && !await Mirrorfly.contactSyncStateValue()) { final permission = await Permission.contacts.status; @@ -314,13 +312,13 @@ class MainController extends FullLifeCycleController with BaseController, FullLi mirrorFlyLog("checkContactPermission isSuccess", value.toString()); }); } - } + }*/ } void networkDisconnected() {} void networkConnected() { - if(!SessionManagement.isTrailLicence()) { + if(!Mirrorfly.isTrialLicence) { syncContacts(); } } diff --git a/lib/app/common/widgets.dart b/lib/app/common/widgets.dart index 54b60b20..582e00a1 100644 --- a/lib/app/common/widgets.dart +++ b/lib/app/common/widgets.dart @@ -7,7 +7,7 @@ import 'package:get/get.dart'; import 'package:mirror_fly_demo/app/data/helper.dart'; import 'package:mirror_fly_demo/app/modules/dashboard/widgets.dart'; -import '../data/session_management.dart'; +import 'package:mirrorfly_plugin/mirrorfly.dart'; import 'constants.dart'; import 'main_controller.dart'; @@ -151,7 +151,7 @@ class ImageNetwork extends GetView { ); },*/ placeholder: (context, string) { - if(!(blocked || (unknown && !SessionManagement.isTrailLicence()))){ + if(!(blocked || (unknown && !Mirrorfly.isTrialLicence))){ if(errorWidget !=null){ return errorWidget!; } @@ -183,7 +183,7 @@ class ImageNetwork extends GetView { // debugPrint("image blocked--> $blocked"); // debugPrint("image unknown--> $unknown"); - if(!(blocked || (unknown && !SessionManagement.isTrailLicence()))){ + if(!(blocked || (unknown && !Mirrorfly.isTrialLicence))){ if(errorWidget !=null){ return errorWidget!; } @@ -207,7 +207,7 @@ class ImageNetwork extends GetView { imageBuilder: (context, provider) { return clipOval ? ClipOval( - child: !(blocked || (unknown && !SessionManagement.isTrailLicence())) ? Image( + child: !(blocked || (unknown && !Mirrorfly.isTrialLicence)) ? Image( image: provider, fit: BoxFit.fill, ) : Image.asset( @@ -218,7 +218,7 @@ class ImageNetwork extends GetView { ),) : InkWell( onTap: onTap, - child: !(blocked || (unknown && !SessionManagement.isTrailLicence())) ? Image( + child: !(blocked || (unknown && !Mirrorfly.isTrialLicence)) ? Image( image: provider, fit: BoxFit.fill, ) : Image.asset( diff --git a/lib/app/data/helper.dart b/lib/app/data/helper.dart index 43791b6d..17364f1a 100644 --- a/lib/app/data/helper.dart +++ b/lib/app/data/helper.dart @@ -8,13 +8,14 @@ import 'package:flutter_svg/svg.dart'; import 'package:get/get.dart'; import 'package:intl/intl.dart'; import 'package:mirror_fly_demo/app/common/constants.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; +import 'package:mirrorfly_plugin/mirrorflychat.dart'; import 'package:mirror_fly_demo/app/data/session_management.dart'; import 'package:mirror_fly_demo/app/routes/app_pages.dart'; import 'package:open_file_plus/open_file_plus.dart'; import 'package:url_launcher/url_launcher.dart'; import '../common/widgets.dart'; +import '../model/chat_message_model.dart'; import 'apputils.dart'; class Helper { @@ -240,12 +241,13 @@ bool checkFileUploadSize(String path, String mediaType) { // debugPrint(getFileSizeText(sizeInBytes.toString())); - if (mediaType == Constants.mImage && sizeInMb < 10) { + if (mediaType == Constants.mImage && sizeInMb <= Constants.maxImageFileSize) { return true; - } else if ((mediaType == Constants.mAudio || - mediaType == Constants.mVideo || - mediaType == Constants.mDocument) && - sizeInMb < 20) { + } else if (mediaType == Constants.mAudio && sizeInMb <= Constants.maxAudioFileSize) { + return true; + } else if (mediaType == Constants.mVideo && sizeInMb <= Constants.maxVideoFileSize) { + return true; + } else if (mediaType == Constants.mDocument && sizeInMb <= Constants.maxDocFileSize) { return true; } else { return false; @@ -297,6 +299,10 @@ extension StringParsing on String? { return this ?? ""; } + bool toBool(){ + return this != null ? this!.toLowerCase() == "true" : false; + } + int checkIndexes(String searchedKey) { var i = -1; if (i == -1 || i < searchedKey.length) { @@ -340,13 +346,13 @@ extension MemberParsing on Member { } String getUsername() { - var value = Mirrorfly.getProfileDetails(jid.checkNull(), false); + var value = Mirrorfly.getProfileDetails(jid.checkNull()); var str = Profile.fromJson(json.decode(value.toString())); return getName(str); //str.name.checkNull(); } Future getProfileDetails() async { - var value = await Mirrorfly.getProfileDetails(jid.checkNull(), false); + var value = await Mirrorfly.getProfileDetails(jid.checkNull()); var str = Profile.fromJson(json.decode(value.toString())); return str; } @@ -372,7 +378,7 @@ extension MemberProfileParsing on MemberProfileDetails { } Future getProfileDetails(String jid) async { - var value = await Mirrorfly.getProfileDetails(jid.checkNull(), false); + var value = await Mirrorfly.getProfileDetails(jid.checkNull()); // profileDataFromJson(value); debugPrint("update profile--> $value"); var profile = await compute(profiledata, value.toString()); @@ -704,7 +710,7 @@ Future getRecentChatOfJid(String jid) async { } String getName(Profile item) { - if (SessionManagement.isTrailLicence()) { + if (Mirrorfly.isTrialLicence) { /*return item.name.toString().checkNull().isEmpty ? item.nickName.toString() : item.name.toString();*/ @@ -750,7 +756,7 @@ String getName(Profile item) { } String getRecentName(RecentChatData item) { - if (SessionManagement.isTrailLicence()) { + if (Mirrorfly.isTrialLicence) { /*return item.name.toString().checkNull().isEmpty ? item.nickName.toString() : item.name.toString();*/ @@ -778,7 +784,7 @@ String getRecentName(RecentChatData item) { } String getMemberName(Member item) { - if (SessionManagement.isTrailLicence()) { + if (Mirrorfly.isTrialLicence) { /*return item.name.toString().checkNull().isEmpty ? item.nickName.toString() : item.name.toString();*/ @@ -838,20 +844,28 @@ String getMobileNumberFromJid(String jid) { String convertSecondToLastSeen(String seconds){ - var userLastSeenDate = DateTime.now().subtract(Duration(seconds: double.parse(seconds).toInt())); - - Duration diff = DateTime.now().difference(userLastSeenDate); - - if(int.parse(DateFormat('yyyy').format(userLastSeenDate)) < int.parse(DateFormat('yyyy').format(DateTime.now()))){ - return 'last seen on ${DateFormat('dd/mm/yyyy')}'; - }else if(diff.inDays > 1){ - return 'last seen on ${DateFormat('dd MMM').format(userLastSeenDate)}'; - }else if(diff.inDays == 1){ - return 'last seen on Yesterday'; - } else if(diff.inHours >= 1 || diff.inMinutes >= 1 || diff.inSeconds >= 1){ - return 'last seen at ${DateFormat('hh:mm a').format(userLastSeenDate)}'; - } else { - return 'Online'; + if(seconds.isNotEmpty) { + if(seconds=="0") return "Online"; + // var userLastSeenDate = DateTime.now().subtract(Duration(milliseconds: double.parse(seconds).toInt())); + DateTime lastSeen = DateTime.fromMillisecondsSinceEpoch( + double.parse(seconds).toInt()); + Duration diff = DateTime.now().difference(lastSeen); + + if (int.parse(DateFormat('yyyy').format(lastSeen)) < + int.parse(DateFormat('yyyy').format(DateTime.now()))) { + return 'last seen on ${DateFormat('dd/mm/yyyy')}'; + } else if (diff.inDays > 1) { + return 'last seen on ${DateFormat('dd MMM').format(lastSeen)}'; + } else if (diff.inDays == 1) { + return 'last seen on Yesterday'; + } else + if (diff.inHours >= 1 || diff.inMinutes >= 1 || diff.inSeconds >= 1) { + return 'last seen at ${DateFormat('hh:mm a').format(lastSeen)}'; + } else { + return 'Online'; + } + }else{ + return ""; } } @@ -946,7 +960,7 @@ void showQuickProfilePopup({required context, required Function() chatTap, child: Text( profile.value.isGroupProfile! ? profile.value.name.checkNull() - : SessionManagement.isTrailLicence() ? profile.value.mobileNumber.checkNull() : profile.value.nickName.checkNull(), + : Mirrorfly.isTrialLicence ? profile.value.mobileNumber.checkNull() : profile.value.nickName.checkNull(), style: const TextStyle(color: Colors.white), ), ), diff --git a/lib/app/data/permissions.dart b/lib/app/data/permissions.dart index a9e601e7..7527d48c 100644 --- a/lib/app/data/permissions.dart +++ b/lib/app/data/permissions.dart @@ -24,22 +24,26 @@ class AppPermission { if (permission != PermissionStatus.granted && permission != PermissionStatus.permanentlyDenied) { const newPermission = Permission.contacts; - mirrorFlyPermissionDialog( + var deniedPopupValue = await mirrorFlyPermissionDialog( notNowBtn: () { return false; }, continueBtn: () async { - newPermission.request(); + // newPermission.request(); }, icon: contactPermission, content: Constants.contactPermission); - return newPermission.status; + if(deniedPopupValue) { + return await newPermission.request(); + }else { + return newPermission.status; + } } else { return permission; } } - static Future getStoragePermission() async { + static Future getStoragePermission() async { var sdkVersion=0; if (Platform.isAndroid) { var sdk = await DeviceInfoPlugin().androidInfo; @@ -52,56 +56,70 @@ class AppPermission { if (permission != PermissionStatus.granted && permission != PermissionStatus.permanentlyDenied) { const newPermission = Permission.storage; - mirrorFlyPermissionDialog( + var deniedPopupValue = await mirrorFlyPermissionDialog( notNowBtn: () { return false; }, continueBtn: () async { - newPermission.request(); + // newPermission.request(); }, icon: filePermission, content: Constants.filePermission); - return newPermission.status; + if(deniedPopupValue) { + return await newPermission.request().isGranted; + }else{ + return newPermission.status.isGranted; + } } else { - return permission; + return permission.isGranted; } } else { return getAndroid13Permission(); } } - static Future getAndroid13Permission() async { + static Future getAndroid13Permission() async { final photos = await Permission.photos.status; final videos = await Permission.videos.status; + final mediaLibrary = await Permission.mediaLibrary.status; // final audio = await Permission.audio.status; const newPermission = [ Permission.photos, Permission.videos, + Permission.mediaLibrary, // Permission.audio ]; - if ((photos != PermissionStatus.granted && - photos != PermissionStatus.permanentlyDenied) || - (videos != PermissionStatus.granted && - videos != PermissionStatus.permanentlyDenied)) { - mirrorFlyPermissionDialog( + if ((photos != PermissionStatus.granted && photos != PermissionStatus.permanentlyDenied) || + (videos != PermissionStatus.granted && videos != PermissionStatus.permanentlyDenied) || + (mediaLibrary != PermissionStatus.granted && mediaLibrary != PermissionStatus.permanentlyDenied) + ) { + mirrorFlyLog("showing mirrorfly popup", ""); + var deniedPopupValue = await mirrorFlyPermissionDialog( notNowBtn: () { return false; }, - continueBtn: () async { - newPermission.request(); + continueBtn: () { + // newPermission.request(); }, icon: filePermission, content: Constants.filePermission); - var photo = await newPermission[0].status.isGranted; - var video = await newPermission[1].isGranted; - // var audio = await newPermission[2].isGranted; - return (photo && video) - ? PermissionStatus.granted - : PermissionStatus.denied; + if(deniedPopupValue) { + var newp = await newPermission.request(); + PermissionStatus? photo = newp[Permission.photos]; + PermissionStatus? video = newp[Permission.videos]; + PermissionStatus? mediaLibrary = newp[Permission.mediaLibrary]; + // var audio = await newPermission[2].isGranted; + return (photo!.isGranted && video!.isGranted && mediaLibrary!.isGranted); + // ? PermissionStatus.granted + // : PermissionStatus.denied; + }else{ + return false;//PermissionStatus.denied; + } } else { - return (photos.isGranted && videos.isGranted) - ? PermissionStatus.granted - : PermissionStatus.denied; + mirrorFlyLog("showing mirrorfly popup", "${photos.isGranted} ${videos.isGranted} ${mediaLibrary.isGranted}"); + return (photos.isGranted && videos.isGranted && mediaLibrary.isGranted); + // ? photos + // : photos; } } @@ -116,6 +134,7 @@ class AppPermission { } } +//not used so var deniedPopupValue = await not imple static Future getCameraPermission() async { final permission = await Permission.camera.status; if (permission != PermissionStatus.granted && @@ -136,6 +155,7 @@ class AppPermission { } } +//not used so var deniedPopupValue = await not imple static Future getAudioPermission() async { final permission = await Permission.microphone.status; if (permission != PermissionStatus.granted && @@ -156,6 +176,7 @@ class AppPermission { } } + //not used so var deniedPopupValue = await not imple static Future askFileCameraAudioPermission() async { var filePermission = Permission.storage; var camerapermission = Permission.camera; @@ -267,12 +288,12 @@ class AppPermission { child: const Text("OK")), ]); } - static mirrorFlyPermissionDialog( + static Future mirrorFlyPermissionDialog( {required Function() notNowBtn, required Function() continueBtn, required String icon, - required String content}) { - Get.dialog(AlertDialog( + required String content}) async { + return await Get.dialog(AlertDialog( contentPadding: EdgeInsets.zero, content: Column( mainAxisSize: MainAxisSize.min, @@ -294,7 +315,7 @@ class AppPermission { actions: [ TextButton( onPressed: () { - Get.back(result: "no"); + Get.back(result: false); notNowBtn(); }, child: const Text( @@ -303,7 +324,7 @@ class AppPermission { )), TextButton( onPressed: () { - Get.back(result: "yes"); + Get.back(result: true); continueBtn(); }, child: const Text( diff --git a/lib/app/data/session_management.dart b/lib/app/data/session_management.dart index 61537b28..307033f0 100644 --- a/lib/app/data/session_management.dart +++ b/lib/app/data/session_management.dart @@ -14,7 +14,12 @@ class SessionManagement { } } static Future onInit() async { - _preferences = await SharedPreferences.getInstance(); + try { + _preferences = await SharedPreferences.getInstance(); + }catch(e){ + SharedPreferences.setMockInitialValues({}); + _preferences = await SharedPreferences.getInstance(); + } } static Future setLogin(bool val) async { @@ -183,7 +188,7 @@ class SessionManagement { static String getTranslationLanguageCode() => _preferences.getString("LanguageCode") ?? "en"; static bool isInitialContactSyncDone() => _preferences.getBool("is_initial_contact_sync_done") ?? false; static bool isContactSyncDone() => _preferences.getBool("is_contact_sync_done") ?? false; - static bool isTrailLicence() => _preferences.getBool("IS_TRIAL_LICENSE") ?? false; + static bool isTrailLicence() => _preferences.getBool("IS_TRIAL_LICENSE") ?? true; static int appLastSession() => _preferences.getInt(Constants.appSession) ?? DateTime.now().millisecondsSinceEpoch; static int lastPinChangedAt() => _preferences.getInt(Constants.changedPinAt) ?? DateTime.now().millisecondsSinceEpoch; static bool showAlert() => _preferences.getBool('show_alert') ?? true; diff --git a/lib/app/model/chat_message_model.dart b/lib/app/model/chat_message_model.dart new file mode 100644 index 00000000..3dcaca11 --- /dev/null +++ b/lib/app/model/chat_message_model.dart @@ -0,0 +1,490 @@ +// To parse this JSON data, do +// +// final chatMessageModel = chatMessageModelFromJson(jsonString); + +import 'dart:convert'; +import 'dart:io'; + +import 'package:get/get.dart'; +import 'package:mirror_fly_demo/app/data/helper.dart'; + +List chatMessageModelFromJson(String str) => + List.from( + json.decode(str).map((x) => ChatMessageModel.fromJson(x))); + +String chatMessageModelToJson(List data) => + json.encode(List.from(data.map((x) => x.toJson()))); + +ChatMessageModel sendMessageModelFromJson(String str) => + ChatMessageModel.fromJson(json.decode(str)); + +String sendMessageModelToJson(ChatMessageModel data) => + json.encode(data.toJson()); + +class ChatMessageModel { + ChatMessageModel({ + required this.chatUserJid, + required this.contactType, + required this.isItCarbonMessage, + required this.isItSavedContact, + required this.isMessageDeleted, + required this.isMessageRecalled, + required this.isMessageSentByMe, + required this.isMessageStarred, + required this.isThisAReplyMessage, + required this.messageChatType, + required this.messageCustomField, + required this.messageId, + required this.messageSentTime, + required this.messageStatus, + required this.messageTextContent, + required this.messageType, + required this.replyParentChatMessage, // + required this.senderNickName, + required this.senderUserJid, + required this.senderUserName, + required this.contactChatMessage, // + required this.mediaChatMessage, // + required this.locationChatMessage, // + }); + + String chatUserJid; + String? contactType; + bool? isItCarbonMessage; + bool? isItSavedContact; + bool isMessageDeleted; + RxBool isMessageRecalled; + bool isMessageSentByMe; + RxBool isMessageStarred; + bool isThisAReplyMessage; + String messageChatType; + Map messageCustomField; + String messageId; + dynamic messageSentTime; + RxString messageStatus; + String? messageTextContent; + String messageType; + ReplyParentChatMessage? replyParentChatMessage; + String senderNickName; + String senderUserJid; + String senderUserName; + ContactChatMessage? contactChatMessage; + MediaChatMessage? mediaChatMessage; + LocationChatMessage? locationChatMessage; + + var isSelected = false.obs; + + factory ChatMessageModel.fromJson(Map json) => + ChatMessageModel( + chatUserJid: json["chatUserJid"] ?? "", + contactType: json["contactType"] == "unknown" + ? "unknown_contact" + : json["contactType"] == "live" + ? "live_contact" + : json["contactType"] == "local" + ? "local_contact" + : json["contactType"] == "deleted" + ? "deleted_contact" + : json["contactType"] ?? "", + isItCarbonMessage: Platform.isAndroid + ? json["isItCarbonMessage"] ?? false + : json["isCarbonMessage"] ?? false, + isItSavedContact: Platform.isAndroid + ? json["isItSavedContact"] ?? false + : json["isSavedContact"] ?? false, + isMessageDeleted: json["isMessageDeleted"], + isMessageRecalled: json["isMessageRecalled"].toString().toBool().obs, + isMessageSentByMe: json["isMessageSentByMe"], + isMessageStarred: json["isMessageStarred"].toString().toBool().obs, + isThisAReplyMessage: Platform.isAndroid + ? json["isThisAReplyMessage"] + : json["isReplyMessage"], + messageChatType: json["messageChatType"] == "singleChat" + ? "chat" + : json["messageChatType"].toLowerCase(), + messageCustomField: json["messageCustomField"] ?? {}, + messageId: json["messageId"], + messageSentTime: json["messageSentTime"].toInt(), + messageStatus: Platform.isAndroid + ? (json["messageStatus"]["status"]).toString().obs + : json["messageStatus"] == 2 + ? "A".obs + : json["messageStatus"] == 3 + ? "D".obs + : json["messageStatus"] == 4 + ? "S".obs + : json["messageStatus"] == 5 + ? "R".obs + : "N".obs, //"N" for "sent" in iOS + messageTextContent: json["messageTextContent"].toString(), + messageType: json["messageType"].toString().toUpperCase() == "FILE" + ? "DOCUMENT" + : json["messageType"].toString().toUpperCase(), + replyParentChatMessage: json["replyParentChatMessage"] == null + ? null + : ReplyParentChatMessage.fromJson(json["replyParentChatMessage"]), + senderNickName: json["senderNickName"], + senderUserJid: json["senderUserJid"], + senderUserName: json["senderUserName"], + contactChatMessage: json["contactChatMessage"] == null + ? null + : ContactChatMessage.fromJson(json["contactChatMessage"]), + mediaChatMessage: json["mediaChatMessage"] == null + ? null + : MediaChatMessage.fromJson(json["mediaChatMessage"]), + locationChatMessage: json["locationChatMessage"] == null + ? null + : LocationChatMessage.fromJson(json["locationChatMessage"]), + ); + + Map toJson() => { + "chatUserJid": chatUserJid, + "contactType": contactType, + "isItCarbonMessage": isItCarbonMessage, + "isItSavedContact": isItSavedContact, + "isMessageDeleted": isMessageDeleted, + "isMessageRecalled": isMessageRecalled, + "isMessageSentByMe": isMessageSentByMe, + "isMessageStarred": isMessageStarred, + "isThisAReplyMessage": isThisAReplyMessage, + "messageChatType": messageChatType, + "messageCustomField": messageCustomField, + "messageId": messageId, + "messageSentTime": messageSentTime, + "messageStatus": messageStatus, + "messageTextContent": messageTextContent, + "messageType": messageType, + "replyParentChatMessage": + replyParentChatMessage ?? replyParentChatMessage?.toJson(), + "senderNickName": senderNickName, + "senderUserJid": senderUserJid, + "senderUserName": senderUserName, + "contactChatMessage": + contactChatMessage == null ? null : contactChatMessage!.toJson(), + "mediaChatMessage": + mediaChatMessage == null ? null : mediaChatMessage!.toJson(), + "locationChatMessage": + locationChatMessage == null ? null : locationChatMessage!.toJson(), + }; +} + +class ContactChatMessage { + ContactChatMessage({ + required this.contactName, + required this.contactPhoneNumbers, + required this.isChatAppUser, + required this.messageId, + }); + + String contactName; + List contactPhoneNumbers; + List isChatAppUser; + String messageId; + + factory ContactChatMessage.fromJson(Map json) => + ContactChatMessage( + contactName: json["contactName"], + contactPhoneNumbers: + List.from(json["contactPhoneNumbers"].map((x) => x)), + isChatAppUser: Platform.isAndroid + ? List.from(json["isChatAppUser"].map((x) => x)) + : List.from(json["isChatUser"].map((x) => x)), + messageId: json["messageId"], + ); + + Map toJson() => { + "contactName": contactName, + "contactPhoneNumbers": + List.from(contactPhoneNumbers.map((x) => x)), + "isChatAppUser": List.from(isChatAppUser.map((x) => x)), + "messageId": messageId, + }; +} + +class LocationChatMessage { + LocationChatMessage({ + required this.latitude, + required this.longitude, + required this.mapLocationUrl, + required this.messageId, + }); + + double latitude; + double longitude; + String mapLocationUrl; + String messageId; + + factory LocationChatMessage.fromJson(Map json) => + LocationChatMessage( + latitude: json["latitude"].toDouble(), + longitude: json["longitude"].toDouble(), + mapLocationUrl: json["mapLocationUrl"], + messageId: json["messageId"], + ); + + Map toJson() => { + "latitude": latitude, + "longitude": longitude, + "mapLocationUrl": mapLocationUrl, + "messageId": messageId, + }; +} + +class MediaChatMessage { + MediaChatMessage({ + required this.isAudioRecorded, + required this.mediaCaptionText, + required this.mediaDownloadStatus, + required this.mediaDuration, + required this.mediaFileHeight, + required this.mediaFileName, + required this.mediaFileSize, + required this.mediaFileType, + required this.mediaFileWidth, + required this.mediaLocalStoragePath, + required this.mediaProgressStatus, + required this.mediaThumbImage, + required this.mediaUploadStatus, + required this.messageId, + required this.messageType, + required this.isPlaying, + required this.currentPos, + }); + + bool isAudioRecorded; + String mediaCaptionText; + int mediaDownloadStatus; + int mediaDuration; + int mediaFileHeight; + String mediaFileName; + int mediaFileSize; + String mediaFileType; + int mediaFileWidth; + String mediaLocalStoragePath; + RxInt mediaProgressStatus; + String mediaThumbImage; + int mediaUploadStatus; + String messageId; + String messageType; + bool isPlaying; + int currentPos; + + factory MediaChatMessage.fromJson(Map json) => + MediaChatMessage( + isAudioRecorded: Platform.isAndroid + ? json["isAudioRecorded"] ?? false + : json["audioType"] == "recording" + ? true + : false, + mediaCaptionText: json["mediaCaptionText"] ?? "", + mediaDownloadStatus: Platform.isIOS + ? json["mediaDownloadStatus"] == 4 + ? 5 + : json["mediaDownloadStatus"] == 5 + ? 3 + : json["mediaDownloadStatus"] == 6 + ? 4 + : json["mediaDownloadStatus"] == 7 + ? 6 + : json["mediaDownloadStatus"] == 9 + ? 401 + : json["mediaDownloadStatus"] + : json["mediaDownloadStatus"] == "not_downloaded" + ? 5 + : json["mediaDownloadStatus"] == "downloading" + ? 3 + : json["mediaDownloadStatus"] == "downloaded" + ? 4 + : json["mediaDownloadStatus"] == "not_available" + ? 6 + : json["mediaDownloadStatus"] == "failed" + ? 401 + : json["mediaDownloadStatus"], + mediaDuration: json["mediaDuration"], + mediaFileHeight: json["mediaFileHeight"] ?? 0, + mediaFileName: json["mediaFileName"], + mediaFileSize: json["mediaFileSize"], + // mediaFileType: json["mediaFileType"], + mediaFileType: Platform.isAndroid + ? json["mediaFileType"] + : json["mediaFileType"].toString().toUpperCase() == "FILE" + ? "DOCUMENT" + : json["mediaFileType"].toString().toUpperCase(), + mediaFileWidth: json["mediaFileWidth"] ?? 0, + mediaLocalStoragePath: json["mediaLocalStoragePath"], + mediaProgressStatus: + int.parse(json["mediaProgressStatus"].toString()).obs, + mediaThumbImage: json["mediaThumbImage"] + .toString() + .replaceAll("\\\\n", "\\n") + .replaceAll("\\n", "\n") + .replaceAll("\n", "") + .replaceAll(" ", ""), + mediaUploadStatus: Platform.isIOS + ? json["mediaUploadStatus"] == 3 + ? 7 + : json["mediaUploadStatus"] == 8 + ? 401 + : json["mediaUploadStatus"] + : json["mediaUploadStatus"] == "not_uploaded" + ? 0 + : json["mediaUploadStatus"] == "uploading" + ? 1 + : json["mediaUploadStatus"] == "uploaded" + ? 2 + : json["mediaUploadStatus"] == "not_available" + ? 7 + : json["mediaUploadStatus"] == "failed" + ? 401 + : json["mediaUploadStatus"], + messageId: json["messageId"], + messageType: Platform.isAndroid + ? json["messageType"] + : json["mediaFileType"].toString().toUpperCase() == "FILE" + ? "DOCUMENT" + : json["mediaFileType"], + isPlaying: false, + currentPos: 0, + ); + + Map toJson() => { + "isAudioRecorded": isAudioRecorded, + "mediaCaptionText": mediaCaptionText, + "mediaDownloadStatus": mediaDownloadStatus, + "mediaDuration": mediaDuration, + "mediaFileHeight": mediaFileHeight, + "mediaFileName": mediaFileName, + "mediaFileSize": mediaFileSize, + "mediaFileType": mediaFileType, + "mediaFileWidth": mediaFileWidth, + "mediaLocalStoragePath": mediaLocalStoragePath, + "mediaProgressStatus": mediaProgressStatus, + "mediaThumbImage": mediaThumbImage, + "mediaUploadStatus": mediaUploadStatus, + "messageId": messageId, + "messageType": messageType, + "isPlaying": isPlaying, + }; +} + +class MessageCustomField { + MessageCustomField(); + + factory MessageCustomField.fromJson(Map json) => + MessageCustomField(); + + Map toJson() => {}; +} + +class MessageStatus { + MessageStatus({ + required this.status, + }); + + String status; + + factory MessageStatus.fromJson(Map json) => MessageStatus( + status: json["status"], + ); + + Map toJson() => { + "status": status, + }; +} + +class ReplyParentChatMessage { + ReplyParentChatMessage({ + required this.chatUserJid, + required this.isMessageDeleted, + required this.isMessageRecalled, + required this.isMessageSentByMe, + required this.isMessageStarred, + required this.messageId, + required this.messageSentTime, + required this.messageTextContent, + required this.messageType, + required this.senderNickName, + required this.senderUserName, + required this.locationChatMessage, + required this.contactChatMessage, + required this.mediaChatMessage, + }); + + String chatUserJid; + bool isMessageDeleted; + bool isMessageRecalled; + bool isMessageSentByMe; + bool isMessageStarred; + String messageId; + dynamic messageSentTime; + String? messageTextContent; + String messageType; + String senderNickName; + String senderUserName; + LocationChatMessage? locationChatMessage; + ContactChatMessage? contactChatMessage; + MediaChatMessage? mediaChatMessage; + + factory ReplyParentChatMessage.fromJson(Map json) => + ReplyParentChatMessage( + chatUserJid: json["chatUserJid"], + isMessageDeleted: json["isMessageDeleted"], + isMessageRecalled: json["isMessageRecalled"], + isMessageSentByMe: json["isMessageSentByMe"], + isMessageStarred: json["isMessageStarred"], + messageId: json["messageId"], + messageSentTime: json["messageSentTime"], + messageTextContent: json["messageTextContent"], + messageType: Platform.isAndroid + ? json["messageType"] + : json["messageTextContent"].toString().isNotEmpty + ? "TEXT" + : json["mediaChatMessage"] != null && + json["mediaChatMessage"]["mediaFileType"] + .toString() + .isNotEmpty + ? json["mediaChatMessage"]["mediaFileType"] + .toString() + .toUpperCase() == + "FILE" + ? "DOCUMENT" + : json["mediaChatMessage"]["mediaFileType"] + .toString() + .toUpperCase() + : json["contactChatMessage"] != null + ? "CONTACT" + : json["locationChatMessage"] != null + ? "LOCATION" + : null, + senderNickName: json["senderNickName"], + senderUserName: json["senderUserName"], + locationChatMessage: json["locationChatMessage"] == null + ? null + : LocationChatMessage.fromJson(json["locationChatMessage"]), + contactChatMessage: json["contactChatMessage"] == null + ? null + : ContactChatMessage.fromJson(json["contactChatMessage"]), + mediaChatMessage: json["mediaChatMessage"] == null + ? null + : MediaChatMessage.fromJson(json["mediaChatMessage"]), + ); + + Map toJson() => { + "chatUserJid": chatUserJid, + "isMessageDeleted": isMessageDeleted, + "isMessageRecalled": isMessageRecalled, + "isMessageSentByMe": isMessageSentByMe, + "isMessageStarred": isMessageStarred, + "messageId": messageId, + "messageSentTime": messageSentTime, + "messageTextContent": messageTextContent, + "messageType": messageType, + "senderNickName": senderNickName, + "senderUserName": senderUserName, + "locationChatMessage": + locationChatMessage ?? locationChatMessage?.toJson(), + "contactChatMessage": + contactChatMessage ?? contactChatMessage?.toJson(), + "mediaChatMessage": mediaChatMessage ?? mediaChatMessage?.toJson(), + }; +} diff --git a/lib/app/model/group_media_model.dart b/lib/app/model/group_media_model.dart new file mode 100644 index 00000000..39c58291 --- /dev/null +++ b/lib/app/model/group_media_model.dart @@ -0,0 +1,22 @@ + + +import 'package:mirror_fly_demo/app/model/chat_message_model.dart'; + +abstract class GroupedMedia { + late double id; +} + +class MessageItem implements GroupedMedia { + final ChatMessageModel chatMessage; + Map? linkMap = {}; + @override + var id = -double.infinity + 0; + MessageItem(this.chatMessage, [this.linkMap]); +} + +class Header implements GroupedMedia { + final String titleName; + @override + var id = -double.infinity + 1; + Header(this.titleName); +} diff --git a/lib/app/modules/archived_chats/archived_chat_list_controller.dart b/lib/app/modules/archived_chats/archived_chat_list_controller.dart index 67ca6394..9894af11 100644 --- a/lib/app/modules/archived_chats/archived_chat_list_controller.dart +++ b/lib/app/modules/archived_chats/archived_chat_list_controller.dart @@ -1,11 +1,12 @@ import 'package:flutter/material.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; +import 'package:mirrorfly_plugin/mirrorflychat.dart'; import 'package:get/get.dart'; import 'package:mirror_fly_demo/app/common/constants.dart'; import 'package:mirror_fly_demo/app/modules/dashboard/controllers/dashboard_controller.dart'; import '../../data/apputils.dart'; import '../../data/helper.dart'; +import '../../model/chat_message_model.dart'; import '../../routes/app_pages.dart'; class ArchivedChatListController extends GetxController { @@ -64,11 +65,12 @@ class ArchivedChatListController extends GetxController { } menuValidationForItem() { - delete(false); + // delete(false); if (selectedChats.length == 1) { var item = archivedChats .firstWhere((element) => selectedChats.first == element.jid); - delete(Constants.typeGroupChat != item.getChatType()); + // delete(Constants.typeGroupChat != item.getChatType()); + menuValidationForDeleteIcon(); if ((Constants.typeBroadcastChat != item.getChatType()&& !archiveEnabled.value)) { unMute(item.isMuted!); mute(!item.isMuted!); @@ -123,13 +125,13 @@ class ArchivedChatListController extends GetxController { } } - toChatPage(String jid) async { + toChatPage(String jid) { if (jid.isNotEmpty) { // Helper.progressLoading(); - await Mirrorfly.getProfileDetails(jid, false).then((value) { - if (value != null) { + getProfileDetails(jid).then((value) { + if (value.jid != null) { Helper.hideLoading(); - var profile = profiledata(value.toString()); + var profile = value;//profiledata(value.toString()); Get.toNamed(Routes.chat, arguments: profile); } }); @@ -199,16 +201,9 @@ class ArchivedChatListController extends GetxController { updateArchiveRecentChat(chatMessage.chatUserJid); } - void onMessageStatusUpdated(event) { + void onMessageStatusUpdated(ChatMessageModel chatMessageModel) { // mirrorFlyLog("MESSAGE STATUS UPDATED", event); - ChatMessageModel chatMessageModel = sendMessageModelFromJson(event); - final index = archivedChats.indexWhere( - (message) => message.lastMessageId == chatMessageModel.messageId); - debugPrint("Message Status Update index of search $index"); - if (!index.isNegative) { - archivedChats[index].lastMessageStatus = chatMessageModel.messageStatus; - archivedChats.refresh(); - } + updateArchiveRecentChat(chatMessageModel.chatUserJid); } Future getRecentChatOfJid(String jid) async { @@ -405,5 +400,52 @@ class ArchivedChatListController extends GetxController { void userDeletedHisProfile(String jid) { userUpdatedHisProfile(jid); + updateProfile(jid); + } + var profile_ = Profile().obs; + void getProfileDetail(context, RecentChatData chatItem, int index) { + getProfileDetails(chatItem.jid.checkNull()).then((value) { + profile_(value); + debugPrint("dashboard controller profile update received"); + showQuickProfilePopup( + context: context, + // chatItem: chatItem, + chatTap: () { + Get.back(); + toChatPage(chatItem.jid.checkNull()); + }, + callTap: () {}, + videoTap: () {}, + infoTap: () { + Get.back(); + infoPage(value); + }, + profile: profile_); + }); + } + void updateProfile(String jid){ + if(profile_.value.jid != null && profile_.value.jid.toString()==jid.toString()) { + getProfileDetails(jid).then((value) { + debugPrint("get profile detail archived $value"); + profile_(value); + }); + } + } + infoPage(Profile profile) { + if (profile.isGroupProfile ?? false) { + Get.toNamed(Routes.groupInfo, arguments: profile)?.then((value) { + if (value != null) { + // profile_(value as Profile); + // isBlocked(profile.isBlocked); + // checkAdminBlocked(); + // memberOfGroup(); + // Mirrorfly.setOnGoingChatUser(profile.jid!); + // getChatHistory(); + // sendReadReceipt(); + } + }); + } else { + Get.toNamed(Routes.chatInfo, arguments: profile)?.then((value) {}); + } } } diff --git a/lib/app/modules/archived_chats/archived_chat_list_view.dart b/lib/app/modules/archived_chats/archived_chat_list_view.dart index f6a23036..58166ad1 100644 --- a/lib/app/modules/archived_chats/archived_chat_list_view.dart +++ b/lib/app/modules/archived_chats/archived_chat_list_view.dart @@ -122,6 +122,9 @@ class ArchivedChatListView extends GetView { return Obx(() { return RecentChatItem( item: item, + onAvatarClick: (){ + controller.getProfileDetail(context, item, index); + }, isSelected: controller.isSelected(index), typingUserid: controller.typingUser( item.jid.checkNull()), diff --git a/lib/app/modules/camera_pick/controllers/camera_pick_controller.dart b/lib/app/modules/camera_pick/controllers/camera_pick_controller.dart index 3826c8f7..c635a6c0 100644 --- a/lib/app/modules/camera_pick/controllers/camera_pick_controller.dart +++ b/lib/app/modules/camera_pick/controllers/camera_pick_controller.dart @@ -99,9 +99,8 @@ class CameraPickController extends GetxController with WidgetsBindingObserver { } Timer? countdownTimer; - Duration myDuration = const Duration(seconds: 40000); - int maxVideoDuration = 40000; - var seconds = 40000.obs; + Duration myDuration = const Duration(seconds: 300); + int maxVideoDuration = 300; void startTimer() { countdownTimer = Timer.periodic(const Duration(seconds: 1), (_) => setCountDown()); @@ -119,7 +118,8 @@ class CameraPickController extends GetxController with WidgetsBindingObserver { progress(counter); debugPrint(counter.toString()); if(counter==maxVideoDuration){ - stopVideoRecording(); + // stopVideoRecording(); + stopRecord(); } } @@ -137,7 +137,7 @@ class CameraPickController extends GetxController with WidgetsBindingObserver { } try { - await cameraController!.startVideoRecording(); + await cameraController?.startVideoRecording(); startTimer(); isRecording(true); } on CameraException catch (e) { @@ -167,7 +167,7 @@ class CameraPickController extends GetxController with WidgetsBindingObserver { } try { - return cameraController!.stopVideoRecording(); + return cameraController?.stopVideoRecording(); } on CameraException catch (e) { _showCameraException(e); return null; diff --git a/lib/app/modules/camera_pick/views/camera_pick_view.dart b/lib/app/modules/camera_pick/views/camera_pick_view.dart index 5b74b1bb..ef750cb5 100644 --- a/lib/app/modules/camera_pick/views/camera_pick_view.dart +++ b/lib/app/modules/camera_pick/views/camera_pick_view.dart @@ -10,36 +10,31 @@ class CameraPickView extends GetView { @override Widget build(BuildContext context) { - return SafeArea( - child: Scaffold( - body: Column( + return Scaffold( + backgroundColor: Colors.black, + body: SafeArea( + child: Column( children: [ Expanded( child: Obx(() { return controller.cameraInitialized.value ? Stack( children: [ - SizedBox( - width: MediaQuery - .of(context) - .size - .width, - child: Listener( - onPointerDown: (_) => controller.pointers++, - onPointerUp: (_) => controller.pointers--, - child: CameraPreview( - controller.cameraController!, child: LayoutBuilder( - builder: (BuildContext context, - BoxConstraints constraints) { - return GestureDetector( - behavior: HitTestBehavior.opaque, - onScaleStart: controller.handleScaleStart, - onScaleUpdate: controller.handleScaleUpdate, - onTapDown: (TapDownDetails details) => - controller.onViewFinderTap( - details, constraints), - ); - }),), - ), + Listener( + onPointerDown: (_) => controller.pointers++, + onPointerUp: (_) => controller.pointers--, + child: CameraPreview( + controller.cameraController!, child: LayoutBuilder( + builder: (BuildContext context, + BoxConstraints constraints) { + return GestureDetector( + behavior: HitTestBehavior.opaque, + onScaleStart: controller.handleScaleStart, + onScaleUpdate: controller.handleScaleUpdate, + onTapDown: (TapDownDetails details) => + controller.onViewFinderTap( + details, constraints), + ); + }),), ), /*Stack( alignment: Alignment.center, @@ -71,7 +66,7 @@ class CameraPickView extends GetView { mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ - SizedBox(height:12,width: 12,child: CircularProgressIndicator(backgroundColor: Colors.red,value: controller.progress/1000,valueColor: const AlwaysStoppedAnimation(Colors.white))), + SizedBox(height:12,width: 12,child: CircularProgressIndicator(backgroundColor: Colors.red,value: controller.progress/controller.maxVideoDuration,valueColor: const AlwaysStoppedAnimation(Colors.white))), Padding( padding: const EdgeInsets.all(5.0), child: Text(controller.timeString,style: const TextStyle(color: Colors.white),), @@ -91,10 +86,6 @@ class CameraPickView extends GetView { Container( color: Colors.black, padding: const EdgeInsets.only(top: 5, bottom: 5), - width: MediaQuery - .of(context) - .size - .width, child: Column( children: [ Row( diff --git a/lib/app/modules/chat/chat_widgets.dart b/lib/app/modules/chat/chat_widgets.dart index 51893057..c7410b68 100644 --- a/lib/app/modules/chat/chat_widgets.dart +++ b/lib/app/modules/chat/chat_widgets.dart @@ -5,11 +5,10 @@ import 'package:audioplayers/audioplayers.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_svg/flutter_svg.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; +import 'package:mirrorfly_plugin/mirrorflychat.dart'; import 'package:get/get.dart'; import 'package:intl/intl.dart'; import 'package:mirror_fly_demo/app/common/widgets.dart'; -import 'package:permission_handler/permission_handler.dart'; import 'package:url_launcher/url_launcher.dart'; import '../../common/constants.dart'; @@ -17,15 +16,15 @@ import '../../data/apputils.dart'; import '../../data/helper.dart'; import '../../data/permissions.dart'; import '../../data/session_management.dart'; +import '../../model/chat_message_model.dart'; import '../../routes/app_pages.dart'; import '../dashboard/widgets.dart'; class ReplyingMessageHeader extends StatelessWidget { - const ReplyingMessageHeader( - {Key? key, - required this.chatMessage, - required this.onCancel, - required this.onClick}) + const ReplyingMessageHeader({Key? key, + required this.chatMessage, + required this.onCancel, + required this.onClick}) : super(key: key); final ChatMessageModel chatMessage; final Function() onCancel; @@ -89,7 +88,7 @@ class ReplyingMessageHeader extends StatelessWidget { backgroundColor: Colors.white, radius: 10, child: - Icon(Icons.close, size: 15, color: Colors.black)), + Icon(Icons.close, size: 15, color: Colors.black)), ), ), ], @@ -103,17 +102,18 @@ class ReplyingMessageHeader extends StatelessWidget { } getReplyTitle(bool isMessageSentByMe, String senderUserName) { + /*debugPrint("issentby me $isMessageSentByMe"); + debugPrint("senderUserName $senderUserName");*/ return isMessageSentByMe ? const Text( - 'You', - style: TextStyle(fontWeight: FontWeight.bold), - ) + 'You', + style: TextStyle(fontWeight: FontWeight.bold), + ) : Text(senderUserName, - style: const TextStyle(fontWeight: FontWeight.bold)); + style: const TextStyle(fontWeight: FontWeight.bold)); } -getReplyMessage( - String messageType, +getReplyMessage(String messageType, String? messageTextContent, String? contactName, String? mediaFileName, @@ -125,7 +125,9 @@ getReplyMessage( return Row( children: [ Helper.forMessageTypeIcon(Constants.mText), - Text(messageTextContent!), + // Text(messageTextContent!), + Expanded(child: Text(messageTextContent!, maxLines: 1,overflow: TextOverflow.ellipsis)), + ], ); case Constants.mImage: @@ -153,15 +155,15 @@ getReplyMessage( children: [ isReplying ? Helper.forMessageTypeIcon( - Constants.mAudio, - mediaChatMessage != null - ? mediaChatMessage.isAudioRecorded - : true) + Constants.mAudio, + mediaChatMessage != null + ? mediaChatMessage.isAudioRecorded + : true) : const SizedBox.shrink(), isReplying ? const SizedBox( - width: 5, - ) + width: 5, + ) : const SizedBox.shrink(), Text( Helper.durationToString(Duration( @@ -213,7 +215,8 @@ getReplyMessage( const SizedBox( width: 5, ), - Flexible(child: Text(mediaFileName!, overflow: TextOverflow.ellipsis, maxLines: 1,)), + Flexible(child: Text( + mediaFileName!, overflow: TextOverflow.ellipsis, maxLines: 1,)), ], ); default: @@ -224,8 +227,7 @@ getReplyMessage( // chatMessage.messageType.toUpperCase(), // chatMessage.mediaChatMessage?.mediaThumbImage, // chatMessage.locationChatMessage, -getReplyImageHolder( - BuildContext context, +getReplyImageHolder(BuildContext context, ChatMessageModel chatMessageModel, MediaChatMessage? mediaChatMessage, double size, @@ -236,9 +238,9 @@ getReplyImageHolder( isReply = true; } switch (isReply - ? mediaChatMessage == null ? "LOCATION" : mediaChatMessage.messageType.checkNull().toUpperCase() + ? mediaChatMessage == null ? "LOCATION" : mediaChatMessage.messageType + .checkNull().toUpperCase() : chatMessageModel.messageType.checkNull().toUpperCase()) { - case Constants.mImage: debugPrint("reply header--> IMAGE"); return ClipRRect( @@ -248,14 +250,14 @@ getReplyImageHolder( isReply ? mediaChatMessage!.mediaThumbImage : chatMessageModel.mediaChatMessage!.mediaThumbImage - .checkNull(), + .checkNull(), context, size, size), ); case Constants.mLocation: - // debugPrint("location mesg--> ${locationChatMessage?.toJson().toString()}"); - // debugPrint("location mesg--> ${chatMessageModel.locationChatMessage?.toJson().toString()}"); + // debugPrint("location mesg--> ${locationChatMessage?.toJson().toString()}"); + // debugPrint("location mesg--> ${chatMessageModel.locationChatMessage?.toJson().toString()}"); return getLocationImage( isReply ? locationChatMessage : chatMessageModel.locationChatMessage, size, @@ -281,42 +283,43 @@ getReplyImageHolder( return isNotChatItem ? SizedBox(height: size) : Container( - width: size, - height: size, - decoration: const BoxDecoration( - borderRadius: BorderRadius.only(topRight : Radius.circular(10), bottomRight: Radius.circular(10)), - color: Colors.white, - ), - child: Center( - child: getImageHolder( - isReply - ? mediaChatMessage!.mediaFileName - : chatMessageModel.mediaChatMessage!.mediaFileName, - 30), - )); + width: size, + height: size, + decoration: const BoxDecoration( + borderRadius: BorderRadius.only(topRight: Radius.circular(10), + bottomRight: Radius.circular(10)), + color: Colors.white, + ), + child: Center( + child: getImageHolder( + isReply + ? mediaChatMessage!.mediaFileName + : chatMessageModel.mediaChatMessage!.mediaFileName, + 30), + )); case Constants.mAudio: return isNotChatItem ? SizedBox(height: size) : ClipRRect( - borderRadius: const BorderRadius.only( - topRight: Radius.circular(5), - bottomRight: Radius.circular(5)), - child: Container( - height: size, - width: size, - color: audioBgColor, - child: Center( - child: SvgPicture.asset( - mediaChatMessage!.isAudioRecorded.checkNull() - ? mAudioRecordIcon - : mAudioIcon, - fit: BoxFit.contain, - color: Colors.white, - height: 18, - ), - ), - ), - ); + borderRadius: const BorderRadius.only( + topRight: Radius.circular(5), + bottomRight: Radius.circular(5)), + child: Container( + height: size, + width: size, + color: audioBgColor, + child: Center( + child: SvgPicture.asset( + mediaChatMessage!.isAudioRecorded.checkNull() + ? mAudioRecordIcon + : mAudioIcon, + fit: BoxFit.contain, + color: Colors.white, + height: 18, + ), + ), + ), + ); default: debugPrint("reply header--> DEFAULT"); return SizedBox( @@ -377,33 +380,40 @@ class ReplyMessageHeader extends StatelessWidget { } } -Image imageFromBase64String( - String base64String, BuildContext context, double? width, double? height) { +Image imageFromBase64String(String base64String, BuildContext context, + double? width, double? height) { var decodedBase64 = base64String.replaceAll("\n", ""); Uint8List image = const Base64Decoder().convert(decodedBase64); return Image.memory( image, - width: width ?? MediaQuery.of(context).size.width * 0.60, - height: height ?? MediaQuery.of(context).size.height * 0.4, + width: width ?? MediaQuery + .of(context) + .size + .width * 0.60, + height: height ?? MediaQuery + .of(context) + .size + .height * 0.4, fit: BoxFit.cover, ); } -Widget getLocationImage( - LocationChatMessage? locationChatMessage, double width, double height, +Widget getLocationImage(LocationChatMessage? locationChatMessage, double width, + double height, {bool isSelected = false}) { return InkWell( onTap: isSelected ? null : () async { - String googleUrl = - 'https://www.google.com/maps/search/?api=1&query=${locationChatMessage!.latitude}, ${locationChatMessage.longitude}'; - if (await canLaunchUrl(Uri.parse(googleUrl))) { - await launchUrl(Uri.parse(googleUrl)); - } else { - throw 'Could not open the map.'; - } - }, + String googleUrl = + 'https://www.google.com/maps/search/?api=1&query=${locationChatMessage! + .latitude}, ${locationChatMessage.longitude}'; + if (await canLaunchUrl(Uri.parse(googleUrl))) { + await launchUrl(Uri.parse(googleUrl)); + } else { + throw 'Could not open the map.'; + } + }, child: Image.network( Helper.getMapImageUri( locationChatMessage!.latitude, locationChatMessage.longitude), @@ -414,11 +424,10 @@ Widget getLocationImage( } class SenderHeader extends StatelessWidget { - const SenderHeader( - {Key? key, - required this.isGroupProfile, - required this.chatList, - required this.index}) + const SenderHeader({Key? key, + required this.isGroupProfile, + required this.chatList, + required this.index}) : super(key: key); final bool? isGroupProfile; final List chatList; @@ -430,7 +439,7 @@ class SenderHeader extends StatelessWidget { var currentMessage = messageList[position]; var previousMessage = messageList[preposition]; if (currentMessage.isMessageSentByMe != - previousMessage.isMessageSentByMe || + previousMessage.isMessageSentByMe || previousMessage.messageType == Constants.msgTypeNotification || (currentMessage.messageChatType == Constants.typeGroupChat && currentMessage.isThisAReplyMessage)) { @@ -452,8 +461,8 @@ class SenderHeader extends StatelessWidget { return previousMessage != null && checkIsNotNotification(previousMessage); } - ChatMessageModel? getPreviousMessage( - List messageList, int position) { + ChatMessageModel? getPreviousMessage(List messageList, + int position) { return (position > 0) ? messageList[position + 1] : null; } @@ -468,8 +477,8 @@ class SenderHeader extends StatelessWidget { return Visibility( visible: isGroupProfile ?? false ? (index == chatList.length - 1 || - isSenderChanged(chatList, index)) && - !chatList[index].isMessageSentByMe + isSenderChanged(chatList, index)) && + !chatList[index].isMessageSentByMe : false, child: Padding( padding: const EdgeInsets.only(top: 8.0, right: 8.0, left: 8.0), @@ -492,6 +501,7 @@ class LocationMessageView extends StatelessWidget { : super(key: key); final ChatMessageModel chatMessage; final bool isSelected; + @override Widget build(BuildContext context) { return Padding( @@ -509,14 +519,15 @@ class LocationMessageView extends StatelessWidget { child: Row( mainAxisSize: MainAxisSize.min, children: [ - chatMessage.isMessageStarred + chatMessage.isMessageStarred.value ? SvgPicture.asset(starSmallIcon) : const SizedBox.shrink(), const SizedBox( width: 5, ), - getMessageIndicator(chatMessage.messageStatus, - chatMessage.isMessageSentByMe, chatMessage.messageType,chatMessage.isMessageRecalled), + getMessageIndicator(chatMessage.messageStatus.value, + chatMessage.isMessageSentByMe, chatMessage.messageType, + chatMessage.isMessageRecalled.value), const SizedBox( width: 4, ), @@ -538,11 +549,10 @@ class LocationMessageView extends StatelessWidget { } class AudioMessageView extends StatefulWidget { - const AudioMessageView( - {Key? key, - required this.chatMessage, - required this.onPlayAudio, - required this.onSeekbarChange}) + const AudioMessageView({Key? key, + required this.chatMessage, + required this.onPlayAudio, + required this.onSeekbarChange}) : super(key: key); final ChatMessageModel chatMessage; final Function() onPlayAudio; @@ -561,9 +571,9 @@ class _AudioMessageViewState extends State case Constants.mediaDownloaded: case Constants.mediaUploaded: if (checkFile( - widget.chatMessage.mediaChatMessage!.mediaLocalStoragePath) && + widget.chatMessage.mediaChatMessage!.mediaLocalStoragePath) && (widget.chatMessage.mediaChatMessage!.mediaDownloadStatus == - Constants.mediaDownloaded || + Constants.mediaDownloaded || widget.chatMessage.mediaChatMessage!.mediaDownloadStatus == Constants.mediaUploaded || widget.chatMessage.isMessageSentByMe)) { @@ -588,7 +598,10 @@ class _AudioMessageViewState extends State void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); - currentPos = widget.chatMessage.mediaChatMessage!.currentPos.toDouble().obs; + currentPos = widget.chatMessage.mediaChatMessage! + .currentPos + .toDouble() + .obs; player.onPlayerCompletion.listen((event) { isPlaying(false); currentPos(0); @@ -634,9 +647,12 @@ class _AudioMessageViewState extends State @override Widget build(BuildContext context) { - var screenWidth = MediaQuery.of(context).size.width; + var screenWidth = MediaQuery + .of(context) + .size + .width; var currentPos = - 0.0; /*double.parse(widget.chatMessage + 0.0; /*double.parse(widget.chatMessage .mediaChatMessage!.currentPos .toString()); var maxPos = double.parse(widget.chatMessage @@ -649,7 +665,8 @@ class _AudioMessageViewState extends State "currentPos--> ${double.parse( widget.chatMessage.mediaChatMessage!.currentPos.toString())}");*/ debugPrint( - "max duration--> ${double.parse(widget.chatMessage.mediaChatMessage!.mediaDuration.toString())}"); + "max duration--> ${double.parse( + widget.chatMessage.mediaChatMessage!.mediaDuration.toString())}"); return Container( decoration: BoxDecoration( border: Border.all( @@ -678,24 +695,24 @@ class _AudioMessageViewState extends State children: [ widget.chatMessage.mediaChatMessage!.isAudioRecorded ? Stack( - alignment: Alignment.center, - children: [ - SvgPicture.asset( - audioMicBg, - width: 28, - height: 28, - fit: BoxFit.contain, - ), - SvgPicture.asset( - audioMic1, - fit: BoxFit.contain, - ), - ], - ) + alignment: Alignment.center, + children: [ + SvgPicture.asset( + audioMicBg, + width: 28, + height: 28, + fit: BoxFit.contain, + ), + SvgPicture.asset( + audioMic1, + fit: BoxFit.contain, + ), + ], + ) : SvgPicture.asset( - musicIcon, - fit: BoxFit.contain, - ), + musicIcon, + fit: BoxFit.contain, + ), getImageOverlay(widget.chatMessage, onAudio: () { widget.onPlayAudio(); playAudio(widget.chatMessage); @@ -744,13 +761,13 @@ class _AudioMessageViewState extends State child: Text( Helper.durationToString(Duration( milliseconds: currentPos != - 0.0 // chatMessage.mediaChatMessage?.currentPos != 0 + 0.0 // chatMessage.mediaChatMessage?.currentPos != 0 ? currentPos - .toInt() /*chatMessage + .toInt() /*chatMessage .mediaChatMessage?.currentPos ?? 0*/ : widget.chatMessage.mediaChatMessage! - .mediaDuration)), + .mediaDuration)), style: const TextStyle( color: durationTextColor, fontSize: 8, @@ -771,16 +788,17 @@ class _AudioMessageViewState extends State child: Row( mainAxisSize: MainAxisSize.min, children: [ - widget.chatMessage.isMessageStarred + widget.chatMessage.isMessageStarred.value ? SvgPicture.asset(starSmallIcon) : const SizedBox.shrink(), const SizedBox( width: 5, ), getMessageIndicator( - widget.chatMessage.messageStatus, + widget.chatMessage.messageStatus.value, widget.chatMessage.isMessageSentByMe, - widget.chatMessage.messageType,widget.chatMessage.isMessageRecalled), + widget.chatMessage.messageType, + widget.chatMessage.isMessageRecalled.value), const SizedBox( width: 4, ), @@ -809,7 +827,7 @@ class _AudioMessageViewState extends State playAudio(ChatMessageModel chatMessage) { var maxPos = - double.parse(chatMessage.mediaChatMessage!.mediaDuration.toString()); + double.parse(chatMessage.mediaChatMessage!.mediaDuration.toString()); /*if(!(currentPos >= 0.0 && currentPos <= maxPos)){ currentPos(maxPos); }*/ @@ -837,24 +855,24 @@ class _AudioMessageViewState extends State ), widget.chatMessage.mediaChatMessage!.isAudioRecorded ? Stack( - alignment: Alignment.center, - children: [ - SvgPicture.asset( - audioMicBg, - width: 28, - height: 28, - fit: BoxFit.contain, - ), - SvgPicture.asset( - audioMic1, - fit: BoxFit.contain, - ), - ], - ) + alignment: Alignment.center, + children: [ + SvgPicture.asset( + audioMicBg, + width: 28, + height: 28, + fit: BoxFit.contain, + ), + SvgPicture.asset( + audioMic1, + fit: BoxFit.contain, + ), + ], + ) : SvgPicture.asset( - musicIcon, - fit: BoxFit.contain, - ), + musicIcon, + fit: BoxFit.contain, + ), const SizedBox( width: 4, ), @@ -866,7 +884,7 @@ class _AudioMessageViewState extends State chatMessage.mediaChatMessage!.mediaLocalStoragePath, position: Duration( milliseconds: - chatMessage.mediaChatMessage!.currentPos), + chatMessage.mediaChatMessage!.currentPos), isLocal: true); if (result == 1) { isPlaying(true); @@ -886,13 +904,13 @@ class _AudioMessageViewState extends State padding: const EdgeInsets.all(8.0), child: isPlaying.value ? SvgPicture.asset( - pauseIcon, - height: 17, - ) //const Icon(Icons.pause) + pauseIcon, + height: 17, + ) //const Icon(Icons.pause) : SvgPicture.asset( - playIcon, - height: 17, - ), + playIcon, + height: 17, + ), ), ); }), @@ -913,7 +931,7 @@ class _AudioMessageViewState extends State child: Obx(() { return Slider( value: (!(currentPos.value >= 0.0 && - currentPos.value <= maxPos)) + currentPos.value <= maxPos)) ? maxPos : currentPos.value, /*double.parse(chatMessage @@ -927,7 +945,7 @@ class _AudioMessageViewState extends State .mediaChatMessage!.mediaDuration .toString()), divisions: - chatMessage.mediaChatMessage!.mediaDuration, + chatMessage.mediaChatMessage!.mediaDuration, onChanged: (double value) { // debugPrint('onChanged $value'); player.seek( @@ -952,7 +970,7 @@ class _AudioMessageViewState extends State Helper.durationToString(Duration( milliseconds: currentPos.value == 0.0 ? widget.chatMessage.mediaChatMessage! - .mediaDuration + .mediaDuration : currentPos.value.toInt())), style: const TextStyle( color: durationTextColor, @@ -988,18 +1006,21 @@ class _AudioMessageViewState extends State } class ContactMessageView extends StatelessWidget { - const ContactMessageView( - {Key? key, - required this.chatMessage, - this.search = "", - required this.isSelected}) + const ContactMessageView({Key? key, + required this.chatMessage, + this.search = "", + required this.isSelected}) : super(key: key); final ChatMessageModel chatMessage; final String search; final bool isSelected; + @override Widget build(BuildContext context) { - var screenWidth = MediaQuery.of(context).size.width; + var screenWidth = MediaQuery + .of(context) + .size + .width; return Container( decoration: BoxDecoration( borderRadius: const BorderRadius.all(Radius.circular(10)), @@ -1025,20 +1046,20 @@ class ContactMessageView extends StatelessWidget { Expanded( child: search.isEmpty ? textMessageSpannableText( - chatMessage.contactChatMessage!.contactName - .checkNull(), - maxLines: 2) + chatMessage.contactChatMessage!.contactName + .checkNull(), + maxLines: 2) : chatSpannedText( - chatMessage.contactChatMessage!.contactName, - search, - const TextStyle(fontSize: 14, color: textHintColor), - maxLines: - 2) /*,Text( + chatMessage.contactChatMessage!.contactName, + search, + const TextStyle(fontSize: 14, color: textHintColor), + maxLines: + 2) /*,Text( chatMessage.contactChatMessage!.contactName, maxLines: 2, overflow: TextOverflow.ellipsis, )*/ - ), + ), ], ), ), @@ -1047,14 +1068,15 @@ class ContactMessageView extends StatelessWidget { child: Row( mainAxisSize: MainAxisSize.min, children: [ - chatMessage.isMessageStarred + chatMessage.isMessageStarred.value ? SvgPicture.asset(starSmallIcon) : const SizedBox.shrink(), const SizedBox( width: 5, ), - getMessageIndicator(chatMessage.messageStatus, - chatMessage.isMessageSentByMe, chatMessage.messageType,chatMessage.isMessageRecalled), + getMessageIndicator(chatMessage.messageStatus.value, + chatMessage.isMessageSentByMe, chatMessage.messageType, + chatMessage.isMessageRecalled.value), const SizedBox( width: 4, ), @@ -1085,7 +1107,8 @@ class ContactMessageView extends StatelessWidget { Future getUserJid(ContactChatMessage contactChatMessage) async { for (int i = 0; i < contactChatMessage.contactPhoneNumbers.length; i++) { debugPrint( - "contactChatMessage.isChatAppUser[i]--> ${contactChatMessage.isChatAppUser[i]}"); + "contactChatMessage.isChatAppUser[i]--> ${contactChatMessage + .isChatAppUser[i]}"); if (contactChatMessage.isChatAppUser[i]) { return await Mirrorfly.getJidFromPhoneNumber( contactChatMessage.contactPhoneNumbers[i], @@ -1121,11 +1144,11 @@ class ContactMessageView extends StatelessWidget { Expanded( child: Center( child: Padding( - padding: const EdgeInsets.all(8.0), - child: (userJid != null && userJid.isNotEmpty) - ? const Text("Message") - : const Text("Invite"), - ))), + padding: const EdgeInsets.all(8.0), + child: (userJid != null && userJid.isNotEmpty) + ? const Text("Message") + : const Text("Invite"), + ))), ], ), ); @@ -1191,7 +1214,7 @@ class ContactMessageView extends StatelessWidget { String? encodeQueryParameters(Map params) { return params.entries .map((e) => - '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}') + '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}') .join('&'); } } @@ -1210,7 +1233,10 @@ class DocumentMessageView extends StatelessWidget { @override Widget build(BuildContext context) { - var screenWidth = MediaQuery.of(context).size.width; + var screenWidth = MediaQuery + .of(context) + .size + .width; return InkWell( onTap: () { onDocumentClick(); @@ -1251,21 +1277,22 @@ class DocumentMessageView extends StatelessWidget { ), Expanded( child: search.isEmpty - ? Text(chatMessage.mediaChatMessage!.mediaFileName,style: const TextStyle( - fontSize: 12,),maxLines: 2,)/*textMessageSpannableText( + ? Text(chatMessage.mediaChatMessage!.mediaFileName, + style: const TextStyle( + fontSize: 12,), maxLines: 2,) /*textMessageSpannableText( chatMessage.mediaChatMessage!.mediaFileName .checkNull(), maxLines: 2, )*/ : chatSpannedText( - chatMessage.mediaChatMessage!.mediaFileName - .checkNull(), - search, - const TextStyle( - color: Colors.black, - fontWeight: FontWeight.w400), - maxLines: - 2), /*Text( + chatMessage.mediaChatMessage!.mediaFileName + .checkNull(), + search, + const TextStyle( + color: Colors.black, + fontWeight: FontWeight.w400), + maxLines: + 2), /*Text( chatMessage.mediaChatMessage!.mediaFileName, maxLines: 2, style: const TextStyle(fontSize: 12,color: Colors.black,fontWeight: FontWeight.w400), @@ -1295,14 +1322,15 @@ class DocumentMessageView extends StatelessWidget { fontWeight: FontWeight.w400), ), const Spacer(), - chatMessage.isMessageStarred + chatMessage.isMessageStarred.value ? SvgPicture.asset(starSmallIcon) : const SizedBox.shrink(), const SizedBox( width: 5, ), - getMessageIndicator(chatMessage.messageStatus, - chatMessage.isMessageSentByMe, chatMessage.messageType,chatMessage.isMessageRecalled), + getMessageIndicator(chatMessage.messageStatus.value, + chatMessage.isMessageSentByMe, chatMessage.messageType, + chatMessage.isMessageRecalled.value), const SizedBox( width: 4, ), @@ -1337,11 +1365,10 @@ Widget getImageHolder(String mediaFileName, double size) { } class VideoMessageView extends StatelessWidget { - const VideoMessageView( - {Key? key, - required this.chatMessage, - this.search = "", - required this.isSelected}) + const VideoMessageView({Key? key, + required this.chatMessage, + this.search = "", + required this.isSelected}) : super(key: key); final ChatMessageModel chatMessage; final String search; @@ -1356,7 +1383,7 @@ class VideoMessageView extends StatelessWidget { if (chatMessage.messageType.toUpperCase() == 'VIDEO') { if (checkFile(chatMessage.mediaChatMessage!.mediaLocalStoragePath) && (chatMessage.mediaChatMessage!.mediaDownloadStatus == - Constants.mediaDownloaded || + Constants.mediaDownloaded || chatMessage.mediaChatMessage!.mediaDownloadStatus == Constants.mediaUploaded || chatMessage.isMessageSentByMe)) { @@ -1376,7 +1403,10 @@ class VideoMessageView extends StatelessWidget { Widget build(BuildContext context) { var mediaMessage = chatMessage.mediaChatMessage!; // var screenHeight = MediaQuery.of(context).size.height; - var screenWidth = MediaQuery.of(context).size.width; + var screenWidth = MediaQuery + .of(context) + .size + .width; return Container( width: screenWidth * 0.60, padding: const EdgeInsets.all(2.0), @@ -1389,8 +1419,8 @@ class VideoMessageView extends StatelessWidget { onTap: isSelected ? null : () { - onVideoClick(); - }, + onVideoClick(); + }, child: ClipRRect( borderRadius: BorderRadius.circular(15), child: imageFromBase64String( @@ -1420,44 +1450,48 @@ class VideoMessageView extends StatelessWidget { ), getImageOverlay(chatMessage, onVideo: isSelected ? null : onVideoClick), - mediaMessage.mediaCaptionText.checkNull().isEmpty + mediaMessage.mediaCaptionText + .checkNull() + .isEmpty ? Positioned( - bottom: 8, - right: 10, - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - chatMessage.isMessageStarred - ? SvgPicture.asset(starSmallIcon) - : const SizedBox.shrink(), - const SizedBox( - width: 5, - ), - getMessageIndicator( - chatMessage.messageStatus, - chatMessage.isMessageSentByMe, - chatMessage.messageType,chatMessage.isMessageRecalled), - const SizedBox( - width: 4, - ), - Text( - getChatTime( - context, chatMessage.messageSentTime.toInt()), - style: TextStyle( - fontSize: 11, - color: chatMessage.isMessageSentByMe - ? durationTextColor - : textHintColor), - ), - ], - ), - ) + bottom: 8, + right: 10, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + chatMessage.isMessageStarred.value + ? SvgPicture.asset(starSmallIcon) + : const SizedBox.shrink(), + const SizedBox( + width: 5, + ), + getMessageIndicator( + chatMessage.messageStatus.value, + chatMessage.isMessageSentByMe, + chatMessage.messageType, chatMessage.isMessageRecalled.value), + const SizedBox( + width: 4, + ), + Text( + getChatTime( + context, chatMessage.messageSentTime.toInt()), + style: TextStyle( + fontSize: 11, + color: chatMessage.isMessageSentByMe + ? durationTextColor + : textHintColor), + ), + ], + ), + ) : const SizedBox(), ], ), - mediaMessage.mediaCaptionText.checkNull().isNotEmpty + mediaMessage.mediaCaptionText + .checkNull() + .isNotEmpty ? setCaptionMessage(mediaMessage, chatMessage, context, - search: search) + search: search) : const SizedBox() ], ), @@ -1466,11 +1500,10 @@ class VideoMessageView extends StatelessWidget { } class ImageMessageView extends StatelessWidget { - const ImageMessageView( - {Key? key, - required this.chatMessage, - this.search = "", - required this.isSelected}) + const ImageMessageView({Key? key, + required this.chatMessage, + this.search = "", + required this.isSelected}) : super(key: key); final ChatMessageModel chatMessage; final String search; @@ -1480,7 +1513,10 @@ class ImageMessageView extends StatelessWidget { Widget build(BuildContext context) { var mediaMessage = chatMessage.mediaChatMessage!; // var screenHeight = MediaQuery.of(context).size.height; - var screenWidth = MediaQuery.of(context).size.width; + var screenWidth = MediaQuery + .of(context) + .size + .width; return Container( width: screenWidth * 0.60, padding: const EdgeInsets.all(2.0), @@ -1499,49 +1535,54 @@ class ImageMessageView extends StatelessWidget { isSelected), ), getImageOverlay(chatMessage), - mediaMessage.mediaCaptionText.checkNull().isEmpty + mediaMessage.mediaCaptionText + .checkNull() + .isEmpty ? Positioned( - bottom: 8, - right: 10, - child: Stack( - children: [ - SvgPicture.asset(mediaBg), - Row( - mainAxisSize: MainAxisSize.min, - children: [ - chatMessage.isMessageStarred - ? SvgPicture.asset(starSmallIcon) - : const SizedBox.shrink(), - const SizedBox( - width: 5, - ), - getMessageIndicator( - chatMessage.messageStatus, - chatMessage.isMessageSentByMe, - chatMessage.messageType,chatMessage.isMessageRecalled), - const SizedBox( - width: 4, - ), - Text( - getChatTime(context, - chatMessage.messageSentTime.toInt()), - style: TextStyle( - fontSize: 11, - color: chatMessage.isMessageSentByMe - ? durationTextColor - : textButtonColor), - ), - ], - ), - ], - ), - ) + bottom: 8, + right: 10, + child: Stack( + children: [ + SvgPicture.asset(mediaBg), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + chatMessage.isMessageStarred.value + ? SvgPicture.asset(starSmallIcon) + : const SizedBox.shrink(), + const SizedBox( + width: 5, + ), + getMessageIndicator( + chatMessage.messageStatus.value, + chatMessage.isMessageSentByMe, + chatMessage.messageType, + chatMessage.isMessageRecalled.value), + const SizedBox( + width: 4, + ), + Text( + getChatTime(context, + chatMessage.messageSentTime.toInt()), + style: TextStyle( + fontSize: 11, + color: chatMessage.isMessageSentByMe + ? durationTextColor + : textButtonColor), + ), + ], + ), + ], + ), + ) : const SizedBox(), ], ), - mediaMessage.mediaCaptionText.checkNull().isNotEmpty + mediaMessage.mediaCaptionText + .checkNull() + .isNotEmpty ? setCaptionMessage(mediaMessage, chatMessage, context, - search: search) + search: search) : const SizedBox(), ], ), @@ -1550,18 +1591,24 @@ class ImageMessageView extends StatelessWidget { getImage(String mediaLocalStoragePath, String mediaThumbImage, BuildContext context, String mediaFileName, bool isSelected) { - var screenHeight = MediaQuery.of(context).size.height; - var screenWidth = MediaQuery.of(context).size.width; + var screenHeight = MediaQuery + .of(context) + .size + .height; + var screenWidth = MediaQuery + .of(context) + .size + .width; if (checkFile(mediaLocalStoragePath)) { return InkWell( onTap: isSelected ? null : () { - Get.toNamed(Routes.imageView, arguments: { - 'imageName': mediaFileName, - 'imagePath': mediaLocalStoragePath - }); - }, + Get.toNamed(Routes.imageView, arguments: { + 'imageName': mediaFileName, + 'imagePath': mediaLocalStoragePath + }); + }, child: Image( image: FileImage(File(mediaLocalStoragePath)), loadingBuilder: (context, child, loadingProgress) { @@ -1581,7 +1628,7 @@ class ImageMessageView extends StatelessWidget { height: controller.screenHeight * 0.4, fit: BoxFit.cover, )*/ - ); + ); } else { return imageFromBase64String(mediaThumbImage, context, null, null); } @@ -1598,23 +1645,24 @@ Widget setCaptionMessage(MediaChatMessage mediaMessage, children: [ search.isEmpty ? textMessageSpannableText( - mediaMessage.mediaCaptionText.checkNull()) + mediaMessage.mediaCaptionText.checkNull()) : chatSpannedText( - mediaMessage.mediaCaptionText.checkNull(), - search, - const TextStyle(fontSize: 14, color: textHintColor), - ), + mediaMessage.mediaCaptionText.checkNull(), + search, + const TextStyle(fontSize: 14, color: textHintColor), + ), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ - chatMessage.isMessageStarred + chatMessage.isMessageStarred.value ? SvgPicture.asset(starSmallIcon) : const SizedBox.shrink(), const SizedBox( width: 5, ), - getMessageIndicator(chatMessage.messageStatus, - chatMessage.isMessageSentByMe, chatMessage.messageType,chatMessage.isMessageRecalled), + getMessageIndicator(chatMessage.messageStatus.value, + chatMessage.isMessageSentByMe, chatMessage.messageType, + chatMessage.isMessageRecalled.value), const SizedBox( width: 5, ), @@ -1658,14 +1706,13 @@ class NotificationMessageView extends StatelessWidget { } class MessageContent extends StatelessWidget { - const MessageContent( - {Key? key, - required this.chatList, - required this.index, - this.search = "", - this.isSelected = false, - required this.onPlayAudio, - required this.onSeekbarChange}) + const MessageContent({Key? key, + required this.chatList, + required this.index, + this.search = "", + this.isSelected = false, + required this.onPlayAudio, + required this.onSeekbarChange}) : super(key: key); final List chatList; final int index; @@ -1679,7 +1726,7 @@ class MessageContent extends StatelessWidget { var chatMessage = chatList[index]; //mirrorFlyLog("message==>", json.encode(chatMessage)); // debugPrint("Message Type===> ${chatMessage.messageType}"); - if (chatList[index].isMessageRecalled) { + if (chatList[index].isMessageRecalled.value) { return RecalledMessageView( chatMessage: chatMessage, ); @@ -1728,7 +1775,7 @@ class MessageContent extends StatelessWidget { search: search, isSelected: isSelected); } else if (chatList[index].messageType.toUpperCase() == - Constants.mDocument || + Constants.mDocument || chatList[index].messageType.toUpperCase() == Constants.mFile) { return DocumentMessageView( chatMessage: chatMessage, @@ -1774,24 +1821,25 @@ class TextMessageView extends StatelessWidget { child: search.isEmpty ? textMessageSpannableText(chatMessage.messageTextContent ?? "") : chatSpannedText( - chatMessage.messageTextContent ?? "", - search, - const TextStyle(fontSize: 14, color: textHintColor), - ), + chatMessage.messageTextContent ?? "", + search, + const TextStyle(fontSize: 14, color: textHintColor), + ), ), const SizedBox( width: 10, ), Row( children: [ - chatMessage.isMessageStarred + chatMessage.isMessageStarred.value ? SvgPicture.asset(starSmallIcon) : const SizedBox.shrink(), const SizedBox( width: 5, ), - getMessageIndicator(chatMessage.messageStatus, - chatMessage.isMessageSentByMe, chatMessage.messageType,chatMessage.isMessageRecalled), + getMessageIndicator(chatMessage.messageStatus.value, + chatMessage.isMessageSentByMe, chatMessage.messageType, + chatMessage.isMessageRecalled.value), const SizedBox( width: 5, ), @@ -1866,7 +1914,8 @@ class RecalledMessageView extends StatelessWidget { } } -getMessageIndicator(String? messageStatus, bool isSender, String messageType,bool isRecalled) { +getMessageIndicator(String? messageStatus, bool isSender, String messageType, + bool isRecalled) { // debugPrint("Message Status ==>"); // debugPrint("Message Status ==> $messageStatus"); if (isSender && !isRecalled) { @@ -1894,7 +1943,7 @@ Widget getImageOverlay(ChatMessageModel chatMessage, // debugPrint( // "getImageOverlay ${(checkFile(chatMessage.mediaChatMessage!.mediaLocalStoragePath) && chatMessage.messageStatus != 'N')}"); if (checkFile(chatMessage.mediaChatMessage!.mediaLocalStoragePath) && - chatMessage.messageStatus != 'N') { + chatMessage.messageStatus.value != 'N') { if (chatMessage.messageType.toUpperCase() == 'VIDEO') { return FloatingActionButton.small( onPressed: onVideo, @@ -1911,13 +1960,13 @@ Widget getImageOverlay(ChatMessageModel chatMessage, padding: const EdgeInsets.all(8.0), child: chatMessage.mediaChatMessage!.isPlaying ? SvgPicture.asset( - pauseIcon, - height: 17, - ) //const Icon(Icons.pause) + pauseIcon, + height: 17, + ) //const Icon(Icons.pause) : SvgPicture.asset( - playIcon, - height: 17, - ), + playIcon, + height: 17, + ), ), ); //const Icon(Icons.play_arrow_sharp); } else { @@ -1960,8 +2009,10 @@ Widget getImageOverlay(ChatMessageModel chatMessage, onTap: () { cancelMediaUploadOrDownload(chatMessage.messageId); }, - child: downloadingOrUploadingView(chatMessage.messageType, - chatMessage.mediaChatMessage!.mediaProgressStatus)); + child: Obx(() { + return downloadingOrUploadingView(chatMessage.messageType, + chatMessage.mediaChatMessage!.mediaProgressStatus.value); + })); default: return const SizedBox.shrink(); } @@ -1973,34 +2024,34 @@ uploadView(int mediaDownloadStatus, int mediaFileSize, String messageType) { padding: const EdgeInsets.symmetric(horizontal: 8.0), child: messageType == 'AUDIO' || messageType == 'DOCUMENT' ? Container( - decoration: BoxDecoration( - border: Border.all(color: borderColor), - borderRadius: BorderRadius.circular(3)), - padding: const EdgeInsets.all(5), - child: SvgPicture.asset( - uploadIcon, - color: playIconColor, - )) + decoration: BoxDecoration( + border: Border.all(color: borderColor), + borderRadius: BorderRadius.circular(3)), + padding: const EdgeInsets.all(5), + child: SvgPicture.asset( + uploadIcon, + color: playIconColor, + )) : Container( - width: 80, - decoration: const BoxDecoration( - borderRadius: BorderRadius.all(Radius.circular(5)), - color: Colors.black45, + width: 80, + decoration: const BoxDecoration( + borderRadius: BorderRadius.all(Radius.circular(5)), + color: Colors.black45, + ), + padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SvgPicture.asset(uploadIcon), + const SizedBox( + width: 5, ), - padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - SvgPicture.asset(uploadIcon), - const SizedBox( - width: 5, - ), - const Text( - "RETRY", - style: TextStyle(color: Colors.white, fontSize: 10), - ), - ], - )), + const Text( + "RETRY", + style: TextStyle(color: Colors.white, fontSize: 10), + ), + ], + )), ); } @@ -2020,7 +2071,8 @@ void downloadMedia(String messageId) async { debugPrint("media download click"); debugPrint("media download click--> $messageId"); if (await AppUtils.isNetConnected()) { - if (await askStoragePermission()) { + var permission = await AppPermission.getStoragePermission(); + if (permission) { debugPrint("media permission granted"); Mirrorfly.downloadMedia(messageId); } else { @@ -2031,56 +2083,43 @@ void downloadMedia(String messageId) async { } } -Future askStoragePermission() async { - final permission = await AppPermission.getStoragePermission(); - switch (permission) { - case PermissionStatus.granted: - return true; - case PermissionStatus.permanentlyDenied: - return false; - default: - debugPrint("Permission default"); - return false; - } -} - -Widget downloadView( - int mediaDownloadStatus, int mediaFileSize, String messageType) { +Widget downloadView(int mediaDownloadStatus, int mediaFileSize, + String messageType) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: messageType == 'AUDIO' || messageType == 'DOCUMENT' ? Container( - decoration: BoxDecoration( - border: Border.all(color: borderColor), - borderRadius: BorderRadius.circular(3)), - padding: const EdgeInsets.all(5), - child: SvgPicture.asset( - downloadIcon, - color: playIconColor, - )) + decoration: BoxDecoration( + border: Border.all(color: borderColor), + borderRadius: BorderRadius.circular(3)), + padding: const EdgeInsets.all(5), + child: SvgPicture.asset( + downloadIcon, + color: playIconColor, + )) : Container( - width: 80, - decoration: BoxDecoration( - border: Border.all( - color: textColor, - ), - borderRadius: const BorderRadius.all(Radius.circular(5)), - color: Colors.black38, + width: 80, + decoration: BoxDecoration( + border: Border.all( + color: textColor, + ), + borderRadius: const BorderRadius.all(Radius.circular(5)), + color: Colors.black38, + ), + padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SvgPicture.asset(downloadIcon), + const SizedBox( + width: 5, ), - padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - SvgPicture.asset(downloadIcon), - const SizedBox( - width: 5, - ), - Text( - Helper.formatBytes(mediaFileSize, 0), - style: const TextStyle(color: Colors.white, fontSize: 10), - ), - ], - )), + Text( + Helper.formatBytes(mediaFileSize, 0), + style: const TextStyle(color: Colors.white, fontSize: 10), + ), + ], + )), ); } @@ -2163,14 +2202,13 @@ downloadingOrUploadingView(String messageType, int progress) { } class AttachmentsSheetView extends StatelessWidget { - const AttachmentsSheetView( - {Key? key, - required this.onDocument, - required this.onCamera, - required this.onGallery, - required this.onAudio, - required this.onContact, - required this.onLocation}) + const AttachmentsSheetView({Key? key, + required this.onDocument, + required this.onCamera, + required this.onGallery, + required this.onAudio, + required this.onContact, + required this.onLocation}) : super(key: key); final Function() onDocument; final Function() onCamera; @@ -2319,7 +2357,9 @@ Widget chatSpannedText(String text, String spannableText, TextStyle? style, class AudioMessagePlayerController extends GetxController { final _obj = ''.obs; + set obj(value) => _obj.value = value; + get obj => _obj.value; var maxDuration = 100.obs; var currentPos = 0.obs; @@ -2345,6 +2385,7 @@ class AudioMessagePlayerController extends GetxController { } ChatMessageModel? playingChat; + playAudio(ChatMessageModel chatMessage, String filePath) async { if (playingChat != null) { if (playingChat?.mediaChatMessage!.messageId != chatMessage.messageId) { @@ -2359,7 +2400,7 @@ class AudioMessagePlayerController extends GetxController { int result = await player.play( playingChat!.mediaChatMessage!.mediaLocalStoragePath, position: - Duration(milliseconds: playingChat!.mediaChatMessage!.currentPos), + Duration(milliseconds: playingChat!.mediaChatMessage!.currentPos), isLocal: true); if (result == 1) { playingChat!.mediaChatMessage!.isPlaying = true; @@ -2414,8 +2455,8 @@ String? groupedDateMessage(int index, List chatList) { return addDateHeaderMessage(chatList.last); } else { return (isDateChanged(index, chatList) && - (addDateHeaderMessage(chatList[index + 1]) != - addDateHeaderMessage(chatList[index]))) + (addDateHeaderMessage(chatList[index + 1]) != + addDateHeaderMessage(chatList[index]))) ? addDateHeaderMessage(chatList[index]) : null; } @@ -2426,7 +2467,10 @@ String addDateHeaderMessage(ChatMessageModel item) { var messageDate = getDateFromTimestamp(item.messageSentTime, "MMMM dd, yyyy"); var monthNumber = calendar.month - 1; var month = getMonthForInt(monthNumber); - var yesterdayDate = DateTime.now().subtract(const Duration(days: 1)).day; + var yesterdayDate = DateTime + .now() + .subtract(const Duration(days: 1)) + .day; var today = "$month ${checkTwoDigitsForDate(calendar.day)}, ${calendar.year}"; var yesterday = "$month ${checkTwoDigitsForDate(yesterdayDate)}, ${calendar.year}"; @@ -2448,7 +2492,9 @@ String addDateHeaderMessage(ChatMessageModel item) { } String checkTwoDigitsForDate(int date) { - if (date.toString().length != 2) { + if (date + .toString() + .length != 2) { return "0$date"; } else { return date.toString(); diff --git a/lib/app/modules/chat/controllers/chat_controller.dart b/lib/app/modules/chat/controllers/chat_controller.dart index 694e4eb8..21d1e599 100644 --- a/lib/app/modules/chat/controllers/chat_controller.dart +++ b/lib/app/modules/chat/controllers/chat_controller.dart @@ -10,7 +10,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart'; import 'package:flutter_libphonenumber/flutter_libphonenumber.dart'; import 'package:get/get.dart'; -import 'package:google_cloud_translation/google_cloud_translation.dart'; +// import 'package:google_cloud_translation/google_cloud_translation.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:intl/intl.dart'; import 'package:mirror_fly_demo/app/common/de_bouncer.dart'; @@ -26,17 +26,18 @@ import 'package:url_launcher/url_launcher.dart'; import '../../../common/constants.dart'; import '../../../data/apputils.dart'; import '../../../data/helper.dart'; +import '../../../model/chat_message_model.dart'; import '../../../model/reply_hash_map.dart'; import '../../../routes/app_pages.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; +import 'package:mirrorfly_plugin/mirrorflychat.dart'; import '../../gallery_picker/src/data/models/picked_asset_model.dart'; import '../chat_widgets.dart'; class ChatController extends FullLifeCycleController with FullLifeCycleMixin, GetTickerProviderStateMixin { - final translator = Translation(apiKey: Constants.googleTranslateKey); + // final translator = Translation(apiKey: Constants.googleTranslateKey); var chatList = List.empty(growable: true).obs; late AnimationController controller; @@ -70,6 +71,7 @@ class ChatController extends FullLifeCycleController TextEditingController messageController = TextEditingController(); FocusNode focusNode = FocusNode(); + FocusNode searchfocusNode = FocusNode(); var calendar = DateTime.now(); var profile_ = Profile().obs; @@ -105,7 +107,7 @@ class ChatController extends FullLifeCycleController String? nJid; String? starredChatMessageId; - bool get isTrail => SessionManagement.isTrailLicence(); + bool get isTrail => Mirrorfly.isTrialLicence; @override void onInit() async { @@ -585,6 +587,8 @@ class ChatController extends FullLifeCycleController if (!chat.isNegative) { navigateToMessage(chatList[chat]); starredChatMessageId = null; + } else { + toToast('Message not found'); } } getUnsentReplyMessage(); @@ -701,7 +705,8 @@ class ChatController extends FullLifeCycleController } documentPickUpload() async { - if (await askStoragePermission()) { + var permission = await AppPermission.getStoragePermission(); + if (permission) { FilePickerResult? result = await FilePicker.platform.pickFiles( allowMultiple: false, type: FileType.custom, @@ -714,7 +719,7 @@ class ChatController extends FullLifeCycleController filePath.value = (result.files.single.path!); sendDocumentMessage(filePath.value, ""); } else { - toToast("File Size should not exceed 20 MB"); + toToast("File Size should not exceed ${Constants.maxDocFileSize} MB"); } } else { // User canceled the picker @@ -852,32 +857,6 @@ class ChatController extends FullLifeCycleController } } - Future askStoragePermission() async { - final permission = await AppPermission.getStoragePermission(); - switch (permission) { - case PermissionStatus.granted: - return true; - case PermissionStatus.permanentlyDenied: - return false; - default: - debugPrint("Permission default"); - return false; - } - } - - Future askManageStoragePermission() async { - final permission = await AppPermission.getManageStoragePermission(); - switch (permission) { - case PermissionStatus.granted: - return true; - case PermissionStatus.permanentlyDenied: - return false; - default: - debugPrint("Permission default"); - return false; - } - } - sendContactMessage(List contactList, String contactName) async { debugPrint("sendingName--> $contactName"); var busyStatus = !profile.isGroupProfile.checkNull() @@ -966,7 +945,7 @@ class ChatController extends FullLifeCycleController filePath.value, false, duration.inMilliseconds.toString()); }); } else { - toToast("File Size should not exceed 20 MB"); + toToast("File Size should not exceed ${Constants.maxAudioFileSize} MB"); } } else { // User canceled the picker @@ -1020,7 +999,7 @@ class ChatController extends FullLifeCycleController // var chatListrev = chatList.reversed; isStarredExcluded - ? chatList.removeWhere((p0) => p0.isMessageStarred == false) + ? chatList.removeWhere((p0) => p0.isMessageStarred.value == false) : chatList.clear(); cancelReplyMessage(); // chatList.refresh(); @@ -1029,7 +1008,8 @@ class ChatController extends FullLifeCycleController } void handleReplyChatMessage(ChatMessageModel chatListItem) { - if (!chatListItem.isMessageRecalled && !chatListItem.isMessageDeleted) { + if (!chatListItem.isMessageRecalled.value && + !chatListItem.isMessageDeleted) { debugPrint(chatListItem.messageType); if (isReplying.value) { isReplying(false); @@ -1052,7 +1032,7 @@ class ChatController extends FullLifeCycleController clearChatSelection(ChatMessageModel chatList) { selectedChatList.remove(chatList); - chatList.isSelected = false; + chatList.isSelected(false); if (selectedChatList.isEmpty) { isSelected(false); selectedChatList.clear(); @@ -1063,7 +1043,7 @@ class ChatController extends FullLifeCycleController clearAllChatSelection() { isSelected(false); for (var chatItem in chatList) { - chatItem.isSelected = false; + chatItem.isSelected(false); } selectedChatList.clear(); chatList.refresh(); @@ -1072,8 +1052,8 @@ class ChatController extends FullLifeCycleController void addChatSelection(ChatMessageModel item) { if (item.messageType.toUpperCase() != Constants.mNotification) { selectedChatList.add(item); - item.isSelected = true; - chatList.refresh(); + item.isSelected(true); + // chatList.refresh(); } else { debugPrint("Unable to Select Notification Banner"); } @@ -1170,7 +1150,7 @@ class ChatController extends FullLifeCycleController // PlatformRepo.copyTextMessages(selectedChatList[0].messageId); debugPrint('Copy text ==> ${selectedChatList[0].messageTextContent}'); Clipboard.setData( - ClipboardData(text: selectedChatList[0].messageTextContent)); + ClipboardData(text: selectedChatList[0].messageTextContent ?? "")); // selectedChatList.clear(); // isSelected(false); clearChatSelection(selectedChatList[0]); @@ -1183,10 +1163,10 @@ class ChatController extends FullLifeCycleController return { selectedChatList.any((element) => element.isMessageSentByMe && - !element.isMessageRecalled && + !element.isMessageRecalled.value && (element.messageSentTime > recallTimeDifference)): selectedChatList.any((element) => - !element.isMessageRecalled && + !element.isMessageRecalled.value && (element.isMediaMessage() && element.mediaChatMessage!.mediaLocalStoragePath .checkNull() @@ -1220,7 +1200,7 @@ class ChatController extends FullLifeCycleController mainAxisSize: MainAxisSize.min, children: [ Text( - "Are you sure you want to delete selected Message${selectedChatList.length > 1 ? "s" : ""}"), + "Are you sure you want to delete selected Message${selectedChatList.length > 1 ? "s" : ""}?",style: const TextStyle(fontSize: 18,color: textColor),), isCheckBoxShown ? Column( mainAxisSize: MainAxisSize.min, @@ -1255,17 +1235,12 @@ class ChatController extends FullLifeCycleController ), message: "", actions: [ - TextButton( - onPressed: () { - Get.back(); - }, - child: const Text("CANCEL")), TextButton( onPressed: () { Get.back(); //Helper.showLoading(message: 'Deleting Message'); Mirrorfly.deleteMessagesForMe(profile.jid!, chatType, - deleteChatListID, isMediaDelete.value) + deleteChatListID, isMediaDelete.value) .then((value) { debugPrint(value.toString()); //Helper.hideLoading(); @@ -1280,6 +1255,11 @@ class ChatController extends FullLifeCycleController selectedChatList.clear(); }, child: const Text("DELETE FOR ME")), + TextButton( + onPressed: () { + Get.back(); + }, + child: const Text("CANCEL")), isRecallAvailable ? TextButton( onPressed: () { @@ -1293,9 +1273,16 @@ class ChatController extends FullLifeCycleController if (value != null && value) { // removeChatList(selectedChatList);// for (var chatList in selectedChatList) { - chatList.isMessageRecalled = true; - chatList.isSelected = false; - this.chatList.refresh(); + chatList.isMessageRecalled(true); + chatList.isSelected(false); + // this.chatList.refresh(); + } + } + if (!value) { + toToast("Unable to delete the selected Messages"); + for (var chatList in selectedChatList) { + chatList.isSelected(false); + // this.chatList.refresh(); } } isSelected(false); @@ -1342,15 +1329,15 @@ class ChatController extends FullLifeCycleController });*/ for (var item in selectedChatList) { Mirrorfly.updateFavouriteStatus(item.messageId, item.chatUserJid, - !item.isMessageStarred, item.messageChatType); + !item.isMessageStarred.value, item.messageChatType); var msg = chatList.firstWhere((element) => item.messageId == element.messageId); - msg.isMessageStarred = !item.isMessageStarred; - msg.isSelected = false; + msg.isMessageStarred(!item.isMessageStarred.value); + msg.isSelected(false); } isSelected(false); selectedChatList.clear(); - chatList.refresh(); + // chatList.refresh(); } Widget getLocationImage( @@ -1414,7 +1401,7 @@ class ChatController extends FullLifeCycleController if (chatList.isNotEmpty) { Future.delayed(const Duration(milliseconds: 100), () { var starred = - chatList.indexWhere((element) => element.isMessageStarred); + chatList.indexWhere((element) => element.isMessageStarred.value); Helper.showAlert( message: "Are you sure you want to clear the chat?", actions: [ @@ -1560,7 +1547,7 @@ class ChatController extends FullLifeCycleController var j = -1; scrollUp() { - if(filteredPosition.isNotEmpty) { + if (filteredPosition.isNotEmpty) { var visiblePos = findTopFirstVisibleItemPosition(); mirrorFlyLog("visiblePos", visiblePos.toString()); mirrorFlyLog( @@ -1574,13 +1561,13 @@ class ChatController extends FullLifeCycleController } else { toToast("No Results Found"); } - }else{ + } else { toToast("No Results Found"); } } scrollDown() { - if(filteredPosition.isNotEmpty) { + if (filteredPosition.isNotEmpty) { var visiblePos = findTopFirstVisibleItemPosition(); mirrorFlyLog("visiblePos", visiblePos.toString()); var g = getPreviousPosition(findTopFirstVisibleItemPosition(), @@ -1592,7 +1579,7 @@ class ChatController extends FullLifeCycleController } else { toToast("No Results Found"); } - }else{ + } else { toToast("No Results Found"); } } @@ -1605,11 +1592,11 @@ class ChatController extends FullLifeCycleController var currentPosition = position; // filteredPosition[position]; //(chatList.length - (position)); mirrorFlyLog("currentPosition", currentPosition.toString()); - chatList[currentPosition].isSelected = true; + chatList[currentPosition].isSelected(true); searchScrollController.jumpTo(index: currentPosition); Future.delayed(const Duration(milliseconds: 800), () { currentPosition = (currentPosition); - chatList[currentPosition].isSelected = false; + chatList[currentPosition].isSelected(false); chatList.refresh(); }); } else { @@ -1695,8 +1682,23 @@ class ChatController extends FullLifeCycleController exportChat() async { if (chatList.isNotEmpty) { - if (await askStoragePermission()) { - Mirrorfly.exportChatConversationToEmail(profile.jid.checkNull()); + var permission = await AppPermission.getStoragePermission(); + if (permission) { + Mirrorfly.exportChatConversationToEmail(profile.jid.checkNull()) + .then((value) async { + debugPrint("exportChatConversationToEmail $value"); + var data = exportModelFromJson(value); + if (data.mediaAttachmentsUrl != null) { + if (data.mediaAttachmentsUrl!.isNotEmpty) { + var xfiles = []; + data.mediaAttachmentsUrl + ?.forEach((element) => xfiles.add(XFile(element))); + await Share.shareXFiles(xfiles); + } + } + }); + } else { + toToast("permission denid"); } } else { toToast("There is no conversation."); @@ -1788,7 +1790,8 @@ class ChatController extends FullLifeCycleController ? await Mirrorfly.isBusyStatusEnabled() : false; if (!busyStatus.checkNull()) { - if (await askStoragePermission()) { + var permission = await AppPermission.getStoragePermission(); + if (permission) { if (await Record().hasPermission()) { record = Record(); timerInit("00:00"); @@ -1928,11 +1931,12 @@ class ChatController extends FullLifeCycleController } void onMessageStatusUpdated(ChatMessageModel chatMessageModel) { + debugPrint("#mirrorfly chat ${chatMessageModel.toJson()}"); if (chatMessageModel.chatUserJid == profile.jid) { final index = chatList.indexWhere( (message) => message.messageId == chatMessageModel.messageId); debugPrint("ChatScreen Message Status Update index of search $index"); - debugPrint("messageID--> $index"); + debugPrint("messageID--> ${chatMessageModel.messageId}"); if (!index.isNegative) { debugPrint("messageID--> replacing the value"); // Helper.hideLoading(); @@ -1950,8 +1954,8 @@ class ChatController extends FullLifeCycleController var selectedIndex = selectedChatList.indexWhere( (element) => chatMessageModel.messageId == element.messageId); if (!selectedIndex.isNegative) { - chatMessageModel.isSelected = - true; //selectedChatList[selectedIndex].isSelected; + chatMessageModel + .isSelected(true); //selectedChatList[selectedIndex].isSelected; selectedChatList[selectedIndex] = chatMessageModel; selectedChatList.refresh(); getMessageActions(); @@ -1984,9 +1988,9 @@ class ChatController extends FullLifeCycleController void onGroupProfileUpdated(groupJid) { if (profile.jid.checkNull() == groupJid.toString()) { - Mirrorfly.getProfileDetails(profile.jid.checkNull(), false).then((value) { - if (value != null) { - var member = Profile.fromJson(json.decode(value.toString())); + getProfileDetails(profile.jid.checkNull()).then((value) { + if (value.jid != null) { + var member = value;//Profile.fromJson(json.decode(value.toString())); profile_.value = member; profile_.refresh(); checkAdminBlocked(); @@ -2146,7 +2150,8 @@ class ChatController extends FullLifeCycleController "userName": profile.name!, 'profile': profile, 'caption': messageController.text, - 'showAdd': false + 'showAdd': false, + 'from': 'camera_pick' }); } }); @@ -2172,18 +2177,15 @@ class ChatController extends FullLifeCycleController // } onAudioClick() async { - // Get.back(); - // if (await askMicrophonePermission()) { - if (await AppPermission.checkPermission( - Permission.storage, filePermission, Constants.filePermission)) { + var permission = await AppPermission.getStoragePermission(); + if (permission) { pickAudio(); } } onGalleryClick() async { - // if (await askStoragePermission()) { - if (await AppPermission.checkPermission( - Permission.storage, filePermission, Constants.filePermission)) { + var permission = await AppPermission.getStoragePermission(); + if (permission) { try { // imagePicker(); Get.toNamed(Routes.galleryPicker, arguments: { @@ -2304,7 +2306,7 @@ class ChatController extends FullLifeCycleController } bool forwardMessageVisibility(ChatMessageModel chat) { - if (!chat.isMessageRecalled && !chat.isMessageDeleted) { + if (!chat.isMessageRecalled.value && !chat.isMessageDeleted) { if (chat.isMediaMessage()) { if (chat.mediaChatMessage!.mediaDownloadStatus == Constants.mediaDownloaded || @@ -2313,7 +2315,8 @@ class ChatController extends FullLifeCycleController return true; } } else { - if (chat.messageType == Constants.mLocation) { + if (chat.messageType == Constants.mLocation || + chat.messageType == Constants.mContact) { return true; } } @@ -2382,7 +2385,7 @@ class ChatController extends FullLifeCycleController for (var message in selectedChatList) { //Recalled Validation - if (message.isMessageRecalled) { + if (message.isMessageRecalled.value) { containsRecalled(true); break; } @@ -2399,7 +2402,7 @@ class ChatController extends FullLifeCycleController setMessageActionValidations(ChatMessageModel message) { //Forward Validation - can be added for forwarding more than one messages if (!canBeForwardedSet && - ((message.isMessageSentByMe && message.messageStatus == "N") || + ((message.isMessageSentByMe && message.messageStatus.value == "N") || (message.isMediaMessage() && !checkFile(message.mediaChatMessage!.mediaLocalStoragePath)))) { canBeForwarded(false); @@ -2414,14 +2417,14 @@ class ChatController extends FullLifeCycleController canBeSharedSet = true; } //Starred Validation - if (!canBeStarredSet && message.isMessageStarred || + if (!canBeStarredSet && message.isMessageStarred.value || (message.isMediaMessage() && !checkFile(message.mediaChatMessage!.mediaLocalStoragePath))) { canBeStarred(false); canBeStarredSet = true; } //UnStarred Validation - if (!canBeUnStarredSet && !message.isMessageStarred) { + if (!canBeUnStarredSet && !message.isMessageStarred.value) { canBeUnStarred(false); canBeUnStarredSet = true; } @@ -2467,13 +2470,13 @@ class ChatController extends FullLifeCycleController setMenuItemsValidations(ChatMessageModel message) { if (!containsRecalled.value) { //Reply Validation - if (message.isMessageSentByMe && message.messageStatus == "N") { + if (message.isMessageSentByMe && message.messageStatus.value == "N") { canBeReplied(false); } //Info Validation if (!message.isMessageSentByMe || - message.messageStatus == "N" || - message.isMessageRecalled || + message.messageStatus.value == "N" || + message.isMessageRecalled.value || (message.isMediaMessage() && !checkFile(message.mediaChatMessage!.mediaLocalStoragePath))) { canShowInfo(false); @@ -2495,12 +2498,12 @@ class ChatController extends FullLifeCycleController newScrollController.scrollTo( index: chatIndex, duration: const Duration(milliseconds: 10)); Future.delayed(const Duration(milliseconds: 15), () { - chatList[chatIndex].isSelected = true; + chatList[chatIndex].isSelected(true); chatList.refresh(); }); Future.delayed(const Duration(milliseconds: 800), () { - chatList[chatIndex].isSelected = false; + chatList[chatIndex].isSelected(false); chatList.refresh(); }); } @@ -2526,6 +2529,8 @@ class ChatController extends FullLifeCycleController .isNotEmpty) { mediaPaths.add( XFile(item.mediaChatMessage!.mediaLocalStoragePath.checkNull())); + debugPrint( + "mediaPaths ${item.mediaChatMessage!.mediaLocalStoragePath.checkNull()}"); } } } @@ -2554,6 +2559,12 @@ class ChatController extends FullLifeCycleController focusNode.requestFocus(); }); } + if(searchfocusNode.hasFocus){ + searchfocusNode.unfocus(); + Future.delayed(const Duration(milliseconds: 100), () { + searchfocusNode.requestFocus(); + }); + } } Mirrorfly.setOnGoingChatUser(profile.jid.checkNull()); SessionManagement.setCurrentChatJID(profile.jid.checkNull()); @@ -2688,7 +2699,7 @@ class ChatController extends FullLifeCycleController Mirrorfly.addContact(parse["international"], userName).then((value) { if (value ?? false) { toToast("Contact Saved"); - if (!SessionManagement.isTrailLicence()) { + if (!Mirrorfly.isTrialLicence) { syncContacts(); } } @@ -2747,9 +2758,10 @@ class ChatController extends FullLifeCycleController if (!index.isNegative) { // chatMessageModel.isSelected=chatList[index].isSelected; // debugPrint("Media Status Onprogress changed---> flutter conversion ${int.parse(progressPercentage)}"); - chatList[index].mediaChatMessage?.mediaProgressStatus = - (int.parse(progressPercentage)); - chatList.refresh(); + chatList[index] + .mediaChatMessage + ?.mediaProgressStatus(int.parse(progressPercentage)); + // chatList.refresh(); } } } diff --git a/lib/app/modules/chat/controllers/contact_controller.dart b/lib/app/modules/chat/controllers/contact_controller.dart index 923d42f0..434d9931 100644 --- a/lib/app/modules/chat/controllers/contact_controller.dart +++ b/lib/app/modules/chat/controllers/contact_controller.dart @@ -17,7 +17,7 @@ class ContactController extends FullLifeCycleController ScrollController scrollController = ScrollController(); var pageNum = 1; var isPageLoading = false.obs; - var scrollable = SessionManagement.isTrailLicence().obs; + var scrollable = Mirrorfly.isTrialLicence.obs; var usersList = [].obs; var mainUsersList = List.empty(growable: true).obs; var selectedUsersList = List.empty(growable: true).obs; @@ -44,7 +44,7 @@ class ContactController extends FullLifeCycleController } scrollController.addListener(_scrollListener); //searchQuery.addListener(_searchListener); - if (await AppUtils.isNetConnected() || !SessionManagement.isTrailLicence()) { + if (await AppUtils.isNetConnected() || !Mirrorfly.isTrialLicence) { isPageLoading(true); fetchUsers(false); } else { @@ -52,7 +52,7 @@ class ContactController extends FullLifeCycleController } //Mirrorfly.syncContacts(true); //Mirrorfly.getRegisteredUsers(true).then((value) => mirrorFlyLog("registeredUsers", value.toString())); - progressSpinner(!SessionManagement.isTrailLicence() && await Mirrorfly.contactSyncStateValue()); + progressSpinner(!Mirrorfly.isTrialLicence && await Mirrorfly.contactSyncStateValue()); } void userUpdatedHisProfile(String jid) { @@ -137,7 +137,7 @@ class ContactController extends FullLifeCycleController _searchText = searchQuery.text.trim(); pageNum = 1; } - if (SessionManagement.isTrailLicence()) { + if (Mirrorfly.isTrialLicence) { deBouncer.run(() { fetchUsers(true); }); @@ -158,19 +158,19 @@ class ContactController extends FullLifeCycleController //fetchUsers(true); //} usersList(mainUsersList); - scrollable(SessionManagement.isTrailLicence()); + scrollable(Mirrorfly.isTrialLicence); } fetchUsers(bool fromSearch,{bool server=false}) async { - if(!SessionManagement.isTrailLicence()){ + if(!Mirrorfly.isTrialLicence){ var granted = await Permission.contacts.isGranted; if(!granted){ isPageLoading(false); return; } } - if (await AppUtils.isNetConnected() || !SessionManagement.isTrailLicence()) { - var future = (SessionManagement.isTrailLicence()) + if (await AppUtils.isNetConnected() || !Mirrorfly.isTrialLicence) { + var future = (Mirrorfly.isTrialLicence) ? Mirrorfly.getUserList(pageNum, _searchText) : Mirrorfly.getRegisteredUsers(false); future.then((data) async { @@ -195,7 +195,7 @@ class ContactController extends FullLifeCycleController mainUsersList(list); } if (fromSearch) { - if (SessionManagement.isTrailLicence()) { + if (Mirrorfly.isTrialLicence) { usersList(list); pageNum = pageNum + 1; scrollable.value = list.length == 20; @@ -213,7 +213,7 @@ class ContactController extends FullLifeCycleController }*/ } } else { - if (SessionManagement.isTrailLicence()) { + if (Mirrorfly.isTrialLicence) { usersList.addAll(list); pageNum = pageNum + 1; scrollable.value = list.length == 20; @@ -226,7 +226,7 @@ class ContactController extends FullLifeCycleController usersList.refresh(); } else { list.addAll(item.data!); - if (!SessionManagement.isTrailLicence() && fromSearch) { + if (!Mirrorfly.isTrialLicence && fromSearch) { var userlist = mainUsersList.where((p0) => getName(p0) .toString() .toLowerCase() @@ -243,7 +243,7 @@ class ContactController extends FullLifeCycleController mainUsersList(list); } if (fromSearch) { - if (SessionManagement.isTrailLicence()) { + if (Mirrorfly.isTrialLicence) { usersList(list); pageNum = pageNum + 1; scrollable.value = list.length == 20; @@ -261,7 +261,7 @@ class ContactController extends FullLifeCycleController }*/ } } else { - if (SessionManagement.isTrailLicence()) { + if (Mirrorfly.isTrialLicence) { usersList.addAll(list); pageNum = pageNum + 1; scrollable.value = list.length == 20; @@ -394,7 +394,7 @@ class ContactController extends FullLifeCycleController if (selectedUsersJIDList.isNotEmpty) { Get.back(result: selectedUsersJIDList); } else { - toToast("Add at least two contacts"); + toToast("Select any contacts"); } } } else { @@ -420,7 +420,7 @@ class ContactController extends FullLifeCycleController var progressSpinner = false.obs; refreshContacts(bool isNetworkToastNeeded) async { - if(!SessionManagement.isTrailLicence()) { + if(!Mirrorfly.isTrialLicence) { mirrorFlyLog('Contact Sync', "[Contact Sync] refreshContacts()"); if (await AppUtils.isNetConnected()) { if (!await Mirrorfly.contactSyncStateValue()) { @@ -479,7 +479,7 @@ class ContactController extends FullLifeCycleController FocusNode searchFocus = FocusNode(); @override Future onResumed() async { - if (!SessionManagement.isTrailLicence()) { + if (!Mirrorfly.isTrialLicence) { var status = await Permission.contacts.isGranted; if(status) { refreshContacts(false); diff --git a/lib/app/modules/chat/controllers/forwardchat_controller.dart b/lib/app/modules/chat/controllers/forwardchat_controller.dart index e35bbdfa..41c4ff4c 100644 --- a/lib/app/modules/chat/controllers/forwardchat_controller.dart +++ b/lib/app/modules/chat/controllers/forwardchat_controller.dart @@ -7,7 +7,6 @@ import 'package:permission_handler/permission_handler.dart'; import '../../../common/de_bouncer.dart'; import '../../../data/apputils.dart'; -import '../../../data/session_management.dart'; class ForwardChatController extends GetxController { //main list @@ -19,22 +18,22 @@ class ForwardChatController extends GetxController { set recentChats(List value) => _recentChats.value = value; - List get recentChats => _recentChats.value.take(3).toList(); + List get recentChats => _recentChats.take(3).toList(); final _groupList = [].obs; set groupList(List value) => _groupList.value = value; - List get groupList => _groupList.value.take(6).toList(); + List get groupList => _groupList.take(6).toList(); var userlistScrollController = ScrollController(); - var scrollable = SessionManagement.isTrailLicence().obs; + var scrollable = Mirrorfly.isTrialLicence.obs; var isPageLoading = false.obs; final _userList = [].obs; set userList(List value) => _userList.value = value; - List get userList => _userList.value; + List get userList => _userList; final _search = false.obs; @@ -157,7 +156,7 @@ class ForwardChatController extends GetxController { if (await AppUtils.isNetConnected()) { if(!bottom)contactLoading(true); searching = true; - var future = (SessionManagement.isTrailLicence()) + var future = (Mirrorfly.isTrialLicence) ? Mirrorfly.getUserList(pageNum, searchQuery.text.trim().toString()) : Mirrorfly.getRegisteredUsers(false); future @@ -169,7 +168,7 @@ class ForwardChatController extends GetxController { if (_mainuserList.isEmpty) { _mainuserList.addAll(list.data!); } - _userList.value.addAll(list.data!); + _userList.addAll(list.data!); _userList.refresh(); } } @@ -222,7 +221,7 @@ class ForwardChatController extends GetxController { _userList.clear(); searching = true; searchLoading(true); - var future = (SessionManagement.isTrailLicence()) + var future = (Mirrorfly.isTrialLicence) ? Mirrorfly.getUserList(pageNum, searchQuery.text.trim().toString()) : Mirrorfly.getRegisteredUsers(false); future @@ -231,8 +230,8 @@ class ForwardChatController extends GetxController { if (value != null) { var list = userListFromJson(value); if (list.data != null) { - scrollable((list.data!.length == 20 && SessionManagement.isTrailLicence())); - if(SessionManagement.isTrailLicence()) { + scrollable((list.data!.length == 20 && Mirrorfly.isTrialLicence)); + if(Mirrorfly.isTrialLicence) { _userList(list.data); }else{ _userList(list.data!.where((element) => element.nickName.checkNull().toLowerCase().contains(searchQuery.text.trim().toString().toLowerCase())).toList()); @@ -253,7 +252,7 @@ class ForwardChatController extends GetxController { } } - bool isChecked(String jid) => selectedJids.value.contains(jid); + bool isChecked(String jid) => selectedJids.contains(jid); void onItemSelect(String jid, String name,bool isBlocked){ if(isBlocked.checkNull()){ @@ -295,13 +294,13 @@ class ForwardChatController extends GetxController { } void onItemClicked(String jid, String name) { - if (selectedJids.value.contains(jid)) { - selectedJids.value.removeAt(selectedJids.indexOf(jid)); - selectedNames.value.removeAt(selectedNames.indexOf(name)); + if (selectedJids.contains(jid)) { + selectedJids.removeAt(selectedJids.indexOf(jid)); + selectedNames.removeAt(selectedNames.indexOf(name)); } else { - if (selectedJids.value.length < 5) { - selectedJids.value.add(jid); - selectedNames.value.add(name); + if (selectedJids.length < 5) { + selectedJids.add(jid); + selectedNames.add(name); } else { toToast("You can only forward with upto 5 users or groups"); } @@ -340,7 +339,7 @@ class ForwardChatController extends GetxController { pageNum = 1; searchQuery.clear(); _isSearchVisible(true); - scrollable((_mainuserList.length == 20 && SessionManagement.isTrailLicence())); + scrollable((_mainuserList.length == 20 && Mirrorfly.isTrialLicence)); _recentChats(_mainrecentChats); _groupList(_maingroupList); _userList(_mainuserList); @@ -350,16 +349,16 @@ class ForwardChatController extends GetxController { if (await AppUtils.isNetConnected()) { var busyStatus = await Mirrorfly.isBusyStatusEnabled(); if (!busyStatus.checkNull()) { - if (forwardMessageIds.isNotEmpty && selectedJids.value.isNotEmpty) { + if (forwardMessageIds.isNotEmpty && selectedJids.isNotEmpty) { Mirrorfly.forwardMessagesToMultipleUsers( - forwardMessageIds, selectedJids.value) + forwardMessageIds, selectedJids) .then((values) { // debugPrint("to chat profile ==> ${selectedUsersList[0].toJson().toString()}"); - Mirrorfly.getProfileDetails(selectedJids.value.last, false) + getProfileDetails(selectedJids.last) .then((value) { - if (value != null) { - var str = profiledata(value.toString()); - Get.back(result: str); + if (value.jid != null) { + // var str = profiledata(value.toString()); + Get.back(result: value); } }); }); diff --git a/lib/app/modules/chat/views/chat_search_view.dart b/lib/app/modules/chat/views/chat_search_view.dart index 72440698..d4c2c840 100644 --- a/lib/app/modules/chat/views/chat_search_view.dart +++ b/lib/app/modules/chat/views/chat_search_view.dart @@ -4,8 +4,8 @@ import 'package:get/get.dart'; import 'package:scrollable_positioned_list/scrollable_positioned_list.dart'; import '../../../common/constants.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; +import '../../../model/chat_message_model.dart'; import '../chat_widgets.dart'; import '../controllers/chat_controller.dart'; @@ -27,6 +27,7 @@ class ChatSearchView extends GetView { title: TextField( onChanged: (text) => controller.setSearch(text), controller: controller.searchedText, + focusNode: controller.searchfocusNode, autofocus: true, decoration: const InputDecoration( hintText: "Search...", border: InputBorder.none), @@ -76,7 +77,7 @@ class ChatSearchView extends GetView { (chatList[index].messageType.toUpperCase() != Constants.mNotification) ? Container( - color: chatList[index].isSelected + color: chatList[index].isSelected.value ? chatReplyContainerColor : Colors.transparent, margin: const EdgeInsets.only( diff --git a/lib/app/modules/chat/views/chat_view.dart b/lib/app/modules/chat/views/chat_view.dart index c122b8e1..58dbcde4 100644 --- a/lib/app/modules/chat/views/chat_view.dart +++ b/lib/app/modules/chat/views/chat_view.dart @@ -5,7 +5,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:get/get.dart'; -import 'package:grouped_list/grouped_list.dart'; +// import 'package:grouped_list/grouped_list.dart'; import 'package:marquee/marquee.dart'; import 'package:mirror_fly_demo/app/common/widgets.dart'; import 'package:mirror_fly_demo/app/data/helper.dart'; @@ -15,11 +15,11 @@ import 'package:scrollable_positioned_list/scrollable_positioned_list.dart'; import 'package:swipe_to/swipe_to.dart'; import '../../../common/constants.dart'; +import '../../../model/chat_message_model.dart'; import '../../../widgets/custom_action_bar_icons.dart'; import '../../../widgets/lottie_animation.dart'; import '../chat_widgets.dart'; import '../controllers/chat_controller.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; class ChatView extends GetView { const ChatView({Key? key}) : super(key: key); @@ -78,135 +78,135 @@ class ChatView extends GetView { color: Colors.white, child: controller.isBlocked.value ? userBlocked() - : !controller.isMemberOfGroup - ? userNoLonger() - : Column( - mainAxisAlignment: - MainAxisAlignment.end, - children: [ - Obx(() { - if (controller.isReplying.value) { - return ReplyingMessageHeader( - chatMessage: - controller.replyChatMessage, - onCancel: () => controller - .cancelReplyMessage(), - onClick: () { - controller.navigateToMessage( - controller - .replyChatMessage); - }, - ); - } else { - return const SizedBox.shrink(); - } - }), - const Divider( - height: 1, - thickness: 0.29, - color: textBlackColor, - ), - const SizedBox( - height: 10, - ), - IntrinsicHeight( - child: Row( - crossAxisAlignment: - CrossAxisAlignment.stretch, - children: [ - Flexible( - child: Container( - padding: - const EdgeInsets.only( - left: 10), - margin: - const EdgeInsets.only( - left: 10, - right: 10, - bottom: 10), - width: double.infinity, - decoration: BoxDecoration( - border: Border.all( - color: textColor, - ), - borderRadius: - const BorderRadius - .all( - Radius.circular( - 40)), - color: Colors.white, - ), - child: Obx(() { - return messageTypingView( - context); - }), - ), - ), - Obx(() { - return controller - .isUserTyping.value - ? InkWell( - onTap: () { - controller - .isAudioRecording - .value == - Constants - .audioRecordDone - ? controller - .sendRecordedAudioMessage() - : controller - .sendMessage( - controller - .profile); - }, - child: Padding( - padding: - const EdgeInsets - .only( - left: 8.0, - right: 8.0, - bottom: 8), - child: SvgPicture.asset( - 'assets/logos/send.svg'), - )) - : const SizedBox.shrink(); - }), - Obx(() { - return controller - .isAudioRecording - .value == - Constants - .audioRecording - ? InkWell( - onTap: () { - controller - .stopRecording(); - }, - child: const Padding( - padding: - EdgeInsets.only( - bottom: - 8.0), - child: - LottieAnimation( - lottieJson: - audioJson1, - showRepeat: true, - width: 54, - height: 54, - ), - )) - : const SizedBox.shrink(); - }), - const SizedBox( - width: 5, - ), - ], + : controller.isMemberOfGroup + ? Column( + mainAxisAlignment: + MainAxisAlignment.end, + children: [ + Obx(() { + if (controller.isReplying.value) { + return ReplyingMessageHeader( + chatMessage: + controller.replyChatMessage, + onCancel: () => controller + .cancelReplyMessage(), + onClick: () { + controller.navigateToMessage( + controller + .replyChatMessage); + }, + ); + } else { + return const SizedBox.shrink(); + } + }), + const Divider( + height: 1, + thickness: 0.29, + color: textBlackColor, + ), + const SizedBox( + height: 10, + ), + IntrinsicHeight( + child: Row( + crossAxisAlignment: + CrossAxisAlignment.stretch, + children: [ + Flexible( + child: Container( + padding: + const EdgeInsets.only( + left: 10), + margin: + const EdgeInsets.only( + left: 10, + right: 10, + bottom: 10), + width: double.infinity, + decoration: BoxDecoration( + border: Border.all( + color: textColor, ), + borderRadius: + const BorderRadius + .all( + Radius.circular( + 40)), + color: Colors.white, ), - emojiLayout(), - ], + child: Obx(() { + return messageTypingView( + context); + }), + ), + ), + Obx(() { + return controller + .isUserTyping.value + ? InkWell( + onTap: () { + controller + .isAudioRecording + .value == + Constants + .audioRecordDone + ? controller + .sendRecordedAudioMessage() + : controller + .sendMessage( + controller + .profile); + }, + child: Padding( + padding: + const EdgeInsets + .only( + left: 8.0, + right: 8.0, + bottom: 8), + child: SvgPicture.asset( + 'assets/logos/send.svg'), + )) + : const SizedBox.shrink(); + }), + Obx(() { + return controller + .isAudioRecording + .value == + Constants + .audioRecording + ? InkWell( + onTap: () { + controller + .stopRecording(); + }, + child: const Padding( + padding: + EdgeInsets.only( + bottom: + 8.0), + child: + LottieAnimation( + lottieJson: + audioJson1, + showRepeat: true, + width: 54, + height: 54, + ), + )) + : const SizedBox.shrink(); + }), + const SizedBox( + width: 5, ), + ], + ), + ), + emojiLayout(), + ], + ) + : userNoLonger(), ); }), ), @@ -403,6 +403,7 @@ class ChatView extends GetView { onChanged: (text) { controller.isTyping(text); }, + style: const TextStyle(fontWeight: FontWeight.w400), keyboardType: TextInputType.multiline, minLines: 1, maxLines: 5, @@ -490,8 +491,8 @@ class ChatView extends GetView { } Widget userNoLonger() { - return Column( - children: const [ + return const Column( + children: [ Divider( height: 1, thickness: 0.29, @@ -576,10 +577,10 @@ class ChatView extends GetView { ? SwipeTo( key: ValueKey(chatList[index].messageId), onRightSwipe: () { - if (!chatList[index].isMessageRecalled && + if (!chatList[index].isMessageRecalled.value && !chatList[index].isMessageDeleted && chatList[index] - .messageStatus + .messageStatus.value .checkNull() .toString() != "N") { @@ -629,7 +630,7 @@ class ChatView extends GetView { child: Obx(() { return Container( key: Key(chatList[index].messageId), - color: chatList[index].isSelected + color: chatList[index].isSelected.value ? chatReplyContainerColor : Colors.transparent, margin: const EdgeInsets.only( @@ -746,75 +747,6 @@ class ChatView extends GetView { ); } - Widget chatGroupedListView(List chatList) { - return GroupedListView( - elements: chatList, - groupBy: (element) => element['group'], - groupSeparatorBuilder: (String groupByValue) => Text(groupByValue), - itemBuilder: (context, dynamic element) => Text(element['name']), - // itemComparator: (item1, item2) => item1['name'].compareTo(item2['name']), // optional - useStickyGroupSeparators: true, - // optional - floatingHeader: true, - // optional - order: GroupedListOrder.ASC, // optional - ); - } - - /*handleMediaUploadDownload( - int mediaDownloadStatus, ChatMessageModel chatList) { - switch (chatList.isMessageSentByMe - ? chatList.mediaChatMessage?.mediaUploadStatus - : mediaDownloadStatus) { - case Constants.mediaDownloaded: - case Constants.mediaUploaded: - if (chatList.messageType.toUpperCase() == 'VIDEO') { - if (controller.checkFile( - chatList.mediaChatMessage!.mediaLocalStoragePath) && - (chatList.mediaChatMessage!.mediaDownloadStatus == - Constants.mediaDownloaded || - chatList.mediaChatMessage!.mediaDownloadStatus == - Constants.mediaUploaded || - chatList.isMessageSentByMe)) { - Get.toNamed(Routes.videoPlay, arguments: { - "filePath": chatList.mediaChatMessage!.mediaLocalStoragePath, - }); - } - } - if (chatList.messageType.toUpperCase() == 'AUDIO') { - if (controller.checkFile( - chatList.mediaChatMessage!.mediaLocalStoragePath) && - (chatList.mediaChatMessage!.mediaDownloadStatus == - Constants.mediaDownloaded || - chatList.mediaChatMessage!.mediaDownloadStatus == - Constants.mediaUploaded || - chatList.isMessageSentByMe)) { - debugPrint("audio click1"); - controller.playAudio(chatList, chatList.mediaChatMessage!.mediaLocalStoragePath); - } else { - debugPrint("condition failed"); - } - } - break; - case Constants.mediaDownloadedNotAvailable: - case Constants.mediaNotDownloaded: - //download - debugPrint("Download"); - debugPrint(chatList.messageId); - chatList.mediaChatMessage!.mediaDownloadStatus = - Constants.mediaDownloading; - controller.downloadMedia(chatList.messageId); - break; - case Constants.mediaUploadedNotAvailable: - //upload - break; - case Constants.mediaNotUploaded: - case Constants.mediaDownloading: - case Constants.mediaUploading: - //return uploadingView(chatList.messageType); - // break; - } - }*/ selectedAppBar() { return AppBar( diff --git a/lib/app/modules/chat/views/contact_list_view.dart b/lib/app/modules/chat/views/contact_list_view.dart index b020a6b8..c113ce2c 100644 --- a/lib/app/modules/chat/views/contact_list_view.dart +++ b/lib/app/modules/chat/views/contact_list_view.dart @@ -3,8 +3,8 @@ import 'package:flutter_svg/svg.dart'; import 'package:get/get.dart'; import 'package:mirror_fly_demo/app/common/constants.dart'; import 'package:mirror_fly_demo/app/data/helper.dart'; -import 'package:mirror_fly_demo/app/data/session_management.dart'; import 'package:mirror_fly_demo/app/modules/chat/controllers/contact_controller.dart'; +import 'package:mirrorfly_plugin/mirrorfly.dart'; import '../../../common/widgets.dart'; import '../../../routes/app_pages.dart'; @@ -112,7 +112,7 @@ class ContactListView extends GetView { controller.refreshContacts(true); }, ), - showAsAction: (!SessionManagement.isTrailLicence() && !controller.progressSpinner.value) ? ShowAsAction.never : ShowAsAction.gone, + showAsAction: (!Mirrorfly.isTrialLicence && !controller.progressSpinner.value) ? ShowAsAction.never : ShowAsAction.gone, keyValue: 'Refresh', onItemClick: () { // Get.back(); diff --git a/lib/app/modules/chat/views/starred_message_header.dart b/lib/app/modules/chat/views/starred_message_header.dart index 94eb25ff..1c7d83ed 100644 --- a/lib/app/modules/chat/views/starred_message_header.dart +++ b/lib/app/modules/chat/views/starred_message_header.dart @@ -1,12 +1,12 @@ -import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:mirror_fly_demo/app/data/helper.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; +import 'package:mirrorfly_plugin/mirrorflychat.dart'; import '../../../common/constants.dart'; import '../../../common/widgets.dart'; +import '../../../model/chat_message_model.dart'; import '../../starred_messages/controllers/starred_messages_controller.dart'; /* @@ -43,8 +43,9 @@ class StarredMessageHeader extends StatelessWidget { } Future getProfile() async { - var value = await Mirrorfly.getProfileDetails(chatList.chatUserJid, true); - return Profile.fromJson(json.decode(value.toString())); + /*var value = await Mirrorfly.getProfileDetails(chatList.chatUserJid); + return Profile.fromJson(json.decode(value.toString()));*/ + return await getProfileDetails(chatList.chatUserJid); } getHeader(ChatMessageModel chatList, BuildContext context) { diff --git a/lib/app/modules/dashboard/controllers/dashboard_controller.dart b/lib/app/modules/dashboard/controllers/dashboard_controller.dart index eb6949d2..10ac3f52 100644 --- a/lib/app/modules/dashboard/controllers/dashboard_controller.dart +++ b/lib/app/modules/dashboard/controllers/dashboard_controller.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart'; import 'package:flutter_libphonenumber/flutter_libphonenumber.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; +import 'package:mirrorfly_plugin/mirrorflychat.dart'; import 'package:get/get.dart'; import 'package:mirror_fly_demo/app/common/constants.dart'; import 'package:mirror_fly_demo/app/data/helper.dart'; @@ -16,6 +16,7 @@ import 'package:permission_handler/permission_handler.dart'; import '../../../common/de_bouncer.dart'; import '../../../data/apputils.dart'; import '../../../data/permissions.dart'; +import '../../../model/chat_message_model.dart'; import '../../../routes/app_pages.dart'; class DashboardController extends FullLifeCycleController @@ -135,14 +136,14 @@ class DashboardController extends FullLifeCycleController }); } - toChatPage(String jid) async { + toChatPage(String jid) { if (jid.isNotEmpty) { // Helper.progressLoading(); - await Mirrorfly.getProfileDetails(jid, false).then((value) { - if (value != null) { + getProfileDetails(jid).then((value) { + if (value.jid != null) { Helper.hideLoading(); // debugPrint("Dashboard Profile===>$value"); - var profile = profiledata(value.toString()); + var profile = value;//profiledata(value.toString()); Get.toNamed(Routes.chat, arguments: profile); } }); @@ -390,16 +391,16 @@ class DashboardController extends FullLifeCycleController const Duration(milliseconds: 100), () => Get.toNamed(Routes.settings)); } - chatInfo() async { + chatInfo() { var chatIndex = recentChats.indexWhere((element) => selectedChats.first == element.jid); //selectedChatsPosition[index]; var item = recentChats[chatIndex]; Helper.progressLoading(); clearAllChatSelection(); - await Mirrorfly.getProfileDetails(item.jid.checkNull(), false).then((value) { - if (value != null) { + getProfileDetails(item.jid.checkNull()).then((value) { + if (value.jid != null) { Helper.hideLoading(); - var profile = profiledata(value.toString()); + var profile = value;//profiledata(value.toString()); if (item.isGroup!) { Future.delayed(const Duration(milliseconds: 100), () => Get.toNamed(Routes.groupInfo, arguments: profile)); @@ -805,7 +806,7 @@ class DashboardController extends FullLifeCycleController }, child: const Text("No")), TextButton( - onPressed: () async { + onPressed: () { Get.back(); Mirrorfly.deleteRecentChat(selectedChats[index]).then((value) { clearAllChatSelection(); @@ -864,7 +865,7 @@ class DashboardController extends FullLifeCycleController debugPrint("Message Status Update index of search $index"); if (!index.isNegative) { // updateRecentChat(chatMessageModel.chatUserJid); - recentChats[index].lastMessageStatus = chatMessageModel.messageStatus; + recentChats[index].lastMessageStatus = chatMessageModel.messageStatus.value; recentChats.refresh(); } } @@ -950,13 +951,13 @@ class DashboardController extends FullLifeCycleController RxBool clearVisible = false.obs; final _mainuserList = []; var userlistScrollController = ScrollController(); - var scrollable = SessionManagement.isTrailLicence().obs; + var scrollable = Mirrorfly.isTrialLicence.obs; var isPageLoading = false.obs; final _userList = [].obs; set userList(List value) => _userList.value = value; - List get userList => _userList.value; + List get userList => _userList; onChange(String inputValue) { if (search.text.trim().isNotEmpty) { @@ -1001,7 +1002,7 @@ class DashboardController extends FullLifeCycleController Future filterUserList() async { if (await AppUtils.isNetConnected()) { searching = true; - var future = (SessionManagement.isTrailLicence()) + var future = (Mirrorfly.isTrialLicence) ? Mirrorfly.getUserList(pageNum, search.text.trim().toString()) : Mirrorfly.getRegisteredUsers(true); future.then((value) { @@ -1009,11 +1010,11 @@ class DashboardController extends FullLifeCycleController if (value != null) { var list = userListFromJson(value); if (list.data != null) { - if (SessionManagement.isTrailLicence()) { + if (Mirrorfly.isTrialLicence) { scrollable(list.data!.length == 20); list.data!.removeWhere((element){ - debugPrint("filter chat list--> ${!filteredRecentChatList.value.indexWhere((recentChatItem) => recentChatItem.jid == element.jid.checkNull()).isNegative}"); + debugPrint("filter chat list--> ${!filteredRecentChatList.indexWhere((recentChatItem) => recentChatItem.jid == element.jid.checkNull()).isNegative}"); return !filteredRecentChatList.indexWhere((recentChatItem) => recentChatItem.jid == element.jid.checkNull()).isNegative; }); _userList(list.data); } else { @@ -1092,7 +1093,7 @@ class DashboardController extends FullLifeCycleController var value = await getProfileDetails(jid); //Mirrorfly.getProfileLocal(jid, false); var value2 = await Mirrorfly.getMessageOfId(mid); - if (value != null && value2 != null) { + if (value.jid != null && value2 != null) { var data = value; //profileDataFromJson(value); var data2 = sendMessageModelFromJson(value2); var map = {}; //{0,searchMessageItem}; @@ -1134,7 +1135,7 @@ class DashboardController extends FullLifeCycleController _mainuserList.addAll(list.data!); } scrollable(list.data!.length == 20); - _userList.value.addAll(list.data!); + _userList.addAll(list.data!); _userList.refresh(); } else { scrollable(false); @@ -1169,7 +1170,7 @@ class DashboardController extends FullLifeCycleController } } - Future updateProfileSearch(String jid) async { + void updateProfileSearch(String jid) { debugPrint("updateProfileSearch jid $jid"); if (jid.isNotEmpty) { var userListIndex = _userList.indexWhere((element) => element.jid == jid); @@ -1232,7 +1233,7 @@ class DashboardController extends FullLifeCycleController } Future gotoContacts() async { - if (SessionManagement.isTrailLicence()) { + if (Mirrorfly.isTrialLicence) { Get.toNamed(Routes.contacts, arguments: {"forward": false, "group": false, "groupJid": ""}); } else { diff --git a/lib/app/modules/dashboard/views/dashboard_view.dart b/lib/app/modules/dashboard/views/dashboard_view.dart index 8e4f2166..e85c50de 100644 --- a/lib/app/modules/dashboard/views/dashboard_view.dart +++ b/lib/app/modules/dashboard/views/dashboard_view.dart @@ -376,7 +376,7 @@ class DashboardView extends GetView { Obx(() { return Visibility( visible: !controller.recentChatLoding.value && - controller.recentChats.isEmpty, + controller.recentChats.isEmpty && controller.archivedChats.isEmpty, child: emptyChat(context)); }), Column( @@ -686,11 +686,11 @@ class DashboardView extends GetView { Padding( padding: const EdgeInsets.only(right: 8.0), child: getMessageIndicator( - item.messageStatus.checkNull(), + item.messageStatus.value.checkNull(), item.isMessageSentByMe.checkNull(), - item.messageType.checkNull(),item.isMessageRecalled), + item.messageType.checkNull(),item.isMessageRecalled.value), ), - item.isMessageRecalled + item.isMessageRecalled.value ? const SizedBox.shrink() : forMessageTypeIcon(item.messageType,item.mediaChatMessage), SizedBox( width: forMessageTypeString( diff --git a/lib/app/modules/dashboard/widgets.dart b/lib/app/modules/dashboard/widgets.dart index 366859a0..c37441a5 100644 --- a/lib/app/modules/dashboard/widgets.dart +++ b/lib/app/modules/dashboard/widgets.dart @@ -6,9 +6,10 @@ import 'package:mirror_fly_demo/app/data/helper.dart'; import '../../common/constants.dart'; import '../../common/widgets.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; +import 'package:mirrorfly_plugin/mirrorflychat.dart'; import '../../data/session_management.dart'; +import '../../model/chat_message_model.dart'; import '../chat/chat_widgets.dart'; Widget searchHeader(String? type, String count, BuildContext context) { @@ -130,7 +131,7 @@ class RecentChatItem extends StatelessWidget { : buildProfileStatus() : Expanded( child: typingUserid.isEmpty - ? item.lastMessageType != null ? buildLastMessageItem() : const SizedBox.shrink() + ? item.lastMessageType != null ? buildLastMessageItem() : const SizedBox(height: 15,) : buildTypingUser(), ), ], @@ -250,13 +251,13 @@ class RecentChatItem extends StatelessWidget { return Positioned( right: 0, child: CircleAvatar( - radius: 8, + radius: 9, child: Text( returnFormattedCount(item.unreadMessageCount!) != "0" ? returnFormattedCount(item.unreadMessageCount!) : "", style: const TextStyle( - fontSize: 9, color: Colors.white, fontFamily: 'sf_ui'), + fontSize: 8, color: Colors.white, fontFamily: 'sf_ui'), ), )); } @@ -268,7 +269,7 @@ class RecentChatItem extends StatelessWidget { Visibility buildArchivedTextVisibility() { return Visibility( - visible: item.isChatArchived! && archiveVisible, + visible: item.isChatArchived! && archiveVisible && !isForwardMessage, child: Container( padding: const EdgeInsets.symmetric(horizontal: 2.0), decoration: BoxDecoration( @@ -288,7 +289,7 @@ class RecentChatItem extends StatelessWidget { Visibility buildMuteIconVisibility() { return Visibility( - visible: !archiveEnabled && item.isMuted!, + visible: !archiveEnabled && item.isMuted! && !isForwardMessage, child: SvgPicture.asset( mute, width: 13, @@ -298,7 +299,7 @@ class RecentChatItem extends StatelessWidget { Visibility buildArchivedIconVisibility() { return Visibility( - visible: !item.isChatArchived! && item.isChatPinned!, + visible: !item.isChatArchived! && item.isChatPinned! && !isForwardMessage, child: SvgPicture.asset( pin, width: 18, @@ -333,19 +334,6 @@ class RecentChatItem extends StatelessWidget { var chat = data.data!; return Row( children: [ - chat.isMessageRecalled - ? const SizedBox.shrink() : forMessageTypeIcon( - chat.messageType, chat.mediaChatMessage), - SizedBox( - width: chat.isMessageRecalled - ? 0.0 - : forMessageTypeString(chat.messageType, - content: - chat.messageTextContent.checkNull()) != - null - ? 3.0 - : 0.0, - ), (item.isGroup.checkNull() && !chat.isMessageSentByMe.checkNull() && (chat.messageType != Constants.mNotification || @@ -357,10 +345,23 @@ class RecentChatItem extends StatelessWidget { overflow: TextOverflow.ellipsis, ) : const SizedBox.shrink(), + chat.isMessageRecalled.value + ? const SizedBox.shrink() : forMessageTypeIcon( + chat.messageType, chat.mediaChatMessage), + SizedBox( + width: chat.isMessageRecalled.value + ? 0.0 + : forMessageTypeString(chat.messageType, + content: + chat.messageTextContent.checkNull()) != + null + ? 3.0 + : 0.0, + ), Expanded( child: spanTxt.isEmpty ? Text( - chat.isMessageRecalled + chat.isMessageRecalled.value ? setRecalledMessageText( chat.isMessageSentByMe) : forMessageTypeString(chat.messageType, @@ -373,7 +374,7 @@ class RecentChatItem extends StatelessWidget { overflow: TextOverflow.ellipsis, ) : spannableText( - chat.isMessageRecalled + chat.isMessageRecalled.value ? setRecalledMessageText( chat.isMessageSentByMe) : forMessageTypeString( diff --git a/lib/app/modules/delete_account/controllers/delete_account_controller.dart b/lib/app/modules/delete_account/controllers/delete_account_controller.dart index 1f4ab7df..f6c8b8c1 100644 --- a/lib/app/modules/delete_account/controllers/delete_account_controller.dart +++ b/lib/app/modules/delete_account/controllers/delete_account_controller.dart @@ -29,13 +29,13 @@ class DeleteAccountController extends GetxController { ]); return; } - mirrorFlyLog("SessionManagement.getMobileNumber()", SessionManagement.getMobileNumber().toString()); + mirrorFlyLog("SessionManagement.getMobileNumber()", SessionManagement.getMobileNumber().toString().trim()); mirrorFlyLog("SessionManagement.getCountryCode()", SessionManagement.getCountryCode().toString()); - mirrorFlyLog("SessionManagement.isTrailLicence()", SessionManagement.isTrailLicence().toString()); + mirrorFlyLog("Mirrorfly.isTrialLicence", Mirrorfly.isTrialLicence.toString()); mirrorFlyLog("countryCode", countryCode.toString()); var mobileNumberWithCountryCode = '${countryCode?.replaceAll('+', '')}${mobileNumber.text.trim()}'; mirrorFlyLog("mobileNumberWithCountryCode", mobileNumberWithCountryCode); - if(SessionManagement.isTrailLicence()) { + if(Mirrorfly.isTrialLicence) { if ((mobileNumber.text.trim() != SessionManagement.getMobileNumber() && mobileNumberWithCountryCode != SessionManagement.getMobileNumber()) || SessionManagement.getCountryCode()?.replaceAll('+', '') != countryCode?.replaceAll('+', '')) { diff --git a/lib/app/modules/delete_account/views/delete_account_view.dart b/lib/app/modules/delete_account/views/delete_account_view.dart index e38e196c..37e83584 100644 --- a/lib/app/modules/delete_account/views/delete_account_view.dart +++ b/lib/app/modules/delete_account/views/delete_account_view.dart @@ -38,24 +38,24 @@ class DeleteAccountView extends GetView { ], ), const SizedBox(height: 10,), - Row( - children: const [ + const Row( + children: [ SizedBox(width: 30,), Text(Constants.bulletPoint, style: TextStyle(fontSize: 12),), Text("Delete your account from MirrorFly",style: TextStyle(color: textColor),), ], ), const SizedBox(height: 10,), - Row( - children: const [ + const Row( + children: [ SizedBox(width: 30,), Text(Constants.bulletPoint, style: TextStyle(fontSize: 12),), Text("Erase your message history",style: TextStyle(color: textColor),), ], ), const SizedBox(height: 10,), - Row( - children: const [ + const Row( + children: [ SizedBox(width: 30,), Text(Constants.bulletPoint, style: TextStyle(fontSize: 12),), Text("Delete you from all of your MirrorFly groups",style: TextStyle(color: textColor),), diff --git a/lib/app/modules/gallery_picker/src/core/functions.dart b/lib/app/modules/gallery_picker/src/core/functions.dart index 69dd991b..88e610bc 100644 --- a/lib/app/modules/gallery_picker/src/core/functions.dart +++ b/lib/app/modules/gallery_picker/src/core/functions.dart @@ -46,7 +46,7 @@ class GalleryFunctions { animationController: animationController, builder: builder), )); - Overlay.of(context)?.insert(entry); + Overlay.of(context).insert(entry); animationController.animateTo(1); return FeatureController( completer, @@ -64,10 +64,10 @@ class GalleryFunctions { static getPermission(setState, GalleryMediaPickerController provider) async { /// request for device permission - var result = await PhotoManager.requestPermissionExtend( + /*var result = await PhotoManager.requestPermissionExtend( requestOption: const PermissionRequestOption( iosAccessLevel: IosAccessLevel.readWrite)); - if (result.isAuth) { + if (result.isAuth) {*/ /// load "recent" album provider.setAssetCount(); PhotoManager.startChangeNotify(); @@ -78,11 +78,11 @@ class GalleryFunctions { if (provider.pathList.isEmpty) { _refreshPathList(setState, provider); } - } else { + /*} else { /// if result is fail, you can call `PhotoManager.openSetting();` /// to open android/ios application's setting to get permission PhotoManager.openSetting(); - } + }*/ } static _refreshPathList(setState, GalleryMediaPickerController provider) { diff --git a/lib/app/modules/gallery_picker/src/presentation/pages/gallery_media_picker.dart b/lib/app/modules/gallery_picker/src/presentation/pages/gallery_media_picker.dart index 2df2346e..87270673 100644 --- a/lib/app/modules/gallery_picker/src/presentation/pages/gallery_media_picker.dart +++ b/lib/app/modules/gallery_picker/src/presentation/pages/gallery_media_picker.dart @@ -246,7 +246,7 @@ class _GalleryMediaPickerState extends State { widget.pathList!(provider.pickedFile); }); }else{ - toToast("File Size should not exceed ${asset.typeInt == 1 ? 10 : 20} MB"); + toToast("File Size should not exceed ${asset.typeInt == 1 ? Constants.maxImageFileSize : Constants.maxVideoFileSize} MB"); } }, ), diff --git a/lib/app/modules/gallery_picker/views/gallery_picker_view.dart b/lib/app/modules/gallery_picker/views/gallery_picker_view.dart index b4a92624..85d2f0aa 100644 --- a/lib/app/modules/gallery_picker/views/gallery_picker_view.dart +++ b/lib/app/modules/gallery_picker/views/gallery_picker_view.dart @@ -73,7 +73,8 @@ class GalleryPickerView extends GetView { "filePath": controller.pickedFile, "userName": controller.userName, 'profile': controller.profile, - 'caption': controller.textMessage + 'caption': controller.textMessage, + 'from': 'gallery_pick' })?.then((value) { value != null ? Get.back() : null; diff --git a/lib/app/modules/group/controllers/group_creation_controller.dart b/lib/app/modules/group/controllers/group_creation_controller.dart index 19baf0aa..6b84b0f7 100644 --- a/lib/app/modules/group/controllers/group_creation_controller.dart +++ b/lib/app/modules/group/controllers/group_creation_controller.dart @@ -1,7 +1,6 @@ import 'dart:io'; import 'package:file_picker/file_picker.dart'; -import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:image_picker/image_picker.dart'; diff --git a/lib/app/modules/group/controllers/group_info_controller.dart b/lib/app/modules/group/controllers/group_info_controller.dart index cd5e18ca..e992be01 100644 --- a/lib/app/modules/group/controllers/group_info_controller.dart +++ b/lib/app/modules/group/controllers/group_info_controller.dart @@ -1,4 +1,3 @@ -import 'dart:convert'; import 'dart:io'; import 'package:file_picker/file_picker.dart'; @@ -59,9 +58,9 @@ class GroupInfoController extends GetxController { if (groupJid.checkNull().isNotEmpty) { if (profile.jid.checkNull() == groupJid.toString()) { mirrorFlyLog("group info", groupJid.toString()); - Mirrorfly.getProfileDetails(profile.jid.checkNull(), false).then((value) { - if (value != null) { - var member = Profile.fromJson(json.decode(value.toString())); + getProfileDetails(profile.jid.checkNull()).then((value) { + if (value.jid != null) { + var member = value;//Profile.fromJson(json.decode(value.toString())); profile_(member); _mute(profile.isMuted!); nameController.text=profile.nickName.checkNull(); @@ -92,8 +91,13 @@ class GroupInfoController extends GetxController { var index = groupMembers.indexWhere((element) => element.jid == userJid); if(!index.isNegative) { debugPrint('user left ${groupMembers[index].name}'); + var isAdmin = groupMembers[index].isGroupAdmin; groupMembers.removeAt(index); - groupMembers.refresh(); + if(isAdmin.checkNull()){ + getGroupMembers(false); + }else { + groupMembers.refresh(); + } } } } diff --git a/lib/app/modules/login/controllers/login_controller.dart b/lib/app/modules/login/controllers/login_controller.dart index d9000b26..de414f4e 100644 --- a/lib/app/modules/login/controllers/login_controller.dart +++ b/lib/app/modules/login/controllers/login_controller.dart @@ -1,7 +1,5 @@ import 'dart:async'; -import 'package:firebase_auth/firebase_auth.dart'; -import 'package:firebase_messaging/firebase_messaging.dart'; // import 'package:firebase_messaging/firebase_messaging.dart'; // import 'package:firebase_messaging/firebase_messaging.dart'; @@ -18,7 +16,7 @@ import 'package:mirrorfly_plugin/mirrorfly.dart'; import '../../../routes/app_pages.dart'; class LoginController extends GetxController { - final FirebaseAuth _auth = FirebaseAuth.instance; + // final FirebaseAuth _auth = FirebaseAuth.instance; var india = CountryData(name: "India", dialCode: "+91", code: "IN"); var selectedCountry = CountryData(name: "India", dialCode: "+91", code: "IN").obs; @@ -68,11 +66,11 @@ class LoginController extends GetxController { debugPrint(seconds.value.toString()); } } - @override + /*@override void onReady() { super.onReady(); - Mirrorfly.isTrailLicence().then((value) => SessionManagement.setIsTrailLicence(value.checkNull())); - } + // Mirrorfly.isTrailLicence().then((value) => SessionManagement.setIsTrailLicence(value.checkNull())); + }*/ @override void dispose() { @@ -109,7 +107,7 @@ class LoginController extends GetxController { }); } - Future phoneAuth() async { + /*Future phoneAuth() async { if(await AppUtils.isNetConnected()) { showLoading(); if (kIsWeb) { @@ -163,14 +161,14 @@ class LoginController extends GetxController { }else{ toToast(Constants.noInternetConnection); } - } + }*/ resend(){ timeout(false); - phoneAuth(); + // phoneAuth(); } - Future verifyOTP() async { + /*Future verifyOTP() async { if (await AppUtils.isNetConnected()) { if (smsCode.length == 6) { PhoneAuthCredential credential = PhoneAuthProvider.credential( @@ -185,8 +183,8 @@ class LoginController extends GetxController { } else { toToast(Constants.noInternetConnection); } - } - + }*/ +/* _onVerificationCompleted(PhoneAuthCredential credential) async { timeout(true); mirrorFlyLog( @@ -201,7 +199,7 @@ class LoginController extends GetxController { // need otp so i can autofill in a text box if (credential.smsCode != null) { otpController.set(credential.smsCode!.split("")); - verifyOTP(); + verifyOTP(); } } @@ -209,7 +207,7 @@ class LoginController extends GetxController { showLoading(); try { await _auth.signInWithCredential(credential).then((value) { - if(SessionManagement.isTrailLicence()) { + if(Mirrorfly.isTrialLicence) { sendTokenToServer(); // for Mirrorfly user list purpose verify the user }else{ validateDeviceToken(''); @@ -227,9 +225,9 @@ class LoginController extends GetxController { toToast("Enter Valid Otp"); hideLoading(); } - } + }*/ - sendTokenToServer() async { + /*sendTokenToServer() async { var mUser = FirebaseAuth.instance.currentUser; if (mUser != null) { await mUser.getIdToken(true).then((value) { @@ -285,7 +283,7 @@ class LoginController extends GetxController { toToast(Constants.noInternetConnection); } // navigateToUserRegisterMethod(deviceToken, firebaseToken); - } + }*/ navigateToUserRegisterMethod(String? deviceToken, String? firebaseToken) { //OTP validated successfully @@ -298,36 +296,51 @@ class LoginController extends GetxController { registerAccount() async { if (await AppUtils.isNetConnected()) { - showLoading(); - Mirrorfly.registerUser( - countryCode!.replaceAll('+', '') + mobileNumber.text, token:SessionManagement.getToken().checkNull()) - .then((value) { - if (value.contains("data")) { - var userData = registerModelFromJson(value); //message - SessionManagement.setLogin(userData.data!.username!.isNotEmpty); - SessionManagement.setUser(userData.data!); - // Mirrorfly.setNotificationSound(true); - // SessionManagement.setNotificationSound(true); - // userData.data. - enableArchive(); - Mirrorfly.setRegionCode(regionCode ?? 'IN');///if its not set then error comes in contact sync delete from phonebook. - SessionManagement.setCountryCode((countryCode ?? "").replaceAll('+', '')); - setUserJID(userData.data!.username!); - } - }).catchError((error) { - debugPrint("issue===> $error"); - debugPrint(error.message); - hideLoading(); - if(error.code == 403){ - Get.offAllNamed(Routes.adminBlocked); - }else{ - toToast(error.message); - } - }); - } else { - toToast(Constants.noInternetConnection); - } + if(mobileNumber.text.length < 5){ + toToast("Mobile number too short"); + return; + } + if(mobileNumber.text.length < 10){ + toToast("Please enter valid mobile number"); + return; + } + // if(mobileNumber.text.length > 9) { + showLoading(); + Mirrorfly.registerUser( + countryCode!.replaceAll('+', '') + mobileNumber.text, token: SessionManagement.getToken().checkNull()) + .then((value) { + if (value.contains("data")) { + var userData = registerModelFromJson(value); //message + SessionManagement.setLogin(userData.data!.username!.isNotEmpty); + SessionManagement.setUser(userData.data!); + // Mirrorfly.setNotificationSound(true); + // SessionManagement.setNotificationSound(true); + // userData.data. + enableArchive(); + Mirrorfly.setRegionCode(regionCode ?? 'IN'); + + ///if its not set then error comes in contact sync delete from phonebook. + SessionManagement.setCountryCode((countryCode ?? "").replaceAll('+', '')); + setUserJID(userData.data!.username!); + } + }).catchError((error) { + debugPrint("issue===> $error"); + debugPrint(error.message); + hideLoading(); + if (error.code == 403) { + Get.offAllNamed(Routes.adminBlocked); + } else { + toToast(error.message); + } + }); + }else{ + toToast("Mobile Number too short"); + } + // } else { + // toToast(Constants.noInternetConnection); + // } } + void enableArchive() async{ if(await AppUtils.isNetConnected()) { Mirrorfly.enableDisableArchivedSettings(true); diff --git a/lib/app/modules/login/views/country_list_view.dart b/lib/app/modules/login/views/country_list_view.dart index 31ebca6f..3e0c1884 100644 --- a/lib/app/modules/login/views/country_list_view.dart +++ b/lib/app/modules/login/views/country_list_view.dart @@ -46,7 +46,7 @@ class CountryListView extends GetView { ), ], ), - body: ListView.builder( + body: controller.countryList.isNotEmpty ? ListView.builder( itemCount: controller.countryList.length, physics: const AlwaysScrollableScrollPhysics(), itemBuilder: (BuildContext context, int index) { @@ -65,7 +65,7 @@ class CountryListView extends GetView { Get.back(result: item); }, ); - }) + }) : const Center(child: Text("No Country Found"),) ), ); } diff --git a/lib/app/modules/login/views/login_view.dart b/lib/app/modules/login/views/login_view.dart index 73915adf..6f480b66 100644 --- a/lib/app/modules/login/views/login_view.dart +++ b/lib/app/modules/login/views/login_view.dart @@ -100,7 +100,7 @@ class LoginView extends GetView { keyboardType: TextInputType.phone, inputFormatters: [ FilteringTextInputFormatter.digitsOnly, - LengthLimitingTextInputFormatter(10) + LengthLimitingTextInputFormatter(13) ], decoration: const InputDecoration( border: InputBorder.none, diff --git a/lib/app/modules/login/views/otp_view.dart b/lib/app/modules/login/views/otp_view.dart index bdb43def..10ed83b3 100644 --- a/lib/app/modules/login/views/otp_view.dart +++ b/lib/app/modules/login/views/otp_view.dart @@ -106,7 +106,7 @@ class OtpView extends GetView { fontWeight: FontWeight.w500), shape: const StadiumBorder()), onPressed: () { - controller.verifyOTP(); + // controller.verifyOTP(); }, child: const Text( 'Verify OTP', diff --git a/lib/app/modules/media_preview/controllers/media_preview_controller.dart b/lib/app/modules/media_preview/controllers/media_preview_controller.dart index 96b95396..e4a032c6 100644 --- a/lib/app/modules/media_preview/controllers/media_preview_controller.dart +++ b/lib/app/modules/media_preview/controllers/media_preview_controller.dart @@ -11,6 +11,7 @@ import '../../../common/constants.dart'; import '../../../data/helper.dart'; import '../../../routes/app_pages.dart'; import '../../chat/controllers/chat_controller.dart'; +import '../../gallery_picker/src/data/models/picked_asset_model.dart'; class MediaPreviewController extends FullLifeCycleController with FullLifeCycleMixin { @@ -19,10 +20,11 @@ class MediaPreviewController extends FullLifeCycleController with FullLifeCycleM TextEditingController caption = TextEditingController(); - var filePath = [].obs; + var filePath = [].obs; var captionMessage = [].obs; var textMessage = Get.arguments['caption']; + var from = Get.arguments['from']; var showAdd = Get.arguments['showAdd'] ?? true; var currentPageIndex = 0.obs; var isFocused = false.obs; @@ -81,7 +83,7 @@ class MediaPreviewController extends FullLifeCycleController with FullLifeCycleM } else if (data.type == 'video') { debugPrint("sending video"); var response = await Get.find() - .sendVideoMessage(data.path, captionMessage[i], ""); + .sendVideoMessage(data.path!, captionMessage[i], ""); debugPrint("Preview View ==> $response"); if (response != null) { debugPrint("Video send Success"); diff --git a/lib/app/modules/media_preview/views/media_preview_view.dart b/lib/app/modules/media_preview/views/media_preview_view.dart index e998ab40..c53a46ea 100644 --- a/lib/app/modules/media_preview/views/media_preview_view.dart +++ b/lib/app/modules/media_preview/views/media_preview_view.dart @@ -1,6 +1,6 @@ import 'dart:io'; -import 'package:better_video_player/better_video_player.dart'; +// import 'package:better_video_player/better_video_player.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; @@ -10,6 +10,7 @@ import 'package:mirror_fly_demo/app/data/helper.dart'; import 'package:photo_view/photo_view.dart'; import '../../../common/widgets.dart'; +import '../../../widgets/video_player_widget.dart'; import '../controllers/media_preview_controller.dart'; class MediaPreviewView extends GetView { @@ -137,7 +138,7 @@ class MediaPreviewView extends GetView { if (data.type == 'image') { return Center( child: PhotoView( - imageProvider: FileImage(File(data.path)), + imageProvider: FileImage(File(data.path!)), // Contained = the smallest possible size to fit one dimension of the screen minScale: PhotoViewComputedScale.contained * 1, @@ -165,23 +166,26 @@ class MediaPreviewView extends GetView { /// show video else { - return AspectRatio( - aspectRatio: 16.0 / 9.0, - child: BetterVideoPlayer( - configuration: - const BetterVideoPlayerConfiguration( - looping: false, - autoPlay: false, - allowedScreenSleep: false, - autoPlayWhenResume: false, - ), - controller: - BetterVideoPlayerController(), - dataSource: BetterVideoPlayerDataSource( - BetterVideoPlayerDataSourceType.file, - data.path, - ), - ), + // return AspectRatio( + // aspectRatio: 16.0 / 9.0, + // child: BetterVideoPlayer( + // configuration: + // const BetterVideoPlayerConfiguration( + // looping: false, + // autoPlay: false, + // allowedScreenSleep: false, + // autoPlayWhenResume: false, + // ), + // controller: + // BetterVideoPlayerController(), + // dataSource: BetterVideoPlayerDataSource( + // BetterVideoPlayerDataSourceType.file, + // data.path!, + // ), + // ), + // ); + return VideoPlayerWidget( + videoPath: data.path ?? "", videoTitle: data.title ?? "Video", ); } }) @@ -344,7 +348,7 @@ class MediaPreviewView extends GetView { .symmetric(horizontal: 1), child: Image.memory(controller .filePath[index] - .thumbnail), + .thumbnail!), ), ); }), diff --git a/lib/app/modules/message_info/controllers/message_info_controller.dart b/lib/app/modules/message_info/controllers/message_info_controller.dart index 306fbb0e..b36e3117 100644 --- a/lib/app/modules/message_info/controllers/message_info_controller.dart +++ b/lib/app/modules/message_info/controllers/message_info_controller.dart @@ -5,13 +5,13 @@ import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:intl/intl.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; +import 'package:mirrorfly_plugin/mirrorflychat.dart'; import 'package:mirror_fly_demo/app/modules/chat/controllers/chat_controller.dart'; -import 'package:permission_handler/permission_handler.dart'; import '../../../common/constants.dart'; import '../../../data/helper.dart'; import '../../../data/permissions.dart'; +import '../../../model/chat_message_model.dart'; class MessageInfoController extends GetxController { var chatController = Get.find(); @@ -71,21 +71,10 @@ class MessageInfoController extends GetxController { File(mediaLocalStoragePath).existsSync(); } - Future askStoragePermission() async { - final permission = await AppPermission.getStoragePermission(); - switch (permission) { - case PermissionStatus.granted: - return true; - case PermissionStatus.permanentlyDenied: - return false; - default: - debugPrint("Permission default"); - return false; - } - } downloadMedia(String messageId) async { - if (await askStoragePermission()) { + var permission = await AppPermission.getStoragePermission(); + if (permission) { Mirrorfly.downloadMedia(messageId); } } @@ -159,26 +148,15 @@ class MessageInfoController extends GetxController { var statusCount = 0.obs; String chatDate(BuildContext cxt,DeliveredParticipantList item) => getChatTime(cxt, int.parse(item.time.checkNull())); getMessageStatus(String messageId) async { - // statusCount(await Mirrorfly.getGroupMessageStatusCount(messageId)); var delivered = await Mirrorfly.getGroupMessageDeliveredToList(messageId, jid); mirrorFlyLog("deliveredResp", delivered); - // var deliveredResp = json.decode(delivered); - // mirrorFlyLog("deliveredResp.deliveredParticipantList", "${deliveredResp["deliveredParticipantList"]}"); - // messageDeliveredList(messageDeliveredStatusFromJson(deliveredResp["deliveredParticipantList"].toString())); - // deliveredStatusCount(deliveredResp["deliveredCount"]); - // deliveredTotalCount(deliveredResp["totalParticipatCount"]); var item = MessageDeliveredStatus.fromJson(json.decode(delivered), "delivered"); statusCount(item.totalParticipatCount!); messageDeliveredList(item.participantList); var read = await Mirrorfly.getGroupMessageReadByList(messageId, jid); - // mirrorFlyLog("readResp", read); - // var readResp = json.decode(read); - // debugPrint("readResp.seenParticipantList ${readResp["seenParticipantList"]}"); - // messageReadList(messageDeliveredStatusFromJson(readResp["seenParticipantList"].toString())); - // participantStatusCount(readResp["seenCount"]); - // participantTotalCount(readResp["totalParticipatCount"]); + mirrorFlyLog("readResp", read); var readItem = MessageDeliveredStatus.fromJson(json.decode(read), "read"); messageReadList(readItem.participantList); } diff --git a/lib/app/modules/profile/controllers/profile_controller.dart b/lib/app/modules/profile/controllers/profile_controller.dart index 7c0112e7..9e356028 100644 --- a/lib/app/modules/profile/controllers/profile_controller.dart +++ b/lib/app/modules/profile/controllers/profile_controller.dart @@ -4,13 +4,13 @@ import 'dart:io'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_libphonenumber/flutter_libphonenumber.dart'; import 'package:get/get.dart'; import 'package:image_picker/image_picker.dart'; import 'package:mirror_fly_demo/app/common/constants.dart'; import 'package:mirror_fly_demo/app/data/session_management.dart'; import 'package:mirror_fly_demo/app/data/helper.dart'; import 'package:mirror_fly_demo/app/routes/app_pages.dart'; -import 'package:permission_handler/permission_handler.dart'; import '../../../common/crop_image.dart'; import 'package:mirrorfly_plugin/mirrorfly.dart'; @@ -32,11 +32,12 @@ class ProfileController extends GetxController { var changed = false.obs; dynamic imageBytes; - var from = Routes.login.obs; + var from = Get.previousRoute;//Routes.login.obs; var name = "".obs; bool get emailEditAccess => true;//Get.previousRoute!=Routes.settings; + RxBool mobileEditAccess = false.obs;//Get.previousRoute!=Routes.settings; var userNameFocus= FocusNode(); var emailFocus= FocusNode(); @@ -46,14 +47,14 @@ class ProfileController extends GetxController { userImgUrl.value = SessionManagement.getUserImage() ?? ""; mirrorFlyLog("auth : ", SessionManagement.getAuthToken().toString()); if (Get.arguments != null) { - from(Get.arguments["from"]); - if (from.value == Routes.login) { + // from(Get.arguments["from"]); + if (from == Routes.login) { profileMobile.text = Get.arguments['mobile'] ?? ""; } } else { profileMobile.text = ""; } - if (from.value == Routes.login) { + if (from == Routes.login) { if(await AppUtils.isNetConnected()) { getProfile(); }else{ @@ -64,24 +65,14 @@ class ProfileController extends GetxController { getProfile(); } //profileStatus.value="I'm Mirror fly user"; - await askStoragePermission(); + // await askStoragePermission(); + await AppPermission.getStoragePermission(); } - Future askStoragePermission() async { - final permission = await AppPermission.getStoragePermission(); - switch (permission) { - case PermissionStatus.granted: - return true; - case PermissionStatus.permanentlyDenied: - return false; - default: - debugPrint("Permission default"); - return false; - } - } Future save({bool frmImage=false}) async { - if (await askStoragePermission()) { + var permission = await AppPermission.getStoragePermission(); + if (permission) { if (profileName.text .trim() .isEmpty) { @@ -107,11 +98,12 @@ class ProfileController extends GetxController { } else { if (await AppUtils.isNetConnected()) { debugPrint("profile update"); + var unformatted = profileMobile.text.replaceAll(" ", "").replaceAll("+", ""); Mirrorfly .updateMyProfile( profileName.text.toString(), profileEmail.text.toString(), - profileMobile.text.toString(), + unformatted, profileStatus.value.toString(), userImgUrl.value.isEmpty ? null : userImgUrl.value ) @@ -129,19 +121,19 @@ class ProfileController extends GetxController { var userProfileData = ProData( email: profileEmail.text.toString(), image: userImgUrl.value, - mobileNumber: profileMobile.text, + mobileNumber: unformatted, nickName: profileName.text, name: profileName.text, status: profileStatus.value); SessionManagement.setCurrentUser(userProfileData); - if (from.value == Routes.login) { - Mirrorfly.isTrailLicence().then((trail){ - if(trail.checkNull()) { + if (from == Routes.login) { + // Mirrorfly.isTrailLicence().then((trail){ + if(Mirrorfly.isTrialLicence) { Get.offNamed(Routes.dashboard); }else{ Get.offNamed(Routes.contactSync); } - }); + // }); } } } @@ -207,7 +199,7 @@ class ProfileController extends GetxController { isImageSelected.value = false; isUserProfileRemoved.value = true; userImgUrl(Constants.emptyString); - if (from.value == Routes.login) { + if (from == Routes.login) { changed(true); } else { save(frmImage: true); @@ -239,20 +231,25 @@ class ProfileController extends GetxController { if (data.data != null) { profileName.text = data.data!.name ?? ""; if (data.data!.mobileNumber.checkNull().isNotEmpty) { - //if (from.value != Routes.login) { - profileMobile.text = data.data!.mobileNumber ?? ""; + //if (from.value != Routes.login) { + validMobileNumber(data.data!.mobileNumber.checkNull()).then((valid) { + // if(valid) profileMobile.text = data.data!.mobileNumber.checkNull(); + mobileEditAccess(!valid); + }); + }else { + mobileEditAccess(true); } profileEmail.text = data.data!.email ?? ""; profileStatus.value = data.data!.status.checkNull().isNotEmpty ? data.data!.status.checkNull() : "I am in Mirror Fly"; userImgUrl.value = data.data!.image ?? "";//SessionManagement.getUserImage() ?? ""; SessionManagement.setUserImage(Constants.emptyString); - changed((from.value == Routes.login)); + changed((from == Routes.login)); name(data.data!.name.toString()); var userProfileData = ProData( email: profileEmail.text.toString(), image: userImgUrl.value, - mobileNumber: profileMobile.text, + mobileNumber: data.data!.mobileNumber.checkNull(), nickName: profileName.text, name: profileName.text, status: profileStatus.value); @@ -326,14 +323,14 @@ class ProfileController extends GetxController { .now() .millisecondsSinceEpoch}.jpg"; writeImageTemp(value.bytes, name).then((value) { - if (from.value == Routes.login) { + if (from == Routes.login) { imagePath(value.path); changed(true); update(); } else { imagePath(value.path); - changed(true); - updateProfileImage(value.path, update: true); + // changed(true); + updateProfileImage(value.path, update: false); } }); }); @@ -363,13 +360,13 @@ class ProfileController extends GetxController { imageBytes = value.bytes; var name = "${DateTime.now().millisecondsSinceEpoch}.jpg"; writeImageTemp(value.bytes, name).then((value) { - if (from.value == Routes.login) { + if (from == Routes.login) { imagePath(value.path); changed(true); } else { imagePath(value.path); - changed(true); - updateProfileImage(value.path, update: true); + // changed(true); + updateProfileImage(value.path, update: false); } }); }); @@ -402,6 +399,33 @@ class ProfileController extends GetxController { update(); } + onMobileChange(String text){ + changed(true); + validMobileNumber(text); + update(); + } + + Future validMobileNumber(String text)async{ + var m = text.contains("+") ? text : "+$text"; + FlutterLibphonenumber().init(); + var formatNumberSync = FlutterLibphonenumber().formatNumberSync(m); + try { + var parse = await FlutterLibphonenumber().parse(formatNumberSync); + debugPrint("parse-----> $parse"); + //{country_code: 91, e164: +91xxxxxxxxxx, national: 0xxxxx xxxxx, type: mobile, international: +91 xxxxx xxxxx, national_number: xxxxxxxxxx, region_code: IN} + if (parse.isNotEmpty) { + var formatted = parse['international'];//.replaceAll("+", ''); + profileMobile.text = formatted; + return true; + } else { + return false; + } + }catch(e){ + debugPrint('validMobileNumber $e'); + return false; + } + } + static void insertStatus() { debugPrint("Inserting Status"); var defaultStatus = Constants.defaultStatusList; diff --git a/lib/app/modules/profile/views/profile_view.dart b/lib/app/modules/profile/views/profile_view.dart index a71c2d36..717df350 100644 --- a/lib/app/modules/profile/views/profile_view.dart +++ b/lib/app/modules/profile/views/profile_view.dart @@ -41,7 +41,9 @@ class ProfileView extends GetView { style: TextStyle(color: appbarTextColor), ), centerTitle: true, - automaticallyImplyLeading: controller.from.value == Routes.login ? false : true, + automaticallyImplyLeading: Get.previousRoute != Routes.login//controller.from.value == Routes.login + // ? false + // : true, ), body: SafeArea( child: SingleChildScrollView( @@ -57,78 +59,92 @@ class ProfileView extends GetView { child: Stack( children: [ Padding( - padding: const EdgeInsets.fromLTRB(18.0, 0, 18.0, 0), + padding: const EdgeInsets.fromLTRB(18.0, 0, 18.0, + 0), child: ClipRRect( borderRadius: BorderRadius.circular(8.0), child: Obx( - () { - debugPrint("controller.userImgUrl.value ${controller.userImgUrl.value}"); - return InkWell( - child: controller.imagePath.value.isNotEmpty - ? SizedBox( + () { + debugPrint( + "controller.userImgUrl.value ${controller + .userImgUrl.value}"); + return InkWell( + child: controller.imagePath.value + .isNotEmpty + ? SizedBox( + width: 150, + height: 150, + child: ClipOval( + child: Image.file( + File(controller.imagePath.value), + fit: BoxFit.fill, + ), + )) + : ImageNetwork( + url: controller.userImgUrl.value + .checkNull(), width: 150, height: 150, - child: ClipOval( - child: Image.file( - File(controller.imagePath.value), - fit: BoxFit.fill, - ), - )) - : ImageNetwork( - url: controller.userImgUrl.value.checkNull(), - width: 150, - height: 150, - clipOval: true, - errorWidget: controller.profileName.text.checkNull() - .isNotEmpty - ? ProfileTextImage( - fontSize: 40, - bgColor: buttonBgColor, - text: controller.profileName.text.checkNull(), - radius: 75, - ) - : null, - isGroup: false, - blocked: false, - unknown: false, - ), - onTap: () { - if (controller.imagePath.value - .checkNull() - .isNotEmpty) { - Get.toNamed(Routes.imageView, arguments: { - 'imageName': controller.profileName.text, - 'imagePath': controller.imagePath.value.checkNull() - }); - } else if (controller.userImgUrl.value - .checkNull() - .isNotEmpty) { - Get.toNamed(Routes.imageView, arguments: { - 'imageName': controller.profileName.text, - 'imageUrl': controller.userImgUrl.value.checkNull() - }); - } - }, - ); - }), + clipOval: true, + errorWidget: controller.profileName.text + .checkNull() + .isNotEmpty + ? ProfileTextImage( + fontSize: 40, + bgColor: buttonBgColor, + text: controller.profileName.text + .checkNull(), + radius: 75, + ) + : null, + isGroup: false, + blocked: false, + unknown: false, + ), + onTap: () { + if (controller.imagePath.value + .checkNull() + .isNotEmpty) { + Get.toNamed( + Routes.imageView, arguments: { + 'imageName': controller.profileName + .text, + 'imagePath': controller.imagePath + .value.checkNull() + }); + } else if (controller.userImgUrl.value + .checkNull() + .isNotEmpty) { + Get.toNamed( + Routes.imageView, arguments: { + 'imageName': controller.profileName + .text, + 'imageUrl': controller.userImgUrl + .value.checkNull() + }); + } + }, + ); + }), ), ), Obx( - () => Positioned( - right: 10, - bottom: 10, - child: InkWell( - onTap: controller.loading.value - ? null - : () { - bottomSheetView(context); - }, - child: Image.asset( - 'assets/logos/camera_profile_change.png', - height: 40, + () => + Positioned( + right: 10, + bottom: 10, + child: InkWell( + onTap: controller.loading.value + ? null + : () { + bottomSheetView(context); + }, + child: Image.asset( + 'assets/logos/camera_profile_change.png', + height: 40, + ), + ), ), - ), - ), ) ], ), @@ -144,7 +160,9 @@ class ProfileView extends GetView { focusNode: controller.userNameFocus, autofocus: false, onChanged: (value) => controller.nameChanges(value), - textAlign: controller.profileName.text.isNotEmpty ? TextAlign.center : TextAlign.start, + textAlign: controller.profileName.text.isNotEmpty + ? TextAlign.center + : TextAlign.start, maxLength: 30, controller: controller.profileName, decoration: const InputDecoration( @@ -162,7 +180,8 @@ class ProfileView extends GetView { ), const Text( 'Email', - style: TextStyle(fontWeight: FontWeight.w600, fontSize: 14), + style: TextStyle( + fontWeight: FontWeight.w600, fontSize: 14), ), TextField( keyboardType: TextInputType.emailAddress, @@ -175,7 +194,8 @@ class ProfileView extends GetView { hintText: 'Enter Email Id', icon: SvgPicture.asset('assets/logos/email.svg'), ), - style: const TextStyle(fontWeight: FontWeight.normal, color: textColor), + style: const TextStyle( + fontWeight: FontWeight.normal, color: textColor), ), const AppDivider(), const SizedBox( @@ -183,40 +203,51 @@ class ProfileView extends GetView { ), const Text( 'Mobile Number', - style: TextStyle(fontWeight: FontWeight.w600, fontSize: 14), - ), - TextField( - controller: controller.profileMobile, - enabled: false, - decoration: InputDecoration( - border: InputBorder.none, - hintText: 'Enter Mobile Number', - icon: SvgPicture.asset('assets/logos/phone.svg'), - ), - style: const TextStyle(fontWeight: FontWeight.normal, color: textColor), + style: TextStyle( + fontWeight: FontWeight.w600, fontSize: 14), ), + Obx(() { + return TextField( + controller: controller.profileMobile, + onChanged: (value) => controller.onMobileChange(value), + enabled: controller.mobileEditAccess.value, + decoration: InputDecoration( + border: InputBorder.none, + hintText: 'Enter Mobile Number', + icon: SvgPicture.asset('assets/logos/phone.svg'), + ), + style: const TextStyle(fontWeight: FontWeight.normal, + color: textColor), + ); + }), const AppDivider(), const SizedBox( height: 20, ), const Text( 'Status', - style: TextStyle(fontWeight: FontWeight.w600, fontSize: 14), + style: TextStyle( + fontWeight: FontWeight.w600, fontSize: 14), ), - Obx(() => ListTile( + Obx(() => + ListTile( contentPadding: EdgeInsets.zero, title: Text( controller.profileStatus.value.isNotEmpty ? controller.profileStatus.value : Constants.defaultStatus, style: TextStyle( - color: controller.profileStatus.value.isNotEmpty ? textColor : Colors.black38, + color: controller.profileStatus.value.isNotEmpty + ? textColor + : Colors.black38, fontWeight: FontWeight.normal), ), minLeadingWidth: 10, leading: SvgPicture.asset('assets/logos/status.svg'), onTap: () { - Get.toNamed(Routes.statusList, arguments: {'status': controller.profileStatus.value}) + Get.toNamed(Routes.statusList, arguments: { + 'status': controller.profileStatus.value + }) ?.then((value) { if (value != null) { controller.profileStatus.value = value; @@ -229,30 +260,33 @@ class ProfileView extends GetView { ), Center( child: Obx( - () => ElevatedButton( - style: ElevatedButton.styleFrom( - padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 15), - textStyle: const TextStyle(fontSize: 14), - shape: const StadiumBorder()), - onPressed: controller.loading.value - ? null - : controller.changed.value + () => + ElevatedButton( + style: ElevatedButton.styleFrom( + padding: const EdgeInsets.symmetric( + horizontal: 40, vertical: 15), + textStyle: const TextStyle(fontSize: 14), + shape: const StadiumBorder()), + onPressed: controller.loading.value + ? null + : controller.changed.value ? () { - FocusScope.of(context).unfocus(); - if (!controller.loading.value) { - controller.save(); - } - } + FocusScope.of(context).unfocus(); + if (!controller.loading.value) { + controller.save(); + } + } : null, - child: Text( - controller.from.value == Routes.login - ? 'Save' - : controller.changed.value + child: Text( + controller.from == Routes.login + ? 'Save' + : controller.changed.value ? 'Update & Continue' : 'Save', - style: const TextStyle(fontWeight: FontWeight.w600), - ), - ), + style: const TextStyle( + fontWeight: FontWeight.w600), + ), + ), ), ), ], @@ -273,9 +307,12 @@ class ProfileView extends GetView { child: SizedBox( child: Card( shape: const RoundedRectangleBorder( - borderRadius: BorderRadius.only(topLeft: Radius.circular(30), topRight: Radius.circular(30))), + borderRadius: BorderRadius.only( + topLeft: Radius.circular(30), + topRight: Radius.circular(30))), child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), + padding: const EdgeInsets.symmetric( + horizontal: 20, vertical: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, @@ -297,7 +334,9 @@ class ProfileView extends GetView { tapTargetSize: MaterialTapTargetSize.shrinkWrap, alignment: Alignment.centerLeft), child: const Text("Take Photo", - style: TextStyle(color: textColor, fontWeight: FontWeight.bold))), + style: TextStyle( + color: textColor, fontWeight: FontWeight + .bold))), TextButton( onPressed: () { Get.back(); @@ -308,12 +347,16 @@ class ProfileView extends GetView { tapTargetSize: MaterialTapTargetSize.shrinkWrap, alignment: Alignment.centerLeft), child: const Text("Choose from Gallery", - style: TextStyle(color: textColor, fontWeight: FontWeight.bold))), + style: TextStyle( + color: textColor, fontWeight: FontWeight + .bold))), controller.userImgUrl.value.isNotEmpty ? TextButton( - onPressed: () { - Get.back(); - Helper.showAlert(message: "Are you sure you want to remove the photo?", actions: [ + onPressed: () { + Get.back(); + Helper.showAlert( + message: "Are you sure you want to remove the photo?", + actions: [ TextButton( onPressed: () { Get.back(); @@ -326,15 +369,16 @@ class ProfileView extends GetView { }, child: const Text("REMOVE")) ]); - }, - style: TextButton.styleFrom( - padding: EdgeInsets.zero, - tapTargetSize: MaterialTapTargetSize.shrinkWrap, - alignment: Alignment.centerLeft), - child: const Text( - "Remove Photo", - style: TextStyle(color: textColor, fontWeight: FontWeight.bold), - )) + }, + style: TextButton.styleFrom( + padding: EdgeInsets.zero, + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + alignment: Alignment.centerLeft), + child: const Text( + "Remove Photo", + style: TextStyle( + color: textColor, fontWeight: FontWeight.bold), + )) : const SizedBox(), ], ), diff --git a/lib/app/modules/scanner/web_login_result_view.dart b/lib/app/modules/scanner/web_login_result_view.dart index c368c991..c2070db8 100644 --- a/lib/app/modules/scanner/web_login_result_view.dart +++ b/lib/app/modules/scanner/web_login_result_view.dart @@ -51,9 +51,9 @@ class WebLoginResultView extends GetView { }); }); }), - ListTile(contentPadding: EdgeInsets.zero, title: Row( + ListTile(contentPadding: EdgeInsets.zero, title: const Row( mainAxisAlignment: MainAxisAlignment.center, - children: const [ + children: [ Icon(Icons.power_settings_new_rounded), SizedBox(width: 8,), Text("LOGOUT FROM ALL COMPUTERS"), diff --git a/lib/app/modules/settings/controllers/settings_controller.dart b/lib/app/modules/settings/controllers/settings_controller.dart index 877b0af8..4a0296d4 100644 --- a/lib/app/modules/settings/controllers/settings_controller.dart +++ b/lib/app/modules/settings/controllers/settings_controller.dart @@ -1,11 +1,11 @@ import 'dart:io'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:get/get.dart'; import 'package:mirror_fly_demo/app/data/helper.dart'; import 'package:mirrorfly_plugin/mirrorfly.dart'; import 'package:mirror_fly_demo/app/routes/app_pages.dart'; -import 'package:package_info_plus/package_info_plus.dart'; import 'package:path/path.dart'; import 'package:yaml/yaml.dart'; @@ -14,16 +14,24 @@ import '../../../data/apputils.dart'; import '../../../data/session_management.dart'; class SettingsController extends GetxController { - PackageInfo? packageInfo; - + // PackageInfo? packageInfo; + RxString version = "".obs; + RxString releaseDate = "".obs; @override void onInit() { super.onInit(); getPackageInfo(); + getReleaseDate(); } getPackageInfo() async { - packageInfo.obs.value = await PackageInfo.fromPlatform(); + // var packageInfo = await PackageInfo.fromPlatform(); + String yamlContent = await rootBundle.loadString('pubspec.yaml'); + YamlMap yamlMap = loadYaml(yamlContent); + String buildVersion = yamlMap['version']; + String buildReleaseDate = yamlMap['build_release_date']; + version(buildVersion); + releaseDate(buildReleaseDate); } logout() { @@ -66,7 +74,7 @@ class SettingsController extends GetxController { } getReleaseDate() async { - var releaseDate = "Nov"; + var releaseDate = ""; String pathToYaml = join(dirname(Platform.script.toFilePath()), '../pubspec.yaml'); File file = File(pathToYaml); diff --git a/lib/app/modules/settings/views/app_lock/app_lock_controller.dart b/lib/app/modules/settings/views/app_lock/app_lock_controller.dart index 0bc773c7..0a67f91f 100644 --- a/lib/app/modules/settings/views/app_lock/app_lock_controller.dart +++ b/lib/app/modules/settings/views/app_lock/app_lock_controller.dart @@ -17,7 +17,7 @@ import '../../../../data/apputils.dart'; import '../../../../routes/app_pages.dart'; class AppLockController extends FullLifeCycleController - with FullLifeCycleMixin { + with FullLifeCycleMixin,GetTickerProviderStateMixin { final FirebaseAuth _auth = FirebaseAuth.instance; final _pinEnabled = false.obs; @@ -545,6 +545,8 @@ class AppLockController extends FullLifeCycleController isDismissible: false, isScrollControlled: true, BottomSheet( + enableDrag: true, + animationController: BottomSheet.createAnimationController(this), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(30), @@ -553,108 +555,110 @@ class AppLockController extends FullLifeCycleController builder: (builder) { return WillPopScope( onWillPop: () async => false, - child: Padding( - padding: EdgeInsets.only( - top: 16.0, - left: 16.0, - right: 16.0, - bottom: MediaQuery - .of(Get.context!) - .viewInsets - .bottom), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - const Text( - 'Forget PIN ?', - textAlign: TextAlign.center, - style: - TextStyle(fontSize: 20, fontWeight: FontWeight.w600), - ), - const Padding( - padding: EdgeInsets.only(top: 16.0, right: 8, left: 8), - child: Text( - 'We have sent you the OTP to the registered mobile number enter the 6 digit verification code below', + child: SafeArea( + child: Padding( + padding: EdgeInsets.only( + top: 16.0, + left: 16.0, + right: 16.0, + bottom: MediaQuery + .of(Get.context!) + .viewInsets + .bottom), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + const Text( + 'Forget PIN ?', textAlign: TextAlign.center, - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w300, - color: Color(0Xff737373)), + style: + TextStyle(fontSize: 20, fontWeight: FontWeight.w600), ), - ), - const SizedBox( - height: 16, - ), - OTPTextField( - width: MediaQuery - .of(Get.context!) - .size - .width, - controller: otpController, - length: 6, - textFieldAlignment: MainAxisAlignment.center, - margin: const EdgeInsets.all(4), - fieldWidth: 40, - fieldStyle: FieldStyle.box, - outlineBorderRadius: 10, - style: const TextStyle(fontSize: 16), - otpFieldStyle: OtpFieldStyle(), - onChanged: (String pin) { - smsCode = (pin); - }), - Padding( - padding: const EdgeInsets.all(16.0), - child: Obx(() { - return InkWell( - onTap: () { - if (timeout.value) { - resend(); - } - }, - child: Text( - timeout.value - ? 'Resend OTP' - : '00:${(myDuration.value.inSeconds.remainder( - 60).toStringAsFixed(0).padLeft(2, '0'))}', - style: TextStyle( - color: timeout.value - ? const Color(0XFFFF0000) - : buttonBgColor, - fontSize: 15, - fontWeight: FontWeight.w500), - ), - ); - }), - ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - TextButton( - onPressed: () { - Get.back(); - }, - child: const Text( - 'Cancel', - style: TextStyle( - color: Color(0XFFFF0000), - fontSize: 16, - fontWeight: FontWeight.w700), - )), - TextButton( - onPressed: () { - verifyOTP(); + const Padding( + padding: EdgeInsets.only(top: 16.0, right: 8, left: 8), + child: Text( + 'We have sent you the OTP to the registered mobile number enter the 6 digit verification code below', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w300, + color: Color(0Xff737373)), + ), + ), + const SizedBox( + height: 16, + ), + OTPTextField( + width: MediaQuery + .of(Get.context!) + .size + .width, + controller: otpController, + length: 6, + textFieldAlignment: MainAxisAlignment.center, + margin: const EdgeInsets.all(4), + fieldWidth: 40, + fieldStyle: FieldStyle.box, + outlineBorderRadius: 10, + style: const TextStyle(fontSize: 16), + otpFieldStyle: OtpFieldStyle(), + onChanged: (String pin) { + smsCode = (pin); + }), + Padding( + padding: const EdgeInsets.all(16.0), + child: Obx(() { + return InkWell( + onTap: () { + if (timeout.value) { + resend(); + } }, - child: const Text( - 'Verify OTP', + child: Text( + timeout.value + ? 'Resend OTP' + : '00:${(myDuration.value.inSeconds.remainder( + 60).toStringAsFixed(0).padLeft(2, '0'))}', style: TextStyle( - color: buttonBgColor, - fontSize: 16, - fontWeight: FontWeight.w700), - )) - ], - ) - ], + color: timeout.value + ? const Color(0XFFFF0000) + : buttonBgColor, + fontSize: 15, + fontWeight: FontWeight.w500), + ), + ); + }), + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + TextButton( + onPressed: () { + Get.back(); + }, + child: const Text( + 'Cancel', + style: TextStyle( + color: Color(0XFFFF0000), + fontSize: 16, + fontWeight: FontWeight.w700), + )), + TextButton( + onPressed: () { + verifyOTP(); + }, + child: const Text( + 'Verify OTP', + style: TextStyle( + color: buttonBgColor, + fontSize: 16, + fontWeight: FontWeight.w700), + )) + ], + ) + ], + ), ), ), ); @@ -701,7 +705,7 @@ class AppLockController extends FullLifeCycleController Future sendVerificationCode() async { var mobileNumber = - '+${(SessionManagement.getCountryCode() ?? '').replaceAll('+', '')}${SessionManagement.getMobileNumber() ?? ''}'; + /*${(SessionManagement.getCountryCode() ?? '').replaceAll('+', '')}*/'+${SessionManagement.getMobileNumber() ?? ''}'; debugPrint('mobileNumber $mobileNumber'); /*Future.delayed(const Duration(milliseconds: 500), () { hideLoading(); diff --git a/lib/app/modules/settings/views/app_lock/app_lock_settings_view.dart b/lib/app/modules/settings/views/app_lock/app_lock_settings_view.dart index e5bfb882..e703772d 100644 --- a/lib/app/modules/settings/views/app_lock/app_lock_settings_view.dart +++ b/lib/app/modules/settings/views/app_lock/app_lock_settings_view.dart @@ -35,11 +35,11 @@ class AppLockSettingsView extends GetView { on: controller.bioEnabled, onToggle: (value) => controller.enableBio()), const SizedBox(height: 8,), - Padding( - padding: const EdgeInsets.all(16.0), + const Padding( + padding: EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, - children: const [ + children: [ Text( "If App Lock enabled, the app will be locked automatically after 32 sec when it is not in use.", style: TextStyle(color: textColor),), diff --git a/lib/app/modules/settings/views/app_lock/pin_view.dart b/lib/app/modules/settings/views/app_lock/pin_view.dart index 288df255..ac6a85f0 100644 --- a/lib/app/modules/settings/views/app_lock/pin_view.dart +++ b/lib/app/modules/settings/views/app_lock/pin_view.dart @@ -13,12 +13,12 @@ class PinView extends GetView { @override Widget build(BuildContext context) { return Scaffold( - body: WillPopScope( - onWillPop: (){ - SystemNavigator.pop(); - return Future.value(false); - }, - child: SafeArea( + body: SafeArea( + child: WillPopScope( + onWillPop: (){ + SystemNavigator.pop(); + return Future.value(false); + }, child: Stack( children: [ Image.asset(icBioBackground), diff --git a/lib/app/modules/settings/views/chat_settings/chat_settings_controller.dart b/lib/app/modules/settings/views/chat_settings/chat_settings_controller.dart index ec6cdb04..d76f89af 100644 --- a/lib/app/modules/settings/views/chat_settings/chat_settings_controller.dart +++ b/lib/app/modules/settings/views/chat_settings/chat_settings_controller.dart @@ -5,7 +5,6 @@ import 'package:mirrorfly_plugin/mirrorfly.dart'; import 'package:get/get.dart'; import 'package:mirror_fly_demo/app/common/constants.dart'; import 'package:mirror_fly_demo/app/data/session_management.dart'; -import 'package:permission_handler/permission_handler.dart'; import '../../../../data/apputils.dart'; import '../../../../data/helper.dart'; @@ -62,24 +61,13 @@ class ChatSettingsController extends GetxController { } Future enableDisableAutoDownload() async { - if (await askStoragePermission()) { + var permission = await AppPermission.getStoragePermission(); + if (permission) { var enable = !_autoDownloadEnabled.value;//SessionManagement.isAutoDownloadEnable(); Mirrorfly.setMediaAutoDownload(enable); _autoDownloadEnabled(enable); } } - Future askStoragePermission() async { - final permission = await AppPermission.getStoragePermission(); - switch (permission) { - case PermissionStatus.granted: - return true; - case PermissionStatus.permanentlyDenied: - return false; - default: - debugPrint("Contact Permission default"); - return false; - } - } Future enableDisableTranslate() async { //if (await AppUtils.isNetConnected() && SessionManagement.isGoogleTranslationEnable()) { diff --git a/lib/app/modules/settings/views/chat_settings/chat_settings_view.dart b/lib/app/modules/settings/views/chat_settings/chat_settings_view.dart index d93487f8..6c090f10 100644 --- a/lib/app/modules/settings/views/chat_settings/chat_settings_view.dart +++ b/lib/app/modules/settings/views/chat_settings/chat_settings_view.dart @@ -14,7 +14,7 @@ class ChatSettingsView extends GetView { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: const Text('Chat'), + title: const Text('Chats'), automaticallyImplyLeading: true, ), body: Obx(() { @@ -63,9 +63,9 @@ class ChatSettingsView extends GetView { Visibility( visible: controller.autoDownloadEnabled, child: chatListItem( - Column( + const Column( crossAxisAlignment: CrossAxisAlignment.start, - children: const [ + children: [ Text(Constants.dataUsageSettings, style: TextStyle( fontSize: 14, diff --git a/lib/app/modules/settings/views/settings_view.dart b/lib/app/modules/settings/views/settings_view.dart index fa31019c..0a7e3f39 100644 --- a/lib/app/modules/settings/views/settings_view.dart +++ b/lib/app/modules/settings/views/settings_view.dart @@ -10,9 +10,9 @@ import 'about/about_and_help_view.dart'; class SettingsView extends GetView { const SettingsView({Key? key}) : super(key: key); + @override Widget build(BuildContext context) { - return Scaffold( appBar: AppBar( title: const Text('Settings'), @@ -22,20 +22,26 @@ class SettingsView extends GetView { child: Column( children: [ settingListItem("Profile", profileIcon, rightArrowIcon, - () => Get.toNamed(Routes.profile,arguments: {"from":Routes.settings})), + () => + Get.toNamed( + Routes.profile, arguments: {"from": Routes.settings})), settingListItem("Chats", chatIcon, rightArrowIcon, () { Get.toNamed(Routes.chatSettings); }), settingListItem( "Starred Messages", staredMsgIcon, rightArrowIcon, () { - Get.toNamed(Routes.starredMessages); + Get.toNamed(Routes.starredMessages); }), settingListItem( - "Notifications", notificationIcon, rightArrowIcon, ()=>Get.toNamed(Routes.notification)), + "Notifications", notificationIcon, rightArrowIcon, () => + Get.toNamed(Routes.notification)), settingListItem( - "Blocked Contacts", blockedIcon, rightArrowIcon, ()=>Get.toNamed(Routes.blockedList)), - settingListItem("App Lock", lockIcon, rightArrowIcon, ()=>Get.toNamed(Routes.appLock)), - settingListItem("About and Help", aboutIcon, rightArrowIcon, () =>Get.to(const AboutAndHelpView())), + "Blocked Contacts", blockedIcon, rightArrowIcon, () => + Get.toNamed(Routes.blockedList)), + // settingListItem("App Lock", lockIcon, rightArrowIcon, () => + // Get.toNamed(Routes.appLock)), + settingListItem("About and Help", aboutIcon, rightArrowIcon, () => + Get.to(const AboutAndHelpView())), settingListItem( "Connection Label", connectionIcon, toggleOffIcon, () {}), settingListItem("Delete My Account", delete, rightArrowIcon, () { @@ -58,34 +64,34 @@ class SettingsView extends GetView { child: const Text("YES")) ]); }), - Padding( + Padding( padding: const EdgeInsets.all(20.0), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - RichText( - text: const TextSpan( - text: "Released On: ", - style: TextStyle(color: textColor), - children: [ - TextSpan( - text: "March 2023", - style: TextStyle(color: textHintColor)) - ]), - ), - RichText( + child: Obx(() { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + RichText( + text: TextSpan( + text: "Released On: ", + style: const TextStyle(color: textColor), + children: [ + TextSpan( + text: controller.releaseDate.value, + style: const TextStyle(color: textHintColor)) + ]), + ), + RichText( text: TextSpan( text: "Version ", style: const TextStyle(color: textColor), children: [ TextSpan( - text: controller.packageInfo != null - ? controller.packageInfo!.version - : "", + text: controller.version.value, style: const TextStyle(color: textHintColor)) ]), ), - ]), + ]); + }), ) ], ), diff --git a/lib/app/modules/starred_messages/controllers/starred_messages_controller.dart b/lib/app/modules/starred_messages/controllers/starred_messages_controller.dart index a86400ae..66de924c 100644 --- a/lib/app/modules/starred_messages/controllers/starred_messages_controller.dart +++ b/lib/app/modules/starred_messages/controllers/starred_messages_controller.dart @@ -1,15 +1,16 @@ -import 'dart:convert'; +import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart'; import 'package:get/get.dart'; import 'package:intl/intl.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; +import 'package:mirrorfly_plugin/mirrorflychat.dart'; import 'package:mirror_fly_demo/app/data/helper.dart'; import 'package:share_plus/share_plus.dart'; import '../../../common/constants.dart'; +import '../../../model/chat_message_model.dart'; import '../../../routes/app_pages.dart'; class StarredMessagesController extends FullLifeCycleController with FullLifeCycleMixin { @@ -51,8 +52,18 @@ class StarredMessagesController extends FullLifeCycleController with FullLifeCyc Mirrorfly.getFavouriteMessages().then((value) { List chatMessageModel = chatMessageModelFromJson( value); - starredChatList(chatMessageModel.toList()); + // starredChatList(chatMessageModel.toList()); + if(Platform.isAndroid){ + starredChatList(chatMessageModel.toList()); + }else{ + var list = chatMessageModel.toList().reversed.toList(); + starredChatList(list); + } isListLoading(false); + if(isSearch.value){ + lastInputValue=""; + startSearch(searchedText.text.toString()); + } }); } } @@ -88,8 +99,7 @@ class StarredMessagesController extends FullLifeCycleController with FullLifeCyc var selectedIndex = selectedChatList.indexWhere( (element) => chatMessageModel.messageId == element.messageId); if (!selectedIndex.isNegative) { - chatMessageModel.isSelected = - true; //selectedChatList[selectedIndex].isSelected; + chatMessageModel.isSelected(true); //selectedChatList[selectedIndex].isSelected; selectedChatList[selectedIndex] = chatMessageModel; selectedChatList.refresh(); validateForForwardMessage(); @@ -113,14 +123,14 @@ class StarredMessagesController extends FullLifeCycleController with FullLifeCyc starredChatList.indexWhere((message) => message.messageId == messageId); debugPrint("Media Status Onprogress changed---> onUploadDownloadProgressChanged $index $messageId $progressPercentage"); if (!index.isNegative) { - starredChatList[index].mediaChatMessage?.mediaProgressStatus = (int.parse(progressPercentage)); + starredChatList[index].mediaChatMessage?.mediaProgressStatus (int.parse(progressPercentage)); starredChatList.refresh(); } if(isSearch.value){ var selectedIndex = searchedStarredMessageList.indexWhere( (message) => message.messageId == messageId); if (!selectedIndex.isNegative) { - searchedStarredMessageList[selectedIndex].mediaChatMessage?.mediaProgressStatus = (int.parse(progressPercentage)); + searchedStarredMessageList[selectedIndex].mediaChatMessage?.mediaProgressStatus(int.parse(progressPercentage)); } } } @@ -165,7 +175,7 @@ class StarredMessagesController extends FullLifeCycleController with FullLifeCyc void addChatSelection(ChatMessageModel item) { if (item.messageType.toUpperCase() != Constants.mNotification) { selectedChatList.add(item); - item.isSelected = true; + item.isSelected (true); starredChatList.refresh(); validateForForwardMessage(); validateForShareMessage(); @@ -176,7 +186,7 @@ class StarredMessagesController extends FullLifeCycleController with FullLifeCyc clearChatSelection(ChatMessageModel item) { selectedChatList.remove(item); - item.isSelected = false; + item.isSelected (false); if (selectedChatList.isEmpty) { isSelected(false); selectedChatList.clear(); @@ -189,7 +199,7 @@ class StarredMessagesController extends FullLifeCycleController with FullLifeCyc clearAllChatSelection() { isSelected(false); for (var chatItem in selectedChatList) { - chatItem.isSelected = false; + chatItem.isSelected(false); } selectedChatList.clear(); } @@ -295,7 +305,7 @@ class StarredMessagesController extends FullLifeCycleController with FullLifeCyc favouriteMessage() { for (var item in selectedChatList) { Mirrorfly.updateFavouriteStatus( - item.messageId, item.chatUserJid, !item.isMessageStarred, item.messageChatType); + item.messageId, item.chatUserJid, !item.isMessageStarred.value, item.messageChatType); starredChatList .removeWhere((element) => item.messageId == element.messageId); if(isSearch.value){ @@ -309,7 +319,7 @@ class StarredMessagesController extends FullLifeCycleController with FullLifeCyc copyTextMessages() { Clipboard.setData( - ClipboardData(text: selectedChatList[0].messageTextContent)); + ClipboardData(text: selectedChatList[0].messageTextContent ?? "")); clearChatSelection(selectedChatList[0]); toToast("1 Text Copied Successfully to the clipboard"); } @@ -320,10 +330,10 @@ class StarredMessagesController extends FullLifeCycleController with FullLifeCyc return { selectedChatList.any((element) => element.isMessageSentByMe && - !element.isMessageRecalled && + !element.isMessageRecalled.value && (element.messageSentTime > recallTimeDifference)): selectedChatList.any((element) => - !element.isMessageRecalled && + !element.isMessageRecalled.value && (element.isMediaMessage() && element.mediaChatMessage!.mediaLocalStoragePath .checkNull() @@ -529,6 +539,7 @@ class StarredMessagesController extends FullLifeCycleController with FullLifeCyc if(str.isNotEmpty) { clear(true); if (lastInputValue != str.trim()) { + starredChatList.clear(); lastInputValue = str.trim(); addSearchedMessagesToList(str.trim()); } @@ -564,42 +575,79 @@ class StarredMessagesController extends FullLifeCycleController with FullLifeCyc var searchedStarredMessageList = []; Future addSearchedMessagesToList(String filterKey) async { - starredChatList.clear(); - for (var message in searchedStarredMessageList) { - var name = await getProfile(message.chatUserJid.checkNull()); - if (isTextMessageContainsFilterKey(message, filterKey)) { - starredChatList.add(message); - } else if (isImageCaptionContainsFilterKey(message, filterKey)) { - starredChatList.add(message); - } else if (isVideoCaptionContainsFilterKey(message, filterKey)) { - starredChatList.add(message); - } else if (Constants.mDocument == message.messageType && - message.mediaChatMessage!.mediaFileName.checkNull().isNotEmpty && - message.mediaChatMessage!.mediaFileName - .toLowerCase() - .contains(filterKey.toLowerCase())) { - starredChatList.add(message); - } else if (Constants.mContact == message.messageType && - message.contactChatMessage!.contactName.checkNull().isNotEmpty && - message.contactChatMessage!.contactName - .toLowerCase() - .contains(filterKey.toLowerCase())) { - starredChatList.add(message); - } else if (message.senderUserName.checkNull().isNotEmpty && - message.senderUserName - .toLowerCase() - .contains(filterKey.toLowerCase())) { - starredChatList.add(message); - } else if (message.isMessageSentByMe && - "You".toLowerCase().contains(filterKey.toLowerCase())) { - starredChatList.add(message); - } else if ((message.messageChatType== Constants.typeGroupChat)&& - name.name.checkNull().contains(filterKey.toLowerCase())) { - starredChatList.add(message); + if(starredChatList.isEmpty) { + for (var message in searchedStarredMessageList) { + if (isTextMessageContainsFilterKey(message, filterKey)) { + if(starredChatList.indexWhere((element) => element.messageId==message.messageId).isNegative) { + starredChatList.add(message); + debugPrint('starredChatList ${message.messageId}text'); + } + } else if (isImageCaptionContainsFilterKey(message, filterKey)) { + if(starredChatList.indexWhere((element) => element.messageId==message.messageId).isNegative) { + starredChatList.add(message); + debugPrint('starredChatList ${message.messageId}image'); + } + } else if (isVideoCaptionContainsFilterKey(message, filterKey)) { + if(starredChatList.indexWhere((element) => element.messageId==message.messageId).isNegative) { + starredChatList.add(message); + debugPrint('starredChatList ${message.messageId}video'); + } + } else if (Constants.mDocument == message.messageType && + message.mediaChatMessage! + .mediaFileName + .checkNull() + .isNotEmpty && + message.mediaChatMessage!.mediaFileName + .toLowerCase() + .contains(filterKey.toLowerCase())) { + if(starredChatList.indexWhere((element) => element.messageId==message.messageId).isNegative) { + starredChatList.add(message); + debugPrint('starredChatList ${message.messageId}doc'); + } + } else if (Constants.mContact == message.messageType && + message.contactChatMessage! + .contactName + .checkNull() + .isNotEmpty && + message.contactChatMessage!.contactName + .toLowerCase() + .contains(filterKey.toLowerCase())) { + if(starredChatList.indexWhere((element) => element.messageId==message.messageId).isNegative) { + starredChatList.add(message); + debugPrint('starredChatList ${message.messageId}contact'); + } + } else if (message.senderUserName + .checkNull() + .isNotEmpty && + message.senderUserName + .toLowerCase() + .contains(filterKey.toLowerCase())) { + if(starredChatList.indexWhere((element) => element.messageId==message.messageId).isNegative) { + starredChatList.add(message); + debugPrint('starredChatList ${message.messageId}sender'); + } + } else if (message.isMessageSentByMe && + "You".toLowerCase().contains(filterKey.toLowerCase())) { + if(starredChatList.indexWhere((element) => element.messageId==message.messageId).isNegative) { + starredChatList.add(message); + debugPrint('starredChatList ${message.messageId}you'); + } + } else if ((message.messageChatType == Constants.typeGroupChat)){ + var name = await getProfileDetails(message.chatUserJid.checkNull()); + if(name.name.checkNull().contains(filterKey.toLowerCase())) { + if(starredChatList.indexWhere((element) => element.messageId==message.messageId).isNegative) { + starredChatList.add(message); + debugPrint('starredChatList ${message.messageId} : group'); + } + } + } + starredChatList.refresh(); } + }else{ + starredChatList([]); + addSearchedMessagesToList(filterKey); } debugPrint('starredChatList ${starredChatList.length}'); - starredChatList.refresh(); /*starredMessagesAdapterAdapterData!!.setSearch(searchEnabled, searchedText) starredMessagesAdapterAdapterData!!.setStarredMessages(searchedStarredMessageList) starredMessagesAdapterAdapterData!!.notifyDataSetChanged()*/ @@ -633,10 +681,6 @@ class StarredMessagesController extends FullLifeCycleController with FullLifeCyc .toLowerCase() .contains(filterKey.toLowerCase()); } - Future getProfile(String jid) async { - var value = await Mirrorfly.getProfileDetails(jid, true); - return Profile.fromJson(json.decode(value.toString())); - } navigateMessage(ChatMessageModel starredChat) { Get.toNamed(Routes.chat,parameters: {'isFromStarred':'true',"userJid":starredChat.chatUserJid,"messageId":starredChat.messageId}); diff --git a/lib/app/modules/starred_messages/views/starred_messages_view.dart b/lib/app/modules/starred_messages/views/starred_messages_view.dart index a2b78038..3e3be093 100644 --- a/lib/app/modules/starred_messages/views/starred_messages_view.dart +++ b/lib/app/modules/starred_messages/views/starred_messages_view.dart @@ -6,11 +6,11 @@ import 'package:get/get.dart'; import '../../../common/constants.dart'; import '../../../common/widgets.dart'; +import '../../../model/chat_message_model.dart'; import '../../../widgets/custom_action_bar_icons.dart'; import '../../chat/chat_widgets.dart'; import '../../chat/views/starred_message_header.dart'; import '../controllers/starred_messages_controller.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; class StarredMessagesView extends GetView { const StarredMessagesView({Key? key}) : super(key: key); @@ -80,7 +80,7 @@ class StarredMessagesView extends GetView { Container( key: Key(starredChatList[index].messageId), color: controller.isSelected.value && - (starredChatList[index].isSelected) && + (starredChatList[index].isSelected.value) && controller.starredChatList.isNotEmpty ? chatReplyContainerColor : Colors.transparent, diff --git a/lib/app/modules/video_preview/controllers/video_play_controller.dart b/lib/app/modules/video_preview/controllers/video_play_controller.dart index dcd1e4b1..efffe887 100644 --- a/lib/app/modules/video_preview/controllers/video_play_controller.dart +++ b/lib/app/modules/video_preview/controllers/video_play_controller.dart @@ -1,19 +1,21 @@ +import 'package:flutter/material.dart'; import 'package:get/get.dart'; -import 'package:video_player/video_player.dart'; +// import 'package:video_player/video_player.dart'; class VideoPlayController extends GetxController{ var videoPath = "".obs; - late VideoPlayerController videoPlayerController; + // late VideoPlayerController videoPlayerController; var isInitialized = false.obs; var isPlaying = false.obs; @override void onInit() { super.onInit(); videoPath(Get.arguments['filePath']); + debugPrint("##path ${videoPath.value}"); // videoPlayerController = VideoPlayerController.file(File(Get.arguments['filePath'])) // ..initialize().then((_) { // // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed. @@ -24,19 +26,20 @@ class VideoPlayController extends GetxController{ @override void onClose() { super.onClose(); - isInitialized(false); + // isInitialized(false); + videoPath(""); // videoPlayerController.dispose(); } - togglePlay() { - if(videoPlayerController.value.isPlaying){ - // videoPlayerController.pause(); - isPlaying(false); - }else{ - - isPlaying(true); - // videoPlayerController.play(); - - } - } + // togglePlay() { + // if(videoPlayerController.value.isPlaying){ + // // videoPlayerController.pause(); + // isPlaying(false); + // }else{ + // + // isPlaying(true); + // // videoPlayerController.play(); + // + // } + // } } \ No newline at end of file diff --git a/lib/app/modules/video_preview/views/video_player_view.dart b/lib/app/modules/video_preview/views/video_player_view.dart index 909cd0a5..9359a449 100644 --- a/lib/app/modules/video_preview/views/video_player_view.dart +++ b/lib/app/modules/video_preview/views/video_player_view.dart @@ -1,46 +1,53 @@ -import 'package:better_video_player/better_video_player.dart'; +// import 'package:better_video_player/better_video_player.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:mirror_fly_demo/app/modules/video_preview/controllers/video_play_controller.dart'; +import '../../../widgets/video_player_widget.dart'; + class VideoPlayerView extends GetView { const VideoPlayerView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( backgroundColor: Colors.black, - appBar: AppBar( - backgroundColor: Colors.black, - iconTheme: const IconThemeData( - color: Colors.white - ), + iconTheme: const IconThemeData(color: Colors.white), + ), + body: SafeArea( + child: Column( + children: [ + // AspectRatio( + // aspectRatio: 0.6, + // child: BetterVideoPlayer( + // configuration: + // const BetterVideoPlayerConfiguration( + // looping: false, + // autoPlay: false, + // allowedScreenSleep: false, + // autoPlayWhenResume: false, + // ), + // controller: + // BetterVideoPlayerController(), + // dataSource: BetterVideoPlayerDataSource( + // BetterVideoPlayerDataSourceType.file, + // controller.videoPath.value, + // ), + // ), + // ), - ), - body: SafeArea( - child: Column( - children: [ - AspectRatio( - aspectRatio: 0.6, - child: BetterVideoPlayer( - configuration: - const BetterVideoPlayerConfiguration( - looping: false, - autoPlay: false, - allowedScreenSleep: false, - autoPlayWhenResume: false, - ), - controller: - BetterVideoPlayerController(), - dataSource: BetterVideoPlayerDataSource( - BetterVideoPlayerDataSourceType.file, - controller.videoPath.value, - ), - ), + AspectRatio( + aspectRatio: 0.6, + child: VideoPlayerWidget( + videoPath: controller.videoPath.value, + videoTitle: "Video", ), - ], - ), + ), + ], ), + ), ); } } diff --git a/lib/app/modules/view_all_media/controllers/view_all_media_controller.dart b/lib/app/modules/view_all_media/controllers/view_all_media_controller.dart index d73fe1c1..2d5ee396 100644 --- a/lib/app/modules/view_all_media/controllers/view_all_media_controller.dart +++ b/lib/app/modules/view_all_media/controllers/view_all_media_controller.dart @@ -7,9 +7,11 @@ import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:intl/intl.dart'; import 'package:mirror_fly_demo/app/data/helper.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; +import 'package:mirrorfly_plugin/mirrorflychat.dart'; import '../../../common/constants.dart'; +import '../../../model/chat_message_model.dart'; +import '../../../model/group_media_model.dart'; import '../../../routes/app_pages.dart'; import '../../chat/controllers/chat_controller.dart'; @@ -99,7 +101,7 @@ class ViewAllMediaController extends GetxController { mirrorFlyLog("get doc before json",value); var data = chatMessageModelFromJson(value); documentCount(data.length); - mirrorFlyLog("getDocsMessagess",json.encode(data)); + // mirrorFlyLog("getDocsMessagess",json.encode(data)); if (data.isNotEmpty) { _docslist(await getMapGroupedMediaList(data, false)); } @@ -171,7 +173,7 @@ class ViewAllMediaController extends GetxController { // debugPrint("getMapGroupedMediaList isMessage Recalled--> ${chatMessage.isMessageRecalled}"); // debugPrint("getMapGroupedMediaList isMediaDownloaded--> ${chatMessage.isMediaDownloaded()}"); // debugPrint("getMapGroupedMediaList isMediaUploaded--> ${chatMessage.isMediaUploaded()}"); - if (!chatMessage.isMessageRecalled && + if (!chatMessage.isMessageRecalled.value && (chatMessage.isMediaDownloaded() || chatMessage.isMediaUploaded()) && await isMediaAvailable(chatMessage, isMedia)) { diff --git a/lib/app/modules/view_all_media/views/view_all_media_view.dart b/lib/app/modules/view_all_media/views/view_all_media_view.dart index 9bcff3da..fc0e49b9 100644 --- a/lib/app/modules/view_all_media/views/view_all_media_view.dart +++ b/lib/app/modules/view_all_media/views/view_all_media_view.dart @@ -7,8 +7,9 @@ import 'package:mirror_fly_demo/app/common/widgets.dart'; import 'package:mirror_fly_demo/app/data/helper.dart'; import '../../../common/constants.dart'; +import '../../../model/chat_message_model.dart'; +import '../../../model/group_media_model.dart'; import '../controllers/view_all_media_controller.dart'; -import 'package:mirrorfly_plugin/mirrorfly.dart'; class ViewAllMediaView extends GetView { const ViewAllMediaView({Key? key}) : super(key: key); diff --git a/lib/app/modules/view_all_media_preview/views/view_all_media_preview_view.dart b/lib/app/modules/view_all_media_preview/views/view_all_media_preview_view.dart index 8b671a3c..8523f1d9 100644 --- a/lib/app/modules/view_all_media_preview/views/view_all_media_preview_view.dart +++ b/lib/app/modules/view_all_media_preview/views/view_all_media_preview_view.dart @@ -1,6 +1,6 @@ import 'dart:io'; -import 'package:better_video_player/better_video_player.dart'; +// import 'package:better_video_player/better_video_player.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; @@ -8,6 +8,7 @@ import 'package:get/get.dart'; import 'package:photo_view/photo_view.dart'; import '../../../common/constants.dart'; +import '../../../widgets/video_player_widget.dart'; import '../controllers/view_all_media_preview_controller.dart'; class ViewAllMediaPreviewView extends GetView { @@ -61,23 +62,26 @@ class ViewAllMediaPreviewView extends GetView { /// show video else { - return AspectRatio( - aspectRatio: 2, - child: BetterVideoPlayer( - configuration: - const BetterVideoPlayerConfiguration( - looping: false, - autoPlay: false, - allowedScreenSleep: false, - autoPlayWhenResume: false, - ), - controller: - BetterVideoPlayerController(), - dataSource: BetterVideoPlayerDataSource( - BetterVideoPlayerDataSourceType.file, - data.mediaChatMessage!.mediaLocalStoragePath, - ), - ), + // return AspectRatio( + // aspectRatio: 2, + // child: BetterVideoPlayer( + // configuration: + // const BetterVideoPlayerConfiguration( + // looping: false, + // autoPlay: false, + // allowedScreenSleep: false, + // autoPlayWhenResume: false, + // ), + // controller: + // BetterVideoPlayerController(), + // dataSource: BetterVideoPlayerDataSource( + // BetterVideoPlayerDataSourceType.file, + // data.mediaChatMessage!.mediaLocalStoragePath, + // ), + // ), + // ); + return VideoPlayerWidget( + videoPath: data.mediaChatMessage?.mediaLocalStoragePath ?? "", videoTitle: data.mediaChatMessage?.mediaFileName ?? "Video", ); } }) diff --git a/lib/app/widgets/video_player_widget.dart b/lib/app/widgets/video_player_widget.dart new file mode 100644 index 00000000..04eb517c --- /dev/null +++ b/lib/app/widgets/video_player_widget.dart @@ -0,0 +1,172 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:video_player/video_player.dart'; + +class VideoPlayerWidget extends StatefulWidget { + final String videoPath; + final String videoTitle; + + const VideoPlayerWidget({super.key, required this.videoPath, required this.videoTitle}); + + @override + State createState() => _VideoPlayerWidgetState(); +} + +class _VideoPlayerWidgetState extends State { + late VideoPlayerController _controller; + late Future _initializeVideoPlayerFuture; + bool _isPlaying = false; + double _sliderValue = 0.0; + + @override + void initState() { + super.initState(); + _controller = VideoPlayerController.file(File(widget.videoPath)) + ..addListener(() { + setState(() { + _sliderValue = + _controller.value.position.inSeconds.toDouble(); + }); + }); + _initializeVideoPlayerFuture = _controller.initialize().then((_) { + setState(() { + // _controller.play(); + _controller.setLooping(false); + _controller.setVolume(1.0); + _controller.setPlaybackSpeed(1.0); + + }); + }); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _playPause() { + setState(() { + if (_controller.value.isPlaying) { + _controller.pause(); + _isPlaying = false; + } else { + _controller.play(); + _isPlaying = true; + } + }); + } + + void _rewind() { + final Duration position = _controller.value.position; + const Duration rewindDuration = Duration(seconds: 10); + final Duration newDuration = position - rewindDuration; + _controller.seekTo(newDuration); + } + + void _forward() { + final Duration position = _controller.value.position; + const Duration forwardDuration = Duration(seconds: 10); + final Duration newDuration = position + forwardDuration; + _controller.seekTo(newDuration); + } + + void _onSliderChanged(double value) { + setState(() { + _sliderValue = value; + }); + final Duration newPosition = Duration(seconds: value.toInt()); + _controller.seekTo(newPosition); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.transparent, + body: Center( + child: FutureBuilder( + future: _initializeVideoPlayerFuture, + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.done) { + return Stack( + alignment: Alignment.center, + children: [ + AspectRatio( + aspectRatio: _controller.value.aspectRatio, + child: VideoPlayer(_controller), + ), + _buildControls(), + ], + ); + } else { + return const Center(child: CircularProgressIndicator()); + } + }, + ), + ), + ); + } + + Widget _buildControls() { + final position = _controller.value.position; + final duration = _controller.value.duration; + + String formatDuration(Duration d) { + final minutes = d.inMinutes.toString().padLeft(2, '0'); + final seconds = (d.inSeconds % 60).toString().padLeft(2, '0'); + return '$minutes:$seconds'; + } + + return Column( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Spacer(), + + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + IconButton( + onPressed: _rewind, + icon: const Icon(Icons.fast_rewind, color: Colors.blue,), + ), + const SizedBox(width: 16), + FloatingActionButton( + onPressed: _playPause, + child: Icon( + _isPlaying ? Icons.pause : Icons.play_arrow, + ), + ), + const SizedBox(width: 16), + IconButton( + onPressed: _forward, + icon: const Icon(Icons.fast_forward, color: Colors.blue,), + ), + ], + ), + const SizedBox(height: 16), + Row( + children: [ + Text( + formatDuration(position), + style: const TextStyle(fontSize: 16, color: Colors.blue), + ), + Expanded( + child: Slider( + min: 0.0, + max: _controller.value.duration.inSeconds.toDouble(), + value: _sliderValue, + onChanged: _onSliderChanged, + ), + ), + Text( + formatDuration(duration - position), + style: const TextStyle(fontSize: 16, color: Colors.blue), + ), + ], + ), + ], + ); + } +} + diff --git a/lib/firebase_options.dart b/lib/firebase_options.dart deleted file mode 100644 index c3df5776..00000000 --- a/lib/firebase_options.dart +++ /dev/null @@ -1,96 +0,0 @@ -// File generated by FlutterFire CLI. -// ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members -import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; -import 'package:flutter/foundation.dart' - show defaultTargetPlatform, kIsWeb, TargetPlatform; - -/// Default [FirebaseOptions] for use with your Firebase apps. -/// -/// Example: -/// ```dart -/// import 'firebase_options.dart'; -/// // ... -/// await Firebase.initializeApp( -/// options: DefaultFirebaseOptions.currentPlatform, -/// ); -/// ``` -class DefaultFirebaseOptions { - static FirebaseOptions get currentPlatform { - if (kIsWeb) { - return web; - } - switch (defaultTargetPlatform) { - case TargetPlatform.android: - return android; - case TargetPlatform.iOS: - return ios; - case TargetPlatform.macOS: - return macos; - case TargetPlatform.windows: - throw UnsupportedError( - 'DefaultFirebaseOptions have not been configured for windows - ' - 'you can reconfigure this by running the FlutterFire CLI again.', - ); - case TargetPlatform.linux: - throw UnsupportedError( - 'DefaultFirebaseOptions have not been configured for linux - ' - 'you can reconfigure this by running the FlutterFire CLI again.', - ); - default: - throw UnsupportedError( - 'DefaultFirebaseOptions are not supported for this platform.', - ); - } - } - - static const FirebaseOptions web = FirebaseOptions( - apiKey: 'AIzaSyBWEnaT0dt9pamuZXVnZEcI49IpxF8IvJo', - appId: '1:1045831384770:web:c1330bd3bb01968c11455b', - messagingSenderId: '1045831384770', - projectId: 'mirrorfly-uikit-dev', - authDomain: 'mirrorfly-uikit-dev.firebaseapp.com', - storageBucket: 'mirrorfly-uikit-dev.appspot.com', - measurementId: 'G-SP1SE77CZT', - ); - - static const FirebaseOptions android = FirebaseOptions( - apiKey: 'AIzaSyDfIqmrHFXEvJgE29tWr3Ps1bFJ-sOd2Go', - appId: '1:235373697524:android:8c60557f4f35c990a0c1a1', - messagingSenderId: '235373697524', - projectId: 'mirrorfly-uikit-qa', - storageBucket: 'mirrorfly-uikit-qa.appspot.com', - ); - - //for dev Bundle ID - // static const FirebaseOptions ios = FirebaseOptions( - // apiKey: 'AIzaSyBy7JDQj6Ar03dMXFCQ-SHgBdBPnKAteG4', - // appId: '1:1045831384770:ios:eff2902ecda09bf911455b', - // messagingSenderId: '1045831384770', - // projectId: 'mirrorfly-uikit-dev', - // storageBucket: 'mirrorfly-uikit-dev.appspot.com', - // androidClientId: '1045831384770-aa561p9dbh0467tsg3395ufeleu162k4.apps.googleusercontent.com', - // iosClientId: '1045831384770-a90apqltl7dtlbaj4844235jgv8l1hfm.apps.googleusercontent.com', - // iosBundleId: 'com.mirrorfly.uikitflutter.dev', - // ); - static const FirebaseOptions ios = FirebaseOptions( - apiKey: 'AIzaSyDsUcOmi4zG9eJfNyDLgmACZICvieFJJDo', - appId: '1:235373697524:ios:2d40908026b55394a0c1a1', - messagingSenderId: '235373697524', - projectId: 'mirrorfly-uikit-qa', - storageBucket: 'mirrorfly-uikit-qa.appspot.com', - androidClientId: '235373697524-aa561p9dbh0467tsg3395ufeleu162k4.apps.googleusercontent.com', - iosClientId: '780821286585-j79p55tl4abuskv43vikijnlc36hbv2p.apps.googleusercontent.com', - iosBundleId: 'com.mirrorfly.uikitflutter.qa', - ); - - static const FirebaseOptions macos = FirebaseOptions( - apiKey: 'AIzaSyBy7JDQj6Ar03dMXFCQ-SHgBdBPnKAteG4', - appId: '1:1045831384770:ios:8e3466b1aa07bd5811455b', - messagingSenderId: '1045831384770', - projectId: 'mirrorfly-uikit-dev', - storageBucket: 'mirrorfly-uikit-dev.appspot.com', - androidClientId: '1045831384770-aa561p9dbh0467tsg3395ufeleu162k4.apps.googleusercontent.com', - iosClientId: '1045831384770-od86edts5jinp5fg6e1t7qkf707rugrm.apps.googleusercontent.com', - iosBundleId: 'com.contusdemo.mirrorFlyDemo', - ); -} diff --git a/lib/main.dart b/lib/main.dart index 5a4dc849..c67d11a0 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -2,9 +2,6 @@ import 'package:flutter/material.dart'; -import 'package:firebase_auth/firebase_auth.dart'; -import 'package:firebase_core/firebase_core.dart'; -import 'package:flutter/foundation.dart'; import 'package:mirrorfly_plugin/mirrorfly.dart'; import 'package:get/get.dart'; @@ -12,7 +9,6 @@ import 'package:mirror_fly_demo/app/common/app_theme.dart'; import 'package:mirror_fly_demo/app/common/constants.dart'; import 'package:mirror_fly_demo/app/common/main_controller.dart'; import 'package:mirror_fly_demo/app/data/helper.dart'; -import 'package:mirror_fly_demo/app/data/pushnotification.dart'; import 'package:mirror_fly_demo/app/modules/dashboard/bindings/dashboard_binding.dart'; import 'package:mirror_fly_demo/app/modules/login/bindings/login_binding.dart'; import 'app/data/session_management.dart'; @@ -23,46 +19,23 @@ import 'app/routes/app_pages.dart'; import 'package:google_maps_flutter_android/google_maps_flutter_android.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; - - - - bool shouldUseFirebaseEmulator = false; -// dynamic nonChatUsers = []; Future main() async { WidgetsFlutterBinding.ensureInitialized(); Mirrorfly.init( baseUrl: 'https://api-preprod-sandbox.mirrorfly.com/api/v1/', - licenseKey: 'Please enter your License key', - iOSContainerID: 'group.com.mirrorfly.qa'); + licenseKey: 'Your License Key Here', + iOSContainerID: 'group.com.mirrorfly.flutter'); final GoogleMapsFlutterPlatform mapsImplementation = GoogleMapsFlutterPlatform.instance; if (mapsImplementation is GoogleMapsFlutterAndroid) { mapsImplementation.useAndroidViewSurface = true; } - await SessionManagement.onInit(); - ReplyHashMap.init(); - // Mirrorfly.getSendData().then((value) { - // debugPrint("notification value ===> $value"); - // SessionManagement.setChatJid(value.checkNull()); - // }); - // var nonchat = await Mirrorfly.getNonChatUsers(); - // nonChatUsers = json.decode(nonchat.toString()); - Mirrorfly.isTrailLicence().then((value) => SessionManagement.setIsTrailLicence(value.checkNull())); - // Mirrorfly.cancelNotifications(); - if (!kIsWeb) { - await Firebase.initializeApp(); - // await Firebase.initializeApp( - // options: DefaultFirebaseOptions.currentPlatform, - // ); - // FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); - PushNotifications.setupInteractedMessage(); - } - if (shouldUseFirebaseEmulator) { - await FirebaseAuth.instance.useAuthEmulator('localhost', 5050); - } - Get.put(MainController()); + // if (shouldUseFirebaseEmulator) { + // await FirebaseAuth.instance.useAuthEmulator('localhost', 5050); + // } + await SessionManagement.onInit(); runApp(const MyApp()); } @@ -76,9 +49,11 @@ class MyApp extends StatelessWidget{ title: "MirrorFly", theme: MirrorFlyAppTheme.theme, debugShowCheckedModeBanner: false, - //initialBinding: getBinding(), + onInit: () { + ReplyHashMap.init(); + Get.put(MainController()); + }, initialRoute: SessionManagement.getEnablePin() ? Routes.pin : getInitialRoute(), - //initialRoute: AppPages.INITIAL, getPages: AppPages.routes, ); } @@ -111,15 +86,19 @@ String getInitialRoute() { .getChatJid() .checkNull() .isEmpty) { - if(!SessionManagement.isTrailLicence()) { - // mirrorFlyLog("nonChatUsers", nonChatUsers.toString()); + if(!Mirrorfly.isTrialLicence) { mirrorFlyLog("SessionManagement.isContactSyncDone()", SessionManagement.isContactSyncDone().toString()); - if (!SessionManagement.isContactSyncDone() /*|| nonChatUsers.isEmpty*/) { + if (!SessionManagement.isContactSyncDone()) { return AppPages.contactSync; }else{ return AppPages.dashboard; } }else{ + mirrorFlyLog("login", "${SessionManagement + .getChatJid() + .checkNull() + .isEmpty}"); + mirrorFlyLog("SessionManagement.getLogin()", "${SessionManagement.getLogin()}"); return AppPages.dashboard; } } else { diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index 747d40eb..fd8c87bc 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -6,7 +6,6 @@ import FlutterMacOS import Foundation import audioplayers -import connectivity_macos import device_info_plus import emoji_picker_flutter import firebase_app_installations @@ -15,18 +14,16 @@ import firebase_core import firebase_messaging import flutter_local_notifications import geolocator_apple -import package_info_plus_macos +import package_info_plus import path_provider_macos import photo_manager import share_plus -import shared_preferences_macos +import shared_preferences_foundation import sqflite import url_launcher_macos -import wakelock_macos func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { AudioplayersPlugin.register(with: registry.registrar(forPlugin: "AudioplayersPlugin")) - ConnectivityPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlugin")) DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin")) EmojiPickerFlutterPlugin.register(with: registry.registrar(forPlugin: "EmojiPickerFlutterPlugin")) FirebaseInstallationsPlugin.register(with: registry.registrar(forPlugin: "FirebaseInstallationsPlugin")) @@ -42,5 +39,4 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin")) UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) - WakelockMacosPlugin.register(with: registry.registrar(forPlugin: "WakelockMacosPlugin")) } diff --git a/pubspec.lock b/pubspec.lock index 1f6ab0b4..97046486 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,10 +5,10 @@ packages: dependency: transitive description: name: _flutterfire_internals - sha256: f175bc1414e4edf8c5b83372c98eeabecf8353f39c9da423c2cfdf1f1f508788 + sha256: "9ebe81588e666f7e2b21309f2b5653bd9642d7f27fd0a6894278d2ff40cb9481" url: "https://pub.dev" source: hosted - version: "1.1.0" + version: "1.3.2" archive: dependency: transitive description: @@ -29,10 +29,10 @@ packages: dependency: transitive description: name: async - sha256: bfe67ef28df125b7dddcea62755991f807aa39a2492a23e1550161692950bbe0 + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" url: "https://pub.dev" source: hosted - version: "2.10.0" + version: "2.11.0" audioplayers: dependency: "direct main" description: @@ -41,14 +41,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.20.1" - better_video_player: - dependency: "direct main" - description: - name: better_video_player - sha256: "97c0e641244a339af82e186cc80466ea43b730eeb30d5eaaf88575d9d0278a94" - url: "https://pub.dev" - source: hosted - version: "1.2.8" boolean_selector: dependency: transitive description: @@ -85,18 +77,18 @@ packages: dependency: "direct main" description: name: camera - sha256: ad1c53c554a2f3e5708f3b01eb738d60b902bb61f7f4ad420c65c715e65a7379 + sha256: ebebead3d5ec3d148249331d751d462d7e8c98102b8830a9b45ec96a2bd4333f url: "https://pub.dev" source: hosted - version: "0.10.3+2" + version: "0.10.5+2" camera_android: dependency: transitive description: name: camera_android - sha256: "772c111c78f31f868b98dbf6dbeda8d6ff77acea773a92ea5705ee2f7949ebfb" + sha256: f83e406d34f5faa80bf0f5c3beee4b4c11da94a94e9621c1bb8e312988621b4b url: "https://pub.dev" source: hosted - version: "0.10.5" + version: "0.10.8+2" camera_avfoundation: dependency: transitive description: @@ -125,10 +117,10 @@ packages: dependency: transitive description: name: characters - sha256: e6a326c8af69605aec75ed6c187d06b349707a27fbff8222ca9cc2cff167975c + sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" url: "https://pub.dev" source: hosted - version: "1.2.1" + version: "1.3.0" clock: dependency: transitive description: @@ -141,58 +133,10 @@ packages: dependency: transitive description: name: collection - sha256: cfc915e6923fe5ce6e153b0723c753045de46de1b4d63771530504004a45fae0 - url: "https://pub.dev" - source: hosted - version: "1.17.0" - connectivity: - dependency: transitive - description: - name: connectivity - sha256: a8e91263cf3e25fb5cc95e19dfde4999e32a648ac3b9e8a558a28165731678f8 - url: "https://pub.dev" - source: hosted - version: "3.0.6" - connectivity_for_web: - dependency: transitive - description: - name: connectivity_for_web - sha256: "01a390c1d5adc2ed1fa1f52d120c07fe9fd01166a93f965a832fd6cfc0ea6482" - url: "https://pub.dev" - source: hosted - version: "0.4.0+1" - connectivity_macos: - dependency: transitive - description: - name: connectivity_macos - sha256: "51ae08d5162eca9669b9d8951ed83ce19c5355a81149f94e4dee2740beb93628" - url: "https://pub.dev" - source: hosted - version: "0.2.1+2" - connectivity_platform_interface: - dependency: transitive - description: - name: connectivity_platform_interface - sha256: "2d82e942df9d49f29a24bb07fb5ce085d4a53e47818c62364d2b6deb9e0d7a8e" + sha256: "4a07be6cb69c84d677a6c3096fcf960cc3285a8330b4603e0d463d15d9bd934c" url: "https://pub.dev" source: hosted - version: "2.0.1" - contact_picker_platform_interface: - dependency: transitive - description: - name: contact_picker_platform_interface - sha256: "40847ffa0f6e6755c0047e8ef35c4b622a2b053f41ef175d22c19f03984a9ed1" - url: "https://pub.dev" - source: hosted - version: "4.7.0" - contact_picker_web: - dependency: transitive - description: - name: contact_picker_web - sha256: "13e739a6ce8f3286e441028dec5967b90fd2d5ceaec53045ae054b030877fe31" - url: "https://pub.dev" - source: hosted - version: "4.7.0" + version: "1.17.1" contacts_service: dependency: "direct main" description: @@ -205,10 +149,10 @@ packages: dependency: transitive description: name: cross_file - sha256: f71079978789bc2fe78d79227f1f8cfe195b31bbd8db2399b0d15a4b96fb843b + sha256: "0b0036e8cccbfbe0555fd83c1d31a6f30b77a96b598b35a5d36dd41f718695e9" url: "https://pub.dev" source: hosted - version: "0.3.3+2" + version: "0.3.3+4" crypto: dependency: transitive description: @@ -317,10 +261,10 @@ packages: dependency: "direct main" description: name: file_picker - sha256: "686efb9e24d488a7196af39d03501a10afdac841435610f4357f9f1eb027f1c2" + sha256: "9d6e95ec73abbd31ec54d0e0df8a961017e165aba1395e462e5b31ea0c165daf" url: "https://pub.dev" source: hosted - version: "5.2.1" + version: "5.3.1" firebase_app_installations: dependency: "direct main" description: @@ -373,50 +317,50 @@ packages: dependency: "direct main" description: name: firebase_core - sha256: ed611fb8e67e43ecc7956f242cecca383d87cf71aace27287aa5dd4bdba4ac07 + sha256: e9b36b391690cf329c6fb1de220045e97c13784c303820cd33962319580a56c6 url: "https://pub.dev" source: hosted - version: "2.9.0" + version: "2.13.1" firebase_core_platform_interface: dependency: transitive description: name: firebase_core_platform_interface - sha256: "0df0a064ab0cad7f8836291ca6f3272edd7b83ad5b3540478ee46a0849d8022b" + sha256: b63e3be6c96ef5c33bdec1aab23c91eb00696f6452f0519401d640938c94cba2 url: "https://pub.dev" source: hosted - version: "4.6.0" + version: "4.8.0" firebase_core_web: dependency: transitive description: name: firebase_core_web - sha256: "347351a8f0518f3343d79a9a0690fa67ad232fc32e2ea270677791949eac792b" + sha256: "8c0f4c87d20e2d001a5915df238c1f9c88704231f591324205f5a5d2a7740a45" url: "https://pub.dev" source: hosted - version: "2.3.0" + version: "2.5.0" firebase_messaging: dependency: "direct main" description: name: firebase_messaging - sha256: e4a5eb079aa9e7bd6b5fb2681f2bb8a6c78f87aacbf1c732c6ce91ad71e595ba + sha256: a01d7b9eb43a4bad54a411edb2b4124089d88eab029191893e83c39e18ab19f7 url: "https://pub.dev" source: hosted - version: "14.4.0" + version: "14.6.2" firebase_messaging_platform_interface: dependency: transitive description: name: firebase_messaging_platform_interface - sha256: "3a007c888e3414c9e4f7c35ea6fa59eafc623c62ee36155710563a1ebc160063" + sha256: c2fef3e30fbfa3a71d74477df102d1c2f5aad860bb68bb4086b0af3b12abedf3 url: "https://pub.dev" source: hosted - version: "4.3.0" + version: "4.5.2" firebase_messaging_web: dependency: transitive description: name: firebase_messaging_web - sha256: a3239662b91b652cea4ce3b3ecac6cccbaebc1b4ac3101224bef805de4195fbf + sha256: "8d280f0110ca4946b9863e578b9879874066ac486ffa596a609aab329fb6fa7e" url: "https://pub.dev" source: hosted - version: "3.3.0" + version: "3.5.2" flutter: dependency: "direct main" description: flutter @@ -431,7 +375,7 @@ packages: source: hosted version: "0.7.0" flutter_cache_manager: - dependency: "direct main" + dependency: transitive description: name: flutter_cache_manager sha256: "32cd900555219333326a2d0653aaaf8671264c29befa65bbd9856d204a4c9fb3" @@ -538,18 +482,10 @@ packages: dependency: transitive description: name: flutter_plugin_android_lifecycle - sha256: "60fc7b78455b94e6de2333d2f95196d32cf5c22f4b0b0520a628804cb463503b" + sha256: "950e77c2bbe1692bc0874fc7fb491b96a4dc340457f4ea1641443d0a6c1ea360" url: "https://pub.dev" source: hosted - version: "2.0.7" - flutter_profile_picture: - dependency: "direct main" - description: - name: flutter_profile_picture - sha256: "067caecef0d7162d3858eaca3c5859cbbb21b3e5704c2bc5b96b50ffe267f45d" - url: "https://pub.dev" - source: hosted - version: "2.0.0" + version: "2.0.15" flutter_svg: dependency: "direct main" description: @@ -576,14 +512,6 @@ packages: description: flutter source: sdk version: "0.0.0" - fluttercontactpicker: - dependency: "direct main" - description: - name: fluttercontactpicker - sha256: cddd2ba4631f97927adb59c53a529ee8f965e8685eded66a6d5988347aef6ec4 - url: "https://pub.dev" - source: hosted - version: "4.7.0" fluttertoast: dependency: "direct main" description: @@ -696,22 +624,22 @@ packages: url: "https://pub.dev" source: hosted version: "4.6.5" - google_cloud_translation: - dependency: "direct main" + google_maps: + dependency: transitive description: - name: google_cloud_translation - sha256: "13944a6832231fe3b750f7f22aa890daf4c2d3b014528fbb38cc0037d406e22f" + name: google_maps + sha256: "555d5d736339b0478e821167ac521c810d7b51c3b2734e6802a9f046b64ea37a" url: "https://pub.dev" source: hosted - version: "0.0.3" + version: "6.3.0" google_maps_flutter: dependency: "direct main" description: name: google_maps_flutter - sha256: "24392ef192f3b00bcd93151375676805a9933574423a5bd5509a0ead2e8a4215" + sha256: "7b417a64ee7a060f42cf44d8c274d3b562423f6fe57d2911b7b536857c0d8eb6" url: "https://pub.dev" source: hosted - version: "2.2.5" + version: "2.3.0" google_maps_flutter_android: dependency: transitive description: @@ -736,14 +664,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.6" - grouped_list: - dependency: "direct main" + google_maps_flutter_web: + dependency: transitive description: - name: grouped_list - sha256: fef106470186081c32636aa055492eee7fc7fe8bf0921a48d31ded24821af19f + name: google_maps_flutter_web + sha256: "5f58d7c491240b0074f455e70ce8d9b038f92472559e49e3b611d9f39b8d51a7" url: "https://pub.dev" source: hosted - version: "5.1.2" + version: "0.5.0+1" html: dependency: transitive description: @@ -752,14 +680,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.15.0" - html_unescape: - dependency: transitive - description: - name: html_unescape - sha256: "15362d7a18f19d7b742ef8dcb811f5fd2a2df98db9f80ea393c075189e0b61e3" - url: "https://pub.dev" - source: hosted - version: "2.0.0" http: dependency: transitive description: @@ -860,10 +780,18 @@ packages: dependency: transitive description: name: js - sha256: "5528c2f391ededb7775ec1daa69e65a2d61276f7552de2b5f7b8d34ee9fd4ab7" + sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 + url: "https://pub.dev" + source: hosted + version: "0.6.7" + js_wrapping: + dependency: transitive + description: + name: js_wrapping + sha256: e385980f7c76a8c1c9a560dfb623b890975841542471eade630b2871d243851c url: "https://pub.dev" source: hosted - version: "0.6.5" + version: "0.7.4" keyboard_dismisser: dependency: "direct main" description: @@ -900,10 +828,10 @@ packages: dependency: transitive description: name: matcher - sha256: "16db949ceee371e9b99d22f88fa3a73c4e59fd0afed0bd25fc336eb76c198b72" + sha256: "6501fbd55da300384b768785b83e5ce66991266cec21af89ab9ae7f5ce1c4cbb" url: "https://pub.dev" source: hosted - version: "0.12.13" + version: "0.12.15" material_color_utilities: dependency: transitive description: @@ -916,10 +844,10 @@ packages: dependency: transitive description: name: meta - sha256: "6c268b42ed578a53088d834796959e4a1814b5e9e164f147f580a386e5decf42" + sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3" url: "https://pub.dev" source: hosted - version: "1.8.0" + version: "1.9.1" mime: dependency: transitive description: @@ -932,10 +860,10 @@ packages: dependency: "direct main" description: name: mirrorfly_plugin - sha256: "53fc731d9c1c014016d76bc108682ae22edad7299a2720fd23583c3cb02a7ae3" + sha256: c2266df8e518a445bf4c96623692229ac33558a9365e2e93a1969765eaaf4f26 url: "https://pub.dev" source: hosted - version: "0.0.3" + version: "0.0.7" nested: dependency: transitive description: @@ -980,58 +908,26 @@ packages: dependency: "direct main" description: name: package_info_plus - sha256: a6eb9db6f8bfadcc95b04f53c9f6ba2b112b8e8fbf430ae34a0aa0a64b1022c8 - url: "https://pub.dev" - source: hosted - version: "2.0.0" - package_info_plus_linux: - dependency: transitive - description: - name: package_info_plus_linux - sha256: "15a66f80b52245e14af7be939bbd1959961f09cfc1d58523cc4e8d5b740efb21" + sha256: ceb027f6bc6a60674a233b4a90a7658af1aebdea833da0b5b53c1e9821a78c7b url: "https://pub.dev" source: hosted - version: "2.0.0" - package_info_plus_macos: - dependency: transitive - description: - name: package_info_plus_macos - sha256: b774a2d8b31c4575a9a9c56f86a2cb542f0ef1d08be8623b94af0f7c962a2845 - url: "https://pub.dev" - source: hosted - version: "2.0.0" + version: "4.0.2" package_info_plus_platform_interface: dependency: transitive description: name: package_info_plus_platform_interface - sha256: "2ce4f956afc47e70f897b7a1d59c398ba6627ac907d1ae02ef955a9f8a9c1eef" + sha256: "9bc8ba46813a4cc42c66ab781470711781940780fd8beddd0c3da62506d3a6c6" url: "https://pub.dev" source: hosted - version: "2.0.0" - package_info_plus_web: - dependency: transitive - description: - name: package_info_plus_web - sha256: fb408fed17c00ed4b4b963d124a83bcbf25de990dea0c43a73d48b20339f62a4 - url: "https://pub.dev" - source: hosted - version: "2.0.0" - package_info_plus_windows: - dependency: transitive - description: - name: package_info_plus_windows - sha256: ffb1f96a57ff7680c06a66ae12f62140350beddc5478ef18494901c74067f122 - url: "https://pub.dev" - source: hosted - version: "3.0.0" + version: "2.0.1" path: dependency: "direct main" description: name: path - sha256: db9d4f58c908a4ba5953fcee2ae317c94889433e5024c27ce74a37f94267945b + sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917" url: "https://pub.dev" source: hosted - version: "1.8.2" + version: "1.8.3" path_drawing: dependency: transitive description: @@ -1100,10 +996,10 @@ packages: dependency: transitive description: name: path_provider_windows - sha256: bcabbe399d4042b8ee687e17548d5d3f527255253b4a639f5f8d2094a9c2b45c + sha256: "1cb68ba4cd3a795033de62ba1b7b4564dace301f952de6bfb3cd91b202b6ee96" url: "https://pub.dev" source: hosted - version: "2.1.3" + version: "2.1.7" pedantic: dependency: transitive description: @@ -1188,10 +1084,10 @@ packages: dependency: transitive description: name: plugin_platform_interface - sha256: dbf0f707c78beedc9200146ad3cb0ab4d5da13c246336987be6940f026500d3a + sha256: "6a2128648c854906c53fa8e33986fc0247a1116122f9534dd20e3ab9e16a32bc" url: "https://pub.dev" source: hosted - version: "2.1.3" + version: "2.1.4" process: dependency: transitive description: @@ -1256,6 +1152,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.27.5" + sanitize_html: + dependency: transitive + description: + name: sanitize_html + sha256: "0a445f19bbaa196f5a4f93461aa066b94e6e025622eb1e9bc77872a5e25233a5" + url: "https://pub.dev" + source: hosted + version: "2.0.0" scrollable_positioned_list: dependency: "direct main" description: @@ -1268,82 +1172,74 @@ packages: dependency: "direct main" description: name: share_plus - sha256: "8c6892037b1824e2d7e8f59d54b3105932899008642e6372e5079c6939b4b625" + sha256: ed3fcea4f789ed95913328e629c0c53e69e80e08b6c24542f1b3576046c614e8 url: "https://pub.dev" source: hosted - version: "6.3.1" + version: "7.0.2" share_plus_platform_interface: dependency: transitive description: name: share_plus_platform_interface - sha256: "82ddd4ab9260c295e6e39612d4ff00390b9a7a21f1bb1da771e2f232d80ab8a1" + sha256: "0c6e61471bd71b04a138b8b588fa388e66d8b005e6f2deda63371c5c505a0981" url: "https://pub.dev" source: hosted - version: "3.2.0" + version: "3.2.1" shared_preferences: dependency: "direct main" description: name: shared_preferences - sha256: "76917b7d4b9526b2ba416808a7eb9fb2863c1a09cf63ec85f1453da240fa818a" + sha256: "396f85b8afc6865182610c0a2fc470853d56499f75f7499e2a73a9f0539d23d0" url: "https://pub.dev" source: hosted - version: "2.0.15" + version: "2.1.2" shared_preferences_android: dependency: transitive description: name: shared_preferences_android - sha256: "3e128864b9cff21bdd5b3ad569953070a851d62901bee880bb052b1110b38007" + sha256: "6478c6bbbecfe9aced34c483171e90d7c078f5883558b30ec3163cf18402c749" url: "https://pub.dev" source: hosted - version: "2.0.13" - shared_preferences_ios: + version: "2.1.4" + shared_preferences_foundation: dependency: transitive description: - name: shared_preferences_ios - sha256: "585a14cefec7da8c9c2fb8cd283a3bb726b4155c0952afe6a0caaa7b2272de34" + name: shared_preferences_foundation + sha256: e014107bb79d6d3297196f4f2d0db54b5d1f85b8ea8ff63b8e8b391a02700feb url: "https://pub.dev" source: hosted - version: "2.1.1" + version: "2.2.2" shared_preferences_linux: dependency: transitive description: name: shared_preferences_linux - sha256: "28aefc1261746e7bad3d09799496054beb84e8c4ffcdfed7734e17b4ada459a5" - url: "https://pub.dev" - source: hosted - version: "2.1.1" - shared_preferences_macos: - dependency: transitive - description: - name: shared_preferences_macos - sha256: fbb94bf296576f49be37a1496d5951796211a8db0aa22cc0d68c46440dad808c + sha256: "9d387433ca65717bbf1be88f4d5bb18f10508917a8fa2fb02e0fd0d7479a9afa" url: "https://pub.dev" source: hosted - version: "2.0.4" + version: "2.2.0" shared_preferences_platform_interface: dependency: transitive description: name: shared_preferences_platform_interface - sha256: da9431745ede5ece47bc26d5d73a9d3c6936ef6945c101a5aca46f62e52c1cf3 + sha256: fb5cf25c0235df2d0640ac1b1174f6466bd311f621574997ac59018a6664548d url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "2.2.0" shared_preferences_web: dependency: transitive description: name: shared_preferences_web - sha256: a4b5bc37fe1b368bbc81f953197d55e12f49d0296e7e412dfe2d2d77d6929958 + sha256: "74083203a8eae241e0de4a0d597dbedab3b8fef5563f33cf3c12d7e93c655ca5" url: "https://pub.dev" source: hosted - version: "2.0.4" + version: "2.1.0" shared_preferences_windows: dependency: transitive description: name: shared_preferences_windows - sha256: "97f7ab9a7da96d9cf19581f5de520ceb529548498bd6b5e0ccd02d68a0d15eba" + sha256: "5e588e2efef56916a3b229c3bfe81e6a525665a454519ca51dbcc4236a274173" url: "https://pub.dev" source: hosted - version: "2.1.1" + version: "2.2.0" sky_engine: dependency: transitive description: flutter @@ -1433,10 +1329,10 @@ packages: dependency: transitive description: name: test_api - sha256: ad540f65f92caa91bf21dfc8ffb8c589d6e4dc0c2267818b4cc2792857706206 + sha256: eb6ac1540b26de412b3403a163d919ba86f6a973fe6cc50ae3541b80092fdcfb url: "https://pub.dev" source: hosted - version: "0.4.16" + version: "0.5.1" timezone: dependency: transitive description: @@ -1481,10 +1377,10 @@ packages: dependency: transitive description: name: url_launcher_linux - sha256: "360fa359ab06bcb4f7c5cd3123a2a9a4d3364d4575d27c4b33468bd4497dd094" + sha256: "207f4ddda99b95b4d4868320a352d374b0b7e05eefad95a4a26f57da413443f5" url: "https://pub.dev" source: hosted - version: "3.0.1" + version: "3.0.5" url_launcher_macos: dependency: transitive description: @@ -1497,26 +1393,26 @@ packages: dependency: transitive description: name: url_launcher_platform_interface - sha256: "4eae912628763eb48fc214522e58e942fd16ce195407dbf45638239523c759a6" + sha256: "6c9ca697a5ae218ce56cece69d46128169a58aa8653c1b01d26fcd4aad8c4370" url: "https://pub.dev" source: hosted - version: "2.1.1" + version: "2.1.2" url_launcher_web: dependency: transitive description: name: url_launcher_web - sha256: "5669882643b96bb6d5786637cac727c6e918a790053b09245fd4513b8a07df2a" + sha256: "6bb1e5d7fe53daf02a8fee85352432a40b1f868a81880e99ec7440113d5cfcab" url: "https://pub.dev" source: hosted - version: "2.0.13" + version: "2.0.17" url_launcher_windows: dependency: transitive description: name: url_launcher_windows - sha256: e3c3b16d3104260c10eea3b0e34272aaa57921f83148b0619f74c2eced9b7ef1 + sha256: "254708f17f7c20a9c8c471f67d86d76d4a3f9c1591aad1e15292008aceb82771" url: "https://pub.dev" source: hosted - version: "3.0.1" + version: "3.0.6" uuid: dependency: transitive description: @@ -1537,42 +1433,42 @@ packages: dependency: "direct main" description: name: video_player - sha256: "32c20460c6879140dbd2728323918e5b1982125ad6517f71a01e17cdd7fa7975" + sha256: de95f0e9405f29b5582573d4166132e71f83b3158aac14e8ee5767a54f4f1fbd url: "https://pub.dev" source: hosted - version: "2.4.7" + version: "2.6.1" video_player_android: dependency: transitive description: name: video_player_android - sha256: d4d7313d1dc6f14d3414b98e2b268c3f34f4ac4ce4af51cf905e9a438edf0c77 + sha256: f338a5a396c845f4632959511cad3542cdf3167e1b2a1a948ef07f7123c03608 url: "https://pub.dev" source: hosted - version: "2.3.9" + version: "2.4.9" video_player_avfoundation: dependency: transitive description: name: video_player_avfoundation - sha256: "3df559495634bba8feb24439ac0a28a380d4ff96be7990811dc4ec81299e8cfa" + sha256: "4c274e439f349a0ee5cb3c42978393ede173a443b98f50de6ffe6900eaa19216" url: "https://pub.dev" source: hosted - version: "2.3.7" + version: "2.4.6" video_player_platform_interface: dependency: transitive description: name: video_player_platform_interface - sha256: "318a6d20577e1c78cf0bf40670883cc571ea860c72a4f7426d7dacce4bdd4343" + sha256: a8c4dcae2a7a6e7cc1d7f9808294d968eca1993af34a98e95b9bdfa959bec684 url: "https://pub.dev" source: hosted - version: "5.1.4" + version: "6.1.0" video_player_web: dependency: transitive description: name: video_player_web - sha256: ed949a3df5fe88533254bbdd242c3d8eea19ecbc4e7af90da84ef087533f584b + sha256: "44ce41424d104dfb7cf6982cc6b84af2b007a24d126406025bf40de5d481c74c" url: "https://pub.dev" source: hosted - version: "2.0.12" + version: "2.0.16" visibility_detector: dependency: transitive description: @@ -1581,54 +1477,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.2.2" - wakelock: - dependency: transitive - description: - name: wakelock - sha256: "769ecf42eb2d07128407b50cb93d7c10bd2ee48f0276ef0119db1d25cc2f87db" - url: "https://pub.dev" - source: hosted - version: "0.6.2" - wakelock_macos: - dependency: transitive - description: - name: wakelock_macos - sha256: "047c6be2f88cb6b76d02553bca5a3a3b95323b15d30867eca53a19a0a319d4cd" - url: "https://pub.dev" - source: hosted - version: "0.4.0" - wakelock_platform_interface: - dependency: transitive - description: - name: wakelock_platform_interface - sha256: "1f4aeb81fb592b863da83d2d0f7b8196067451e4df91046c26b54a403f9de621" - url: "https://pub.dev" - source: hosted - version: "0.3.0" - wakelock_web: - dependency: transitive - description: - name: wakelock_web - sha256: "1b256b811ee3f0834888efddfe03da8d18d0819317f20f6193e2922b41a501b5" - url: "https://pub.dev" - source: hosted - version: "0.4.0" - wakelock_windows: - dependency: transitive - description: - name: wakelock_windows - sha256: "857f77b3fe6ae82dd045455baa626bc4b93cb9bb6c86bf3f27c182167c3a5567" - url: "https://pub.dev" - source: hosted - version: "0.2.1" win32: dependency: transitive description: name: win32 - sha256: "9555cd63283445e101f0df32105862fdc0b30adb9b84fd0553e9433b3e074d4c" + sha256: "5a751eddf9db89b3e5f9d50c20ab8612296e4e8db69009788d6c8b060a84191c" url: "https://pub.dev" source: hosted - version: "3.0.1" + version: "4.1.4" xdg_directories: dependency: transitive description: @@ -1654,5 +1510,5 @@ packages: source: hosted version: "3.1.1" sdks: - dart: ">=2.19.1 <3.0.0" + dart: ">=3.0.0-0 <4.0.0" flutter: ">=3.3.0" diff --git a/pubspec.yaml b/pubspec.yaml index 4db15e58..8096c51d 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,44 +1,41 @@ name: mirror_fly_demo -version: 2.3.3+26 -build_release_date: Mar 10 +version: 2.3.8+31 +build_release_date: Jun 2023 publish_to: none description: A MirrorFly Flutter Sample Application. -environment: +environment: sdk: '>=2.19.1 <3.0.0' -dependencies: +dependencies: cupertino_icons: ^1.0.2 get: 4.6.5 - flutter: + flutter: sdk: flutter - shared_preferences: ^2.0.15 + shared_preferences: ^2.1.0 flutter_svg: ^1.1.5 cached_network_image: ^3.2.2 file_picker: ^5.2.0+1 #file picker fluttertoast: ^8.0.7 #toast intl: ^0.17.0 #datetime - package_info_plus: ^2.0.0 #package info + package_info_plus: ^4.0.2 #package info image_picker: ^0.8.6 - flutter_profile_picture: ^2.0.0 permission_handler: ^10.2.0 emoji_picker_flutter: ^1.4.0 image_cropping: ^0.0.13 #crop image path_provider: ^2.0.11 #path provider - video_player: ^2.4.7 + lottie: ^1.4.3 url_launcher: ^6.1.6 #url Launcher custom_image_crop: ^0.0.4 #crop image photo_view: ^0.14.0 - fluttercontactpicker: ^4.7.0 audioplayers: ^0.20.1 contacts_service: ^0.6.3 - google_maps_flutter: ^2.2.1 #google map + google_maps_flutter: ^2.3.0 #google map geolocator: ^9.0.2 #geolocator geocoding: ^2.0.5 #geocoder for address focus_detector: ^2.0.1 #focus detector record: ^3.0.0 swipe_to: ^1.0.2 - flutter_cache_manager: ^3.3.0 flutter_keyboard_visibility: ^5.4.0 keyboard_dismisser: ^3.0.0 scrollable_positioned_list: ^0.3.5 #scrollable position @@ -46,33 +43,32 @@ dependencies: firebase_core: ^2.3.0 #firebase core firebase_auth: ^4.1.4 #firebas authentication firebase_app_installations: ^0.2.1+5 #firebase installations - firebase_messaging: ^14.1.2 #firebase messaging + firebase_messaging: ^14.6.2 #firebase messaging flutter_switch: ^0.3.2 #switchbox marquee: ^2.2.0 # marquee text qr_code_scanner: ^1.0.1 #qr scanner yaml: ^3.1.1 path: ^1.8.2 - camera: ^0.10.0+4 - better_video_player: ^1.2.8 + camera: ^0.10.5+2 + video_player: ^2.6.1 internet_connection_checker: ^1.0.0+1 # connectivity check provider: ^6.0.3 - photo_manager: ^2.5.2 + photo_manager: ^2.6.0 oktoast: ^3.3.1 - google_cloud_translation: ^0.0.3 # Google Translator - grouped_list: ^5.1.2 - share_plus: ^6.3.0 + # google_cloud_translation: ^0.0.3 # Google Translator + share_plus: ^7.0.2 flutter_inappwebview: ^5.7.2+3 # inapp webview flutter_local_notifications: ^13.0.0 flutter_libphonenumber: ^1.4.0 open_file_plus: ^3.4.0 is_lock_screen: ^2.0.0 device_info_plus: ^8.1.0 - mirrorfly_plugin: ^0.0.3 # our mirrorfly plugin + mirrorfly_plugin: ^0.0.7 -dev_dependencies: +dev_dependencies: flutter_lints: 2.0.1 - flutter_test: + flutter_test: sdk: flutter flutter: diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index 8186d7f3..bf420470 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -6,12 +6,15 @@ #include "generated_plugin_registrant.h" +#include #include #include #include #include void RegisterPlugins(flutter::PluginRegistry* registry) { + FirebaseCorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); GeolocatorWindowsRegisterWithRegistrar( registry->GetRegistrarForPlugin("GeolocatorWindows")); PermissionHandlerWindowsPluginRegisterWithRegistrar( diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index fb6bd2ed..1b787fe4 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + firebase_core geolocator_windows permission_handler_windows share_plus