forked from eatvio/eatvio_app
Compare commits
108 Commits
issue-1062
...
issue-1122
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3db96a1969 | ||
| 0511bd2cb5 | |||
| 28ae75474a | |||
| da0ac9d396 | |||
| 22b8ef97b4 | |||
| 6c4572af55 | |||
| e1a1ce4b68 | |||
| 67920b2016 | |||
| ad70d0988e | |||
| 0241265b3c | |||
|
|
fc28062bb5 | ||
| f947182632 | |||
|
|
27b8128a19 | ||
| 924dc2c16a | |||
| 57536aba06 | |||
| 16084ee94c | |||
| bd1155233f | |||
| 53ce73b41e | |||
|
|
1829ad611d | ||
| 2b2991012d | |||
| 7a456c2d9d | |||
| 36079de81c | |||
| 3825a974f9 | |||
| 678d73932c | |||
| 8942e11be9 | |||
|
|
55e1633d1c | ||
| 2668907f60 | |||
| 56ab9b65f9 | |||
| 5b2ac4f228 | |||
| 51aff6c175 | |||
| cba2689406 | |||
| 5f0b7e026b | |||
| 85bc2c6d5c | |||
| f58892bdeb | |||
| f14f426381 | |||
| 6a31880a85 | |||
| 3a41a85f9d | |||
| 194b8d5b16 | |||
|
|
508c321913 | ||
|
|
4a5c67632e | ||
|
|
f6f9764811 | ||
| e2d287eb9e | |||
| cf5c42ff4b | |||
|
|
5e6e114d5d | ||
|
|
e9cfcb9637 | ||
| 28c62bf775 | |||
| 67e6526552 | |||
|
|
1c8709fc50 | ||
| dedb55ecca | |||
| 6b4c88068e | |||
|
|
d30c63be85 | ||
|
|
0ddd4c6b14 | ||
| 04dab02a6d | |||
| c45612decb | |||
|
|
2779f79464 | ||
| db293bf13f | |||
| 05eaa3caa9 | |||
|
|
d8d7a211bd | ||
| fe54037cef | |||
| e6601e2fe6 | |||
|
|
992573aead | ||
| c70c9beb20 | |||
| d2fc087699 | |||
|
|
3122394037 | ||
| 18925fd95e | |||
|
|
9916828956 | ||
| 37a787c8d0 | |||
| fb68f02ca4 | |||
|
|
8cb3a184b0 | ||
| 4b72258b1f | |||
|
|
592f387221 | ||
|
|
dcf695777a | ||
| 3b8d1bf651 | |||
|
|
141cf5543d | ||
| 40ba5f304e | |||
|
|
996cf07fb8 | ||
|
|
1766314bbe | ||
| d1575d7ac4 | |||
| 94bca6a793 | |||
|
|
a6b94f835c | ||
|
|
4c38026748 | ||
|
|
355ec2df48 | ||
| 04195dd95b | |||
|
|
d3336b1263 | ||
| 82f5c9a7fe | |||
|
|
39a512193e | ||
| 4dc5839317 | |||
|
|
da6158625f | ||
|
|
5a8f8aee3e | ||
|
|
86e9d0cc31 | ||
| 60080c7407 | |||
|
|
6d2935400a | ||
| 293601f1e1 | |||
|
|
ff17b813ac | ||
| 6a259e5452 | |||
|
|
9288a5c849 | ||
|
|
4ef174ebde | ||
|
|
1901248539 | ||
| b2e700a4eb | |||
| 61f1b76f99 | |||
| 572a6f1943 | |||
|
|
a6ae9abb57 | ||
| 431354170e | |||
|
|
c38e82f558 | ||
| afd6f9a93a | |||
|
|
641eb4d2e2 | ||
| 74c66c9600 | |||
|
|
73e89ff7a9 |
62
.gitea/ISSUE_TEMPLATE/bug_report.yml
Normal file
62
.gitea/ISSUE_TEMPLATE/bug_report.yml
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
name: "🐞 Bug Report"
|
||||||
|
description: "Report a bug to help us improve"
|
||||||
|
title: "[Bug]: "
|
||||||
|
labels: ["bug"]
|
||||||
|
body:
|
||||||
|
- type: dropdown
|
||||||
|
id: stand
|
||||||
|
attributes:
|
||||||
|
label: "Stand"
|
||||||
|
description: "Select the environment where the bug occurs"
|
||||||
|
options:
|
||||||
|
- "prod"
|
||||||
|
- "stage-dev2"
|
||||||
|
- "local"
|
||||||
|
- "all"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: dropdown
|
||||||
|
id: platform
|
||||||
|
attributes:
|
||||||
|
label: "Platform"
|
||||||
|
description: "Select the platform where the bug occurs"
|
||||||
|
options:
|
||||||
|
- "Android"
|
||||||
|
- "iPhone"
|
||||||
|
- "Huawei"
|
||||||
|
- "All"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: input
|
||||||
|
id: device_model
|
||||||
|
attributes:
|
||||||
|
label: "Device Model"
|
||||||
|
description: "Optional. Specify the device where the bug occurs"
|
||||||
|
placeholder: "e.g., Samsung Galaxy S23, iPhone 15 Pro, Huawei P60"
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
id: reproduction_steps
|
||||||
|
attributes:
|
||||||
|
label: "Steps to Reproduce"
|
||||||
|
description: "Clear numbered steps"
|
||||||
|
placeholder: "1. Click X\n2. Navigate to Y..."
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
id: expected_actual
|
||||||
|
attributes:
|
||||||
|
label: "Expected vs Actual Behavior"
|
||||||
|
description: "What should happen vs what happens"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
id: description
|
||||||
|
attributes:
|
||||||
|
label: "Description"
|
||||||
|
description: "Дополнительная информация описывающая проблему"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
5
.gitea/ISSUE_TEMPLATE/config.yml
Normal file
5
.gitea/ISSUE_TEMPLATE/config.yml
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
blank_issues_enabled: false
|
||||||
|
contact_links:
|
||||||
|
- name: "💬 Community Support"
|
||||||
|
url: "https://pepe.eatv.io/channel/general"
|
||||||
|
about: "Ask questions here"
|
||||||
26
.gitea/ISSUE_TEMPLATE/feature_request.yml
Normal file
26
.gitea/ISSUE_TEMPLATE/feature_request.yml
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
name: "✨ Feature Request"
|
||||||
|
description: "Suggest an idea for this project"
|
||||||
|
title: "[Feature]: "
|
||||||
|
labels: ["enhancement"]
|
||||||
|
body:
|
||||||
|
- type: textarea
|
||||||
|
id: use_case
|
||||||
|
attributes:
|
||||||
|
label: "Use Case"
|
||||||
|
description: "Problem solved or value added"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
id: description
|
||||||
|
attributes:
|
||||||
|
label: "Description"
|
||||||
|
description: "Дополнительная информация описывающая функциональность"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: dropdown
|
||||||
|
id: priority
|
||||||
|
attributes:
|
||||||
|
label: "Priority Level"
|
||||||
|
options: ["Low", "Medium", "High"]
|
||||||
@@ -14,7 +14,7 @@ env:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
runs-on: [ubuntu-latest]
|
runs-on: [debian-12]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: https://github.com/actions/checkout@v3
|
- uses: https://github.com/actions/checkout@v3
|
||||||
@@ -155,10 +155,10 @@ jobs:
|
|||||||
|
|
||||||
- name: Get dependencies
|
- name: Get dependencies
|
||||||
run: |
|
run: |
|
||||||
flutter clean
|
flutter clean
|
||||||
flutter pub cache repair
|
flutter pub cache repair
|
||||||
flutter pub get
|
flutter pub get
|
||||||
dart run build_runner build --delete-conflicting-outputs
|
dart run build_runner build --delete-conflicting-outputs
|
||||||
|
|
||||||
- name: Native Analyze
|
- name: Native Analyze
|
||||||
run: flutter analyze
|
run: flutter analyze
|
||||||
|
|||||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -16,6 +16,8 @@
|
|||||||
*.mocks.dart
|
*.mocks.dart
|
||||||
android/build/
|
android/build/
|
||||||
ios/XCBuildData/
|
ios/XCBuildData/
|
||||||
|
docs/
|
||||||
|
specs/
|
||||||
env/.env
|
env/.env
|
||||||
.env
|
.env
|
||||||
android/key.properties
|
android/key.properties
|
||||||
@@ -25,4 +27,4 @@ backend/
|
|||||||
.fvm/
|
.fvm/
|
||||||
.fvmrc
|
.fvmrc
|
||||||
/eatvio
|
/eatvio
|
||||||
*.code-workspace
|
*.code-workspace
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ android {
|
|||||||
versionName = flutter.versionName
|
versionName = flutter.versionName
|
||||||
manifestPlaceholders = [
|
manifestPlaceholders = [
|
||||||
YANDEX_CLIENT_ID: yandexClientId,
|
YANDEX_CLIENT_ID: yandexClientId,
|
||||||
applicationName: "io.flutter.app.FlutterApplication"
|
applicationName: "com.eatvioapp.app.EatvioApplication"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,6 +69,7 @@ android {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
|
testImplementation 'junit:junit:4.13.2'
|
||||||
implementation platform('com.google.firebase:firebase-bom:34.4.0')
|
implementation platform('com.google.firebase:firebase-bom:34.4.0')
|
||||||
implementation 'com.google.firebase:firebase-messaging'
|
implementation 'com.google.firebase:firebase-messaging'
|
||||||
implementation 'com.huawei.agconnect:agconnect-core:1.9.5.300'
|
implementation 'com.huawei.agconnect:agconnect-core:1.9.5.300'
|
||||||
|
|||||||
@@ -87,8 +87,11 @@
|
|||||||
android:name="flutterEmbedding"
|
android:name="flutterEmbedding"
|
||||||
android:value="2" />
|
android:value="2" />
|
||||||
|
|
||||||
<!-- Tap on notification body opens CallkitIncomingActivity via PendingIntent.
|
<!-- The incoming notification's content intent and full-screen intent both open
|
||||||
Replace it with a bridge that routes to the same accept flow as Answer. -->
|
CallkitIncomingActivity. Replace it with a bridge: a tap on an unlocked phone
|
||||||
|
routes to the same accept flow as Answer; on a locked/dark screen it shows a
|
||||||
|
ringing screen that wakes the device. Own task affinity keeps the plugin's
|
||||||
|
CLEAR_TASK flag from killing MainActivity. -->
|
||||||
<activity
|
<activity
|
||||||
android:name="com.hiennv.flutter_callkit_incoming.CallkitIncomingActivity"
|
android:name="com.hiennv.flutter_callkit_incoming.CallkitIncomingActivity"
|
||||||
tools:node="remove" />
|
tools:node="remove" />
|
||||||
@@ -97,20 +100,26 @@
|
|||||||
android:name=".EatvioCallkitIncomingBridgeActivity"
|
android:name=".EatvioCallkitIncomingBridgeActivity"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:theme="@android:style/Theme.Translucent.NoTitleBar"
|
android:theme="@android:style/Theme.Translucent.NoTitleBar"
|
||||||
|
android:taskAffinity=""
|
||||||
|
android:allowTaskReparenting="false"
|
||||||
android:excludeFromRecents="true"
|
android:excludeFromRecents="true"
|
||||||
android:noHistory="true"
|
android:noHistory="true"
|
||||||
|
android:showWhenLocked="true"
|
||||||
android:turnScreenOn="true"
|
android:turnScreenOn="true"
|
||||||
android:launchMode="singleTop"
|
android:launchMode="singleInstance"
|
||||||
android:configChanges="orientation" />
|
android:configChanges="orientation" />
|
||||||
|
|
||||||
<activity-alias
|
<activity-alias
|
||||||
android:name="com.hiennv.flutter_callkit_incoming.CallkitIncomingActivity"
|
android:name="com.hiennv.flutter_callkit_incoming.CallkitIncomingActivity"
|
||||||
android:targetActivity=".EatvioCallkitIncomingBridgeActivity"
|
android:targetActivity=".EatvioCallkitIncomingBridgeActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
|
android:taskAffinity=""
|
||||||
|
android:allowTaskReparenting="false"
|
||||||
android:excludeFromRecents="true"
|
android:excludeFromRecents="true"
|
||||||
android:noHistory="true"
|
android:noHistory="true"
|
||||||
|
android:showWhenLocked="true"
|
||||||
android:turnScreenOn="true"
|
android:turnScreenOn="true"
|
||||||
android:launchMode="singleTop"
|
android:launchMode="singleInstance"
|
||||||
android:configChanges="orientation"
|
android:configChanges="orientation"
|
||||||
android:permission="${applicationId}.PERMISSION_CALL">
|
android:permission="${applicationId}.PERMISSION_CALL">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
|
|||||||
@@ -13,14 +13,12 @@ object CallKitAcceptIntentMapper {
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return hashMapOf(
|
return payloadMap(data, action)
|
||||||
"action" to action,
|
}
|
||||||
"id" to data.getString(CallkitConstants.EXTRA_CALLKIT_ID, ""),
|
|
||||||
"handle" to data.getString(CallkitConstants.EXTRA_CALLKIT_HANDLE, ""),
|
fun declinePayloadFromBundle(data: Bundle, action: String): Map<String, Any?>? {
|
||||||
"nameCaller" to data.getString(CallkitConstants.EXTRA_CALLKIT_NAME_CALLER, ""),
|
if (!action.contains(CallkitConstants.ACTION_CALL_DECLINE)) return null
|
||||||
"avatar" to data.getString(CallkitConstants.EXTRA_CALLKIT_AVATAR, ""),
|
return payloadMap(data, action)
|
||||||
"extra" to data.getSerializable(CallkitConstants.EXTRA_CALLKIT_EXTRA),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun payloadFromIntent(intent: Intent?): Map<String, Any?>? {
|
fun payloadFromIntent(intent: Intent?): Map<String, Any?>? {
|
||||||
@@ -35,6 +33,16 @@ object CallKitAcceptIntentMapper {
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return payloadMap(data, action)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearCallKitLaunchIntent(intent: Intent?) {
|
||||||
|
if (intent == null) return
|
||||||
|
intent.removeExtra(FlutterCallkitIncomingPlugin.EXTRA_CALLKIT_CALL_DATA)
|
||||||
|
intent.action = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun payloadMap(data: Bundle, action: String): Map<String, Any?> {
|
||||||
return hashMapOf(
|
return hashMapOf(
|
||||||
"action" to action,
|
"action" to action,
|
||||||
"id" to data.getString(CallkitConstants.EXTRA_CALLKIT_ID, ""),
|
"id" to data.getString(CallkitConstants.EXTRA_CALLKIT_ID, ""),
|
||||||
@@ -44,10 +52,4 @@ object CallKitAcceptIntentMapper {
|
|||||||
"extra" to data.getSerializable(CallkitConstants.EXTRA_CALLKIT_EXTRA),
|
"extra" to data.getSerializable(CallkitConstants.EXTRA_CALLKIT_EXTRA),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun clearCallKitLaunchIntent(intent: Intent?) {
|
|
||||||
if (intent == null) return
|
|
||||||
intent.removeExtra(FlutterCallkitIncomingPlugin.EXTRA_CALLKIT_CALL_DATA)
|
|
||||||
intent.action = null
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,10 +8,20 @@ import com.hiennv.flutter_callkit_incoming.CallkitIncomingBroadcastReceiver
|
|||||||
|
|
||||||
object CallKitIntentBridge {
|
object CallKitIntentBridge {
|
||||||
fun dispatchCallKitAction(context: Context, action: String, data: Bundle?) {
|
fun dispatchCallKitAction(context: Context, action: String, data: Bundle?) {
|
||||||
|
if (IncomingCallRingtonePolicy.actionStopsRingtone(action)) {
|
||||||
|
VideoCallPushBridge.silenceIncomingCall(context)
|
||||||
|
}
|
||||||
|
|
||||||
if (data != null) {
|
if (data != null) {
|
||||||
CallKitAcceptIntentMapper.payloadFromBundle(data, action)?.let { payload ->
|
CallKitAcceptIntentMapper.payloadFromBundle(data, action)?.let { payload ->
|
||||||
PendingCallKitAcceptBridge.store(payload)
|
PendingCallKitAcceptBridge.store(payload)
|
||||||
}
|
}
|
||||||
|
CallKitAcceptIntentMapper.declinePayloadFromBundle(data, action)?.let { payload ->
|
||||||
|
PendingCallKitDeclineBridge.store(payload)
|
||||||
|
if (MainActivity.isInForeground) {
|
||||||
|
MainActivity.onPendingDecline?.invoke()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val broadcastIntent = CallkitIncomingBroadcastReceiver.getIntent(context, action, data)
|
val broadcastIntent = CallkitIncomingBroadcastReceiver.getIntent(context, action, data)
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.eatvioapp.app
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
|
||||||
|
class EatvioApplication : Application() {
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
VideoCallDeclineReporter.install(this)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,71 @@
|
|||||||
package com.eatvioapp.app
|
package com.eatvioapp.app
|
||||||
|
|
||||||
import android.app.Activity
|
import android.app.Activity
|
||||||
|
import android.app.KeyguardManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.ActivityInfo
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.os.PowerManager
|
||||||
|
import android.util.Log
|
||||||
|
import android.view.View
|
||||||
|
import android.view.WindowManager
|
||||||
|
import android.view.ViewGroup.MarginLayoutParams
|
||||||
|
import android.widget.ImageView
|
||||||
|
import android.widget.LinearLayout
|
||||||
|
import android.widget.TextView
|
||||||
|
import com.hiennv.flutter_callkit_incoming.AppUtils
|
||||||
import com.hiennv.flutter_callkit_incoming.CallkitConstants
|
import com.hiennv.flutter_callkit_incoming.CallkitConstants
|
||||||
|
import com.hiennv.flutter_callkit_incoming.CallkitNotificationManager
|
||||||
|
import com.hiennv.flutter_callkit_incoming.ImageLoaderProvider
|
||||||
|
import com.hiennv.flutter_callkit_incoming.Utils
|
||||||
|
import com.hiennv.flutter_callkit_incoming.widgets.RippleRelativeLayout
|
||||||
|
import java.lang.ref.WeakReference
|
||||||
|
import kotlin.math.abs
|
||||||
|
import com.hiennv.flutter_callkit_incoming.R as CallkitR
|
||||||
|
|
||||||
/// Redirects notification body / full-screen intent taps to the same accept path as
|
/// Target of the incoming notification's content intent and full-screen intent.
|
||||||
/// the Answer button, instead of showing the native Callkit incoming UI.
|
///
|
||||||
|
/// Unlocked, lit screen: the user tapped the notification body, route it to the same
|
||||||
|
/// accept flow as the Answer button.
|
||||||
|
///
|
||||||
|
/// Locked or dark screen: Android fired the full-screen intent on its own, so show a
|
||||||
|
/// ringing screen that wakes the device and lets the user answer or decline.
|
||||||
class EatvioCallkitIncomingBridgeActivity : Activity() {
|
class EatvioCallkitIncomingBridgeActivity : Activity() {
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "EatvioIncomingBridge"
|
||||||
|
private const val WAKE_LOCK_TAG = "eatvio:incoming_call"
|
||||||
|
private const val DEFAULT_RING_DURATION_MS = 45_000L
|
||||||
|
private const val MIN_RING_SCREEN_MS = 1_000L
|
||||||
|
|
||||||
|
private val mainHandler = Handler(Looper.getMainLooper())
|
||||||
|
private var ringingScreen: WeakReference<EatvioCallkitIncomingBridgeActivity>? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Closes the ringing screen once the call stopped ringing: answered or declined
|
||||||
|
* from the notification, timed out, or ended by the caller.
|
||||||
|
*/
|
||||||
|
fun dismissRingingScreen() {
|
||||||
|
mainHandler.post {
|
||||||
|
ringingScreen?.get()?.closeRingingScreen()
|
||||||
|
ringingScreen = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun shouldShowRingingScreen(keyguardLocked: Boolean, screenInteractive: Boolean): Boolean {
|
||||||
|
return keyguardLocked || !screenInteractive
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var callData: Bundle? = null
|
||||||
|
private var wakeLock: PowerManager.WakeLock? = null
|
||||||
|
private var ringTimeout: Runnable? = null
|
||||||
|
private var actionTaken = false
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
|
|
||||||
@@ -15,15 +74,256 @@ class EatvioCallkitIncomingBridgeActivity : Activity() {
|
|||||||
finish()
|
finish()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
callData = data
|
||||||
|
|
||||||
CallKitIntentBridge.dispatchCallKitAction(
|
if (!launchedOnLockedOrDarkScreen()) {
|
||||||
this,
|
Log.i(TAG, "tap on notification body: accept")
|
||||||
CallkitConstants.ACTION_CALL_ACCEPT,
|
CallKitIntentBridge.dispatchCallKitAction(this, CallkitConstants.ACTION_CALL_ACCEPT, data)
|
||||||
data,
|
finish()
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
overridePendingTransition(0, 0)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
Log.i(TAG, "full-screen intent on locked/dark screen: show ringing screen")
|
||||||
|
showRingingScreen(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onNewIntent(intent: Intent) {
|
||||||
|
super.onNewIntent(intent)
|
||||||
|
setIntent(intent)
|
||||||
|
val data = intent.extras?.getBundle(CallkitConstants.EXTRA_CALLKIT_INCOMING_DATA) ?: return
|
||||||
|
if (ringingScreen?.get() !== this) return
|
||||||
|
callData = data
|
||||||
|
bindCallData(data)
|
||||||
|
scheduleRingTimeout(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
cancelRingTimeout()
|
||||||
|
releaseWakeLock()
|
||||||
|
if (ringingScreen?.get() === this) {
|
||||||
|
ringingScreen = null
|
||||||
|
}
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Deprecated("Deprecated in Java")
|
||||||
|
override fun onBackPressed() {
|
||||||
|
// The ringing screen is dismissed by Answer / Decline / timeout only.
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun launchedOnLockedOrDarkScreen(): Boolean {
|
||||||
|
val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
|
||||||
|
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||||
|
return shouldShowRingingScreen(
|
||||||
|
keyguardLocked = keyguardManager.isKeyguardLocked,
|
||||||
|
screenInteractive = powerManager.isInteractive,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showRingingScreen(data: Bundle) {
|
||||||
|
ringingScreen = WeakReference(this)
|
||||||
|
|
||||||
|
setTheme(CallkitR.style.CallkitIncomingTheme)
|
||||||
|
requestedOrientation = if (Utils.isTablet(this)) {
|
||||||
|
ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
|
||||||
|
} else {
|
||||||
|
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
|
||||||
|
}
|
||||||
|
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
|
||||||
|
setTurnScreenOn(true)
|
||||||
|
setShowWhenLocked(true)
|
||||||
|
} else {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
window.addFlags(
|
||||||
|
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON or
|
||||||
|
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
||||||
|
window.statusBarColor = Color.TRANSPARENT
|
||||||
|
window.navigationBarColor = Color.TRANSPARENT
|
||||||
|
}
|
||||||
|
|
||||||
|
acquireWakeLock(ringDuration(data))
|
||||||
|
VideoCallPushBridge.keepRingingOnFullScreen()
|
||||||
|
|
||||||
|
setContentView(CallkitR.layout.activity_callkit_incoming)
|
||||||
|
bindCallData(data)
|
||||||
|
scheduleRingTimeout(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun bindCallData(data: Bundle) {
|
||||||
|
val background: ImageView = findViewById(CallkitR.id.ivBackground)
|
||||||
|
val ripple: RippleRelativeLayout = findViewById(CallkitR.id.llBackgroundAnimation)
|
||||||
|
val callerName: TextView = findViewById(CallkitR.id.tvNameCaller)
|
||||||
|
val callerNumber: TextView = findViewById(CallkitR.id.tvNumber)
|
||||||
|
val logo: ImageView = findViewById(CallkitR.id.ivLogo)
|
||||||
|
val avatar: ImageView = findViewById(CallkitR.id.ivAvatar)
|
||||||
|
val actions: LinearLayout = findViewById(CallkitR.id.llAction)
|
||||||
|
val acceptButton: ImageView = findViewById(CallkitR.id.ivAcceptCall)
|
||||||
|
val acceptLabel: TextView = findViewById(CallkitR.id.tvAccept)
|
||||||
|
val declineButton: ImageView = findViewById(CallkitR.id.ivDeclineCall)
|
||||||
|
val declineLabel: TextView = findViewById(CallkitR.id.tvDecline)
|
||||||
|
|
||||||
|
ripple.layoutParams.height = Utils.getScreenWidth() + Utils.getStatusBarHeight(this)
|
||||||
|
ripple.startRippleAnimation()
|
||||||
|
(actions.layoutParams as? MarginLayoutParams)?.let { params ->
|
||||||
|
params.setMargins(0, 0, 0, Utils.getNavigationBarHeight(this))
|
||||||
|
actions.layoutParams = params
|
||||||
|
}
|
||||||
|
|
||||||
|
callerName.text = data.getString(CallkitConstants.EXTRA_CALLKIT_NAME_CALLER, "")
|
||||||
|
callerNumber.visibility = View.INVISIBLE
|
||||||
|
logo.visibility = View.INVISIBLE
|
||||||
|
|
||||||
|
val textColor = parseColor(data.getString(CallkitConstants.EXTRA_CALLKIT_TEXT_COLOR), Color.WHITE)
|
||||||
|
callerName.setTextColor(textColor)
|
||||||
|
acceptLabel.setTextColor(textColor)
|
||||||
|
declineLabel.setTextColor(textColor)
|
||||||
|
background.setBackgroundColor(
|
||||||
|
parseColor(data.getString(CallkitConstants.EXTRA_CALLKIT_BACKGROUND_COLOR), Color.parseColor("#0955fa")),
|
||||||
)
|
)
|
||||||
|
|
||||||
finish()
|
val avatarUrl = data.getString(CallkitConstants.EXTRA_CALLKIT_AVATAR, "")
|
||||||
@Suppress("DEPRECATION")
|
if (!avatarUrl.isNullOrEmpty()) {
|
||||||
overridePendingTransition(0, 0)
|
avatar.visibility = View.VISIBLE
|
||||||
|
@Suppress("DEPRECATION", "UNCHECKED_CAST")
|
||||||
|
val headers = data.getSerializable(CallkitConstants.EXTRA_CALLKIT_HEADERS) as? HashMap<String, Any?>
|
||||||
|
try {
|
||||||
|
ImageLoaderProvider.loadImage(this, avatarUrl, headers, CallkitR.drawable.ic_default_avatar, avatar)
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(TAG, "failed to load caller avatar", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.getInt(CallkitConstants.EXTRA_CALLKIT_TYPE, 0) > 0) {
|
||||||
|
acceptButton.setImageResource(CallkitR.drawable.ic_video)
|
||||||
|
}
|
||||||
|
acceptButton.background = AppUtils.createCircleDrawable(
|
||||||
|
parseColor(data.getString(CallkitConstants.EXTRA_CALLKIT_ACCEPT_COLOR), Color.parseColor("#4CAF50")),
|
||||||
|
)
|
||||||
|
declineButton.background = AppUtils.createCircleDrawable(
|
||||||
|
parseColor(data.getString(CallkitConstants.EXTRA_CALLKIT_DECLINE_COLOR), Color.parseColor("#F44336")),
|
||||||
|
)
|
||||||
|
|
||||||
|
val acceptText = data.getString(CallkitConstants.EXTRA_CALLKIT_TEXT_ACCEPT, "")
|
||||||
|
acceptLabel.text = if (acceptText.isNullOrEmpty()) getString(CallkitR.string.text_accept) else acceptText
|
||||||
|
val declineText = data.getString(CallkitConstants.EXTRA_CALLKIT_TEXT_DECLINE, "")
|
||||||
|
declineLabel.text = if (declineText.isNullOrEmpty()) getString(CallkitR.string.text_decline) else declineText
|
||||||
|
|
||||||
|
acceptButton.setOnClickListener { onAcceptClick() }
|
||||||
|
declineButton.setOnClickListener { onDeclineClick() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onAcceptClick() {
|
||||||
|
val data = callData ?: return
|
||||||
|
if (actionTaken) return
|
||||||
|
actionTaken = true
|
||||||
|
cancelRingTimeout()
|
||||||
|
Log.i(TAG, "ringing screen: accept")
|
||||||
|
|
||||||
|
// Same order as the plugin's own incoming activity: dispatch the accept, then ask
|
||||||
|
// the keyguard to unlock so MainActivity (which cannot show over the keyguard)
|
||||||
|
// becomes visible as soon as the user unlocks.
|
||||||
|
CallKitIntentBridge.dispatchCallKitAction(this, CallkitConstants.ACTION_CALL_ACCEPT, data)
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
|
||||||
|
if (keyguardManager.isKeyguardLocked) {
|
||||||
|
keyguardManager.requestDismissKeyguard(this, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finishRingingTask()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onDeclineClick() {
|
||||||
|
val data = callData ?: return
|
||||||
|
if (actionTaken) return
|
||||||
|
actionTaken = true
|
||||||
|
cancelRingTimeout()
|
||||||
|
Log.i(TAG, "ringing screen: decline")
|
||||||
|
|
||||||
|
CallKitIntentBridge.dispatchCallKitAction(this, CallkitConstants.ACTION_CALL_DECLINE, data)
|
||||||
|
finishRingingTask()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun closeRingingScreen() {
|
||||||
|
if (isFinishing) return
|
||||||
|
cancelRingTimeout()
|
||||||
|
finishRingingTask()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun finishRingingTask() {
|
||||||
|
if (isFinishing) return
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
||||||
|
finishAndRemoveTask()
|
||||||
|
} else {
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ringDuration(data: Bundle): Long {
|
||||||
|
val duration = data.getLong(CallkitConstants.EXTRA_CALLKIT_DURATION, DEFAULT_RING_DURATION_MS)
|
||||||
|
return if (duration > 0L) duration else DEFAULT_RING_DURATION_MS
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The notification was posted before this screen appeared, so ring only for the
|
||||||
|
* remaining part of the call duration.
|
||||||
|
*/
|
||||||
|
private fun scheduleRingTimeout(data: Bundle) {
|
||||||
|
cancelRingTimeout()
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
val startedAt = data.getLong(CallkitNotificationManager.EXTRA_TIME_START_CALL, now)
|
||||||
|
val remaining = (ringDuration(data) - abs(now - startedAt)).coerceAtLeast(MIN_RING_SCREEN_MS)
|
||||||
|
val timeout = Runnable {
|
||||||
|
Log.i(TAG, "ringing screen: timed out")
|
||||||
|
closeRingingScreen()
|
||||||
|
}
|
||||||
|
ringTimeout = timeout
|
||||||
|
mainHandler.postDelayed(timeout, remaining)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cancelRingTimeout() {
|
||||||
|
ringTimeout?.let { mainHandler.removeCallbacks(it) }
|
||||||
|
ringTimeout = null
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
private fun acquireWakeLock(durationMs: Long) {
|
||||||
|
try {
|
||||||
|
val powerManager = applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||||
|
val lock = powerManager.newWakeLock(
|
||||||
|
PowerManager.SCREEN_BRIGHT_WAKE_LOCK or
|
||||||
|
PowerManager.ACQUIRE_CAUSES_WAKEUP or
|
||||||
|
PowerManager.ON_AFTER_RELEASE,
|
||||||
|
WAKE_LOCK_TAG,
|
||||||
|
)
|
||||||
|
lock.acquire(durationMs)
|
||||||
|
wakeLock = lock
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(TAG, "failed to acquire wake lock", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun releaseWakeLock() {
|
||||||
|
val lock = wakeLock ?: return
|
||||||
|
wakeLock = null
|
||||||
|
try {
|
||||||
|
if (lock.isHeld) lock.release()
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(TAG, "failed to release wake lock", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseColor(value: String?, fallback: Int): Int {
|
||||||
|
if (value.isNullOrBlank()) return fallback
|
||||||
|
return try {
|
||||||
|
Color.parseColor(value)
|
||||||
|
} catch (error: IllegalArgumentException) {
|
||||||
|
fallback
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ class EatvioFcmMessagingService : FirebaseMessagingService() {
|
|||||||
Log.i(TAG, "onMessageReceived: ${message.data}")
|
Log.i(TAG, "onMessageReceived: ${message.data}")
|
||||||
|
|
||||||
if (VideoCallPushBridge.isEndedVideoCall(message.data)) {
|
if (VideoCallPushBridge.isEndedVideoCall(message.data)) {
|
||||||
VideoCallPushBridge.dismissAllIncomingCalls(this)
|
VideoCallPushBridge.dismissEndedVideoCall(this, message.data)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ class HmsPushService : HmsMessageService() {
|
|||||||
if (message == null) return
|
if (message == null) return
|
||||||
|
|
||||||
if (VideoCallPushBridge.isEndedVideoCall(message.dataOfMap)) {
|
if (VideoCallPushBridge.isEndedVideoCall(message.dataOfMap)) {
|
||||||
VideoCallPushBridge.dismissAllIncomingCalls(this)
|
VideoCallPushBridge.dismissEndedVideoCall(this, message.dataOfMap)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package com.eatvioapp.app
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Call actions that must stop the incoming ringtone.
|
||||||
|
* Accept is included: answering the call is not the same as ending it,
|
||||||
|
* but the ringing player is a separate object from the in-call audio.
|
||||||
|
*/
|
||||||
|
internal object IncomingCallRingtonePolicy {
|
||||||
|
fun actionStopsRingtone(action: String): Boolean {
|
||||||
|
return action.contains("ACTION_CALL_ACCEPT") ||
|
||||||
|
action.contains("ACTION_CALL_DECLINE") ||
|
||||||
|
action.contains("ACTION_CALL_ENDED") ||
|
||||||
|
action.contains("ACTION_CALL_TIMEOUT")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,6 +25,9 @@ class MainActivity: FlutterActivity() {
|
|||||||
@JvmStatic
|
@JvmStatic
|
||||||
var isInForeground: Boolean = false
|
var isInForeground: Boolean = false
|
||||||
private set
|
private set
|
||||||
|
|
||||||
|
@JvmStatic
|
||||||
|
var onPendingDecline: (() -> Unit)? = null
|
||||||
}
|
}
|
||||||
|
|
||||||
private val channelName = "com.eatvioapp/hms_push"
|
private val channelName = "com.eatvioapp/hms_push"
|
||||||
@@ -38,13 +41,18 @@ class MainActivity: FlutterActivity() {
|
|||||||
override fun onResume() {
|
override fun onResume() {
|
||||||
super.onResume()
|
super.onResume()
|
||||||
isInForeground = true
|
isInForeground = true
|
||||||
|
onPendingDecline = { scheduleDeliverPendingCallKitDecline() }
|
||||||
captureCallKitLaunchIntent(intent)
|
captureCallKitLaunchIntent(intent)
|
||||||
if (PendingCallKitAcceptBridge.peek() != null) {
|
if (PendingCallKitAcceptBridge.peek() != null) {
|
||||||
scheduleDeliverPendingCallKitAccept()
|
scheduleDeliverPendingCallKitAccept()
|
||||||
}
|
}
|
||||||
|
if (PendingCallKitDeclineBridge.peek() != null) {
|
||||||
|
scheduleDeliverPendingCallKitDecline()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onPause() {
|
override fun onPause() {
|
||||||
|
onPendingDecline = null
|
||||||
isInForeground = false
|
isInForeground = false
|
||||||
super.onPause()
|
super.onPause()
|
||||||
}
|
}
|
||||||
@@ -55,22 +63,50 @@ class MainActivity: FlutterActivity() {
|
|||||||
methodChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channelName)
|
methodChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channelName)
|
||||||
videoCallPipChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, videoCallPipChannelName)
|
videoCallPipChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, videoCallPipChannelName)
|
||||||
videoCallPushChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, videoCallPushChannelName)
|
videoCallPushChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, videoCallPushChannelName)
|
||||||
|
onPendingDecline = { scheduleDeliverPendingCallKitDecline() }
|
||||||
videoCallPushChannel?.setMethodCallHandler { call, result ->
|
videoCallPushChannel?.setMethodCallHandler { call, result ->
|
||||||
when (call.method) {
|
when (call.method) {
|
||||||
"dismissIncomingCalls" -> {
|
"dismissIncomingCalls" -> {
|
||||||
try {
|
try {
|
||||||
VideoCallPushBridge.dismissAllIncomingCalls(applicationContext)
|
val args = call.arguments as? Map<*, *>
|
||||||
|
val callId = args?.get("call_id")?.toString()
|
||||||
|
?: args?.get("callId")?.toString()
|
||||||
|
val conversationUuid = args?.get("conversation_uuid")?.toString()
|
||||||
|
?: args?.get("conversationUuid")?.toString()
|
||||||
|
VideoCallPushBridge.dismissIncomingCalls(
|
||||||
|
applicationContext,
|
||||||
|
callId = callId,
|
||||||
|
conversationUuid = conversationUuid,
|
||||||
|
)
|
||||||
result.success(null)
|
result.success(null)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
result.error("DISMISS_INCOMING_CALLS_FAILED", e.message, null)
|
result.error("DISMISS_INCOMING_CALLS_FAILED", e.message, null)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
"showIncomingCall" -> {
|
||||||
|
try {
|
||||||
|
val args = call.arguments as? Map<*, *> ?: emptyMap<Any, Any>()
|
||||||
|
val data = HashMap<String, String>()
|
||||||
|
for ((key, value) in args) {
|
||||||
|
val name = key as? String ?: continue
|
||||||
|
if (value == null) continue
|
||||||
|
data[name] = value.toString()
|
||||||
|
}
|
||||||
|
VideoCallPushBridge.showIncomingCall(applicationContext, data)
|
||||||
|
result.success(null)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
result.error("SHOW_INCOMING_CALL_FAILED", e.message, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
"drainPendingCallKitAccept" -> {
|
"drainPendingCallKitAccept" -> {
|
||||||
result.success(PendingCallKitAcceptBridge.drain())
|
result.success(PendingCallKitAcceptBridge.drain())
|
||||||
}
|
}
|
||||||
"peekPendingCallKitAccept" -> {
|
"peekPendingCallKitAccept" -> {
|
||||||
result.success(PendingCallKitAcceptBridge.peekPending())
|
result.success(PendingCallKitAcceptBridge.peekPending())
|
||||||
}
|
}
|
||||||
|
"drainPendingCallKitDecline" -> {
|
||||||
|
result.success(PendingCallKitDeclineBridge.drain())
|
||||||
|
}
|
||||||
else -> result.notImplemented()
|
else -> result.notImplemented()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -226,6 +262,30 @@ class MainActivity: FlutterActivity() {
|
|||||||
channel.invokeMethod("onCallKitLaunchIntent", payload)
|
channel.invokeMethod("onCallKitLaunchIntent", payload)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun scheduleDeliverPendingCallKitDecline() {
|
||||||
|
PendingCallKitDeclineBridge.scheduleDeliverToFlutter(
|
||||||
|
deliver = { deliverPendingCallKitDeclineToFlutter() },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun deliverPendingCallKitDeclineToFlutter() {
|
||||||
|
val payload = PendingCallKitDeclineBridge.peek() ?: return
|
||||||
|
val channel = videoCallPushChannel
|
||||||
|
if (channel == null) {
|
||||||
|
android.util.Log.w(
|
||||||
|
"VideoCallPush",
|
||||||
|
"deliverPendingCallKitDeclineToFlutter: channel not ready",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
android.util.Log.i(
|
||||||
|
"VideoCallPush",
|
||||||
|
"deliverPendingCallKitDeclineToFlutter: id=${payload["id"]}",
|
||||||
|
)
|
||||||
|
channel.invokeMethod("onCallKitDecline", payload)
|
||||||
|
}
|
||||||
|
|
||||||
private fun handleIntentForActionUrl(intent: Intent?) {
|
private fun handleIntentForActionUrl(intent: Intent?) {
|
||||||
if (intent == null) return
|
if (intent == null) return
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package com.eatvioapp.app
|
||||||
|
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.util.Log
|
||||||
|
|
||||||
|
/// Stores a decline until Flutter can POST /video-call/decline.
|
||||||
|
///
|
||||||
|
/// The plugin broadcasts the decline. If the Flutter engine is not attached,
|
||||||
|
/// that broadcast never reaches the backend and the call keeps ringing on the
|
||||||
|
/// user's other devices.
|
||||||
|
object PendingCallKitDeclineBridge {
|
||||||
|
private const val TAG = "PendingCallKitDecline"
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var pendingPayload: Map<String, Any?>? = null
|
||||||
|
|
||||||
|
private val mainHandler = Handler(Looper.getMainLooper())
|
||||||
|
|
||||||
|
fun store(payload: Map<String, Any?>) {
|
||||||
|
pendingPayload = payload
|
||||||
|
Log.i(TAG, "stored pending decline id=${payload["id"]}")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun peek(): Map<String, Any?>? = pendingPayload
|
||||||
|
|
||||||
|
fun drain(): Map<String, Any?>? {
|
||||||
|
val payload = pendingPayload
|
||||||
|
pendingPayload = null
|
||||||
|
if (payload != null) {
|
||||||
|
Log.i(TAG, "drained pending decline id=${payload["id"]}")
|
||||||
|
}
|
||||||
|
return payload
|
||||||
|
}
|
||||||
|
|
||||||
|
fun scheduleDeliverToFlutter(
|
||||||
|
deliver: () -> Unit,
|
||||||
|
delaysMs: LongArray = longArrayOf(0L, 250L, 700L, 1500L, 2800L, 4200L, 6000L),
|
||||||
|
) {
|
||||||
|
for (delayMs in delaysMs) {
|
||||||
|
mainHandler.postDelayed({ deliver() }, delayMs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package com.eatvioapp.app
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import java.net.HttpURLConnection
|
||||||
|
import java.net.URL
|
||||||
|
|
||||||
|
internal object FlutterSharedPrefs {
|
||||||
|
const val NAME = "FlutterSharedPreferences"
|
||||||
|
private const val PREFIX = "flutter."
|
||||||
|
|
||||||
|
fun string(context: Context, key: String): String? {
|
||||||
|
return context
|
||||||
|
.getSharedPreferences(NAME, Context.MODE_PRIVATE)
|
||||||
|
.getString(PREFIX + key, null)
|
||||||
|
?.trim()
|
||||||
|
?.takeIf { it.isNotEmpty() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal object VideoCallDeclineClient {
|
||||||
|
private const val TAG = "VideoCallDecline"
|
||||||
|
private const val TIMEOUT_MS = 4_000
|
||||||
|
|
||||||
|
fun send(context: Context, handle: String?, extra: Map<*, *>?) {
|
||||||
|
val fields = VideoCallDeclineRequestFactory.fields(handle, extra)
|
||||||
|
val baseUrl = FlutterSharedPrefs.string(context, "apiBaseUrl")
|
||||||
|
?: FlutterSharedPrefs.string(context, "customBaseUrl")
|
||||||
|
val request = VideoCallDeclineRequestFactory.build(
|
||||||
|
baseUrl = baseUrl,
|
||||||
|
token = FlutterSharedPrefs.string(context, "token"),
|
||||||
|
hwId = FlutterSharedPrefs.string(context, "eatvio.android_install_hw_id"),
|
||||||
|
fields = fields,
|
||||||
|
)
|
||||||
|
if (request == null) {
|
||||||
|
Log.w(
|
||||||
|
TAG,
|
||||||
|
"skip decline POST conversation=${fields.conversationUuid} ended=${fields.endedPush}",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
val code = post(request)
|
||||||
|
Log.i(TAG, "decline POST status=$code conversation=${fields.conversationUuid}")
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(TAG, "decline POST failed conversation=${fields.conversationUuid}", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun post(request: VideoCallDeclineRequest): Int {
|
||||||
|
val connection = (URL(request.url).openConnection() as HttpURLConnection).apply {
|
||||||
|
requestMethod = "POST"
|
||||||
|
connectTimeout = TIMEOUT_MS
|
||||||
|
readTimeout = TIMEOUT_MS
|
||||||
|
doOutput = true
|
||||||
|
setRequestProperty("Authorization", "Bearer ${request.token}")
|
||||||
|
setRequestProperty("Accept", "application/json")
|
||||||
|
setRequestProperty("Content-Type", "application/json; charset=utf-8")
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
connection.outputStream.use { stream ->
|
||||||
|
stream.write(request.body.toByteArray(Charsets.UTF_8))
|
||||||
|
}
|
||||||
|
val code = connection.responseCode
|
||||||
|
val response = if (code in 200..299) connection.inputStream else connection.errorStream
|
||||||
|
response?.use { stream -> stream.readBytes() }
|
||||||
|
return code
|
||||||
|
} finally {
|
||||||
|
connection.disconnect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package com.eatvioapp.app
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.core.os.BundleCompat
|
||||||
|
import com.hiennv.flutter_callkit_incoming.CallkitConstants
|
||||||
|
import com.hiennv.flutter_callkit_incoming.CallkitEventCallback
|
||||||
|
import com.hiennv.flutter_callkit_incoming.FlutterCallkitIncomingPlugin
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import kotlinx.coroutines.withTimeoutOrNull
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends `POST /video-call/decline` from the process that handled the tap.
|
||||||
|
*
|
||||||
|
* The notification Decline button is an explicit broadcast into the CallKit
|
||||||
|
* plugin. That broadcast starts the process when the app was killed and does
|
||||||
|
* not start Flutter. The plugin notifies this callback before it returns, so
|
||||||
|
* the request can finish while the process is still alive.
|
||||||
|
*/
|
||||||
|
object VideoCallDeclineReporter : CallkitEventCallback {
|
||||||
|
private const val TAG = "VideoCallDecline"
|
||||||
|
private const val WAIT_FOR_HTTP_MS = 9_000L
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var appContext: Context? = null
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var installed = false
|
||||||
|
|
||||||
|
fun install(context: Context) {
|
||||||
|
if (installed) return
|
||||||
|
installed = true
|
||||||
|
appContext = context.applicationContext
|
||||||
|
FlutterCallkitIncomingPlugin.registerEventCallback(this)
|
||||||
|
Log.i(TAG, "installed")
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCallEvent(event: CallkitEventCallback.CallEvent, callData: Bundle) {
|
||||||
|
if (event != CallkitEventCallback.CallEvent.DECLINE) return
|
||||||
|
val context = appContext ?: return
|
||||||
|
val handle = callData.getString(CallkitConstants.EXTRA_CALLKIT_HANDLE)
|
||||||
|
val extra = copyExtra(callData)
|
||||||
|
if (MainActivity.isInForeground) {
|
||||||
|
CoroutineScope(Dispatchers.IO).launch {
|
||||||
|
VideoCallDeclineClient.send(context, handle, extra)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// The Decline button starts this process and then the broadcast ends.
|
||||||
|
// Wait here so Android does not kill the process before the POST returns.
|
||||||
|
runBlocking(Dispatchers.IO) {
|
||||||
|
withTimeoutOrNull(WAIT_FOR_HTTP_MS) {
|
||||||
|
VideoCallDeclineClient.send(context, handle, extra)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun copyExtra(callData: Bundle): Map<String, Any?> {
|
||||||
|
val raw = BundleCompat.getSerializable(
|
||||||
|
callData,
|
||||||
|
CallkitConstants.EXTRA_CALLKIT_EXTRA,
|
||||||
|
HashMap::class.java,
|
||||||
|
) ?: return emptyMap()
|
||||||
|
return buildMap {
|
||||||
|
for ((key, value) in raw) {
|
||||||
|
if (key is String) put(key, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
package com.eatvioapp.app
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Body of `POST /api/v2/chat/{conversation}/video-call/decline`.
|
||||||
|
*
|
||||||
|
* [callId] is omitted when it is missing, not a uuid, or equal to the
|
||||||
|
* conversation uuid: the server treats `call_id` as the session uuid.
|
||||||
|
*/
|
||||||
|
internal data class VideoCallDeclineRequest(
|
||||||
|
val url: String,
|
||||||
|
val token: String,
|
||||||
|
val body: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal data class VideoCallDeclineFields(
|
||||||
|
val conversationUuid: String,
|
||||||
|
val callId: String?,
|
||||||
|
val endedPush: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal object VideoCallDeclineRequestFactory {
|
||||||
|
private val HEX = "0123456789ABCDEF".toCharArray()
|
||||||
|
private val uuidPattern =
|
||||||
|
Regex("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
|
||||||
|
|
||||||
|
fun fields(handle: String?, extra: Map<*, *>?): VideoCallDeclineFields {
|
||||||
|
val conversation = firstString(
|
||||||
|
extra,
|
||||||
|
listOf("conversationUuid", "conversation_uuid"),
|
||||||
|
) ?: handle?.trim().orEmpty()
|
||||||
|
val rawCallId = firstString(extra, listOf("call_id", "callId"))
|
||||||
|
return VideoCallDeclineFields(
|
||||||
|
conversationUuid = conversation,
|
||||||
|
callId = backendCallId(rawCallId, conversation),
|
||||||
|
endedPush = marksEndedPush(extra),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun build(
|
||||||
|
baseUrl: String?,
|
||||||
|
token: String?,
|
||||||
|
hwId: String?,
|
||||||
|
fields: VideoCallDeclineFields,
|
||||||
|
): VideoCallDeclineRequest? {
|
||||||
|
if (fields.endedPush) return null
|
||||||
|
val conversation = fields.conversationUuid.trim()
|
||||||
|
val authToken = token?.trim().orEmpty()
|
||||||
|
val deviceId = hwId?.trim().orEmpty()
|
||||||
|
val root = baseUrl?.trim()?.trimEnd('/').orEmpty()
|
||||||
|
if (conversation.isEmpty() || authToken.isEmpty()) return null
|
||||||
|
if (deviceId.length < 8 || deviceId.length > 64) return null
|
||||||
|
if (!root.startsWith("http://") && !root.startsWith("https://")) return null
|
||||||
|
|
||||||
|
val encoded = encodePathSegment(conversation)
|
||||||
|
return VideoCallDeclineRequest(
|
||||||
|
url = "$root/api/v2/chat/$encoded/video-call/decline",
|
||||||
|
token = authToken,
|
||||||
|
body = jsonBody(deviceId, fields.callId),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun backendCallId(callId: String?, conversationUuid: String): String? {
|
||||||
|
val id = callId?.trim().orEmpty()
|
||||||
|
if (!uuidPattern.matches(id)) return null
|
||||||
|
if (id.equals(conversationUuid.trim(), ignoreCase = true)) return null
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun firstString(extra: Map<*, *>?, keys: List<String>): String? {
|
||||||
|
if (extra == null) return null
|
||||||
|
for (key in keys) {
|
||||||
|
val value = extra[key] as? String ?: continue
|
||||||
|
val trimmed = value.trim()
|
||||||
|
if (trimmed.isNotEmpty()) return trimmed
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun marksEndedPush(extra: Map<*, *>?): Boolean {
|
||||||
|
val value = extra?.get("endedPush") ?: return false
|
||||||
|
return when (value) {
|
||||||
|
is Boolean -> value
|
||||||
|
is Number -> value.toInt() != 0
|
||||||
|
is String -> {
|
||||||
|
val normalized = value.trim().lowercase()
|
||||||
|
normalized == "true" || normalized == "1"
|
||||||
|
}
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun jsonBody(hwId: String, callId: String?): String {
|
||||||
|
val hw = jsonString(hwId)
|
||||||
|
if (callId == null) return """{"hw_id":$hw}"""
|
||||||
|
return """{"hw_id":$hw,"call_id":${jsonString(callId)}}"""
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun encodePathSegment(value: String): String {
|
||||||
|
val bytes = value.encodeToByteArray()
|
||||||
|
return buildString(bytes.size) {
|
||||||
|
for (byte in bytes) {
|
||||||
|
val code = byte.toInt() and 0xFF
|
||||||
|
val allowed = code in 'A'.code..'Z'.code ||
|
||||||
|
code in 'a'.code..'z'.code ||
|
||||||
|
code in '0'.code..'9'.code ||
|
||||||
|
code == '-'.code ||
|
||||||
|
code == '_'.code ||
|
||||||
|
code == '.'.code ||
|
||||||
|
code == '~'.code
|
||||||
|
if (allowed) {
|
||||||
|
append(code.toChar())
|
||||||
|
} else {
|
||||||
|
append('%')
|
||||||
|
append(HEX[code ushr 4])
|
||||||
|
append(HEX[code and 0x0F])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun jsonString(value: String): String {
|
||||||
|
val escaped = buildString {
|
||||||
|
for (char in value) {
|
||||||
|
when (char) {
|
||||||
|
'\\' -> append("\\\\")
|
||||||
|
'"' -> append("\\\"")
|
||||||
|
'\n' -> append("\\n")
|
||||||
|
'\r' -> append("\\r")
|
||||||
|
'\t' -> append("\\t")
|
||||||
|
else -> append(char)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "\"$escaped\""
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,10 +4,12 @@ import android.content.Context
|
|||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
|
import android.os.PowerManager
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import androidx.core.app.NotificationCompat
|
import androidx.core.app.NotificationCompat
|
||||||
import androidx.core.app.NotificationManagerCompat
|
import androidx.core.app.NotificationManagerCompat
|
||||||
import com.hiennv.flutter_callkit_incoming.CallkitConstants
|
import com.hiennv.flutter_callkit_incoming.CallkitConstants
|
||||||
|
import com.hiennv.flutter_callkit_incoming.CallkitEventCallback
|
||||||
import com.hiennv.flutter_callkit_incoming.CallkitNotificationManager
|
import com.hiennv.flutter_callkit_incoming.CallkitNotificationManager
|
||||||
import com.hiennv.flutter_callkit_incoming.CallkitNotificationService
|
import com.hiennv.flutter_callkit_incoming.CallkitNotificationService
|
||||||
import com.hiennv.flutter_callkit_incoming.CallkitSoundPlayerManager
|
import com.hiennv.flutter_callkit_incoming.CallkitSoundPlayerManager
|
||||||
@@ -16,15 +18,42 @@ import com.hiennv.flutter_callkit_incoming.FlutterCallkitIncomingPlugin
|
|||||||
import com.hiennv.flutter_callkit_incoming.addCall
|
import com.hiennv.flutter_callkit_incoming.addCall
|
||||||
import com.hiennv.flutter_callkit_incoming.getDataActiveCalls
|
import com.hiennv.flutter_callkit_incoming.getDataActiveCalls
|
||||||
import com.hiennv.flutter_callkit_incoming.removeAllCalls
|
import com.hiennv.flutter_callkit_incoming.removeAllCalls
|
||||||
|
import com.hiennv.flutter_callkit_incoming.removeCall
|
||||||
import java.util.HashMap
|
import java.util.HashMap
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
|
||||||
object VideoCallPushBridge {
|
object VideoCallPushBridge {
|
||||||
private const val TAG = "VideoCallPushBridge"
|
private const val TAG = "VideoCallPushBridge"
|
||||||
private const val ANDROID_ACCENT_COLOR = "#2787F5"
|
private const val ANDROID_ACCENT_COLOR = "#2787F5"
|
||||||
private const val MISSED_CALL_CLEANUP_DELAY_MS = 250L
|
private const val MISSED_CALL_CLEANUP_DELAY_MS = 250L
|
||||||
|
private const val TOMBSTONE_TTL_MS = 2 * 60 * 1000L
|
||||||
|
private const val WAKE_LOCK_TAG = "eatvio:incoming_call_ring"
|
||||||
|
|
||||||
|
private val mainHandler = Handler(Looper.getMainLooper())
|
||||||
|
private val playbackLock = Any()
|
||||||
|
private val playbackGeneration = AtomicInteger(0)
|
||||||
|
private val tombstonedCallIds = HashMap<String, Long>()
|
||||||
|
|
||||||
private var activeSoundManager: CallkitSoundPlayerManager? = null
|
private var activeSoundManager: CallkitSoundPlayerManager? = null
|
||||||
private var activeNotificationManager: CallkitNotificationManager? = null
|
private var activeNotificationManager: CallkitNotificationManager? = null
|
||||||
|
private var activeCallBundle: Bundle? = null
|
||||||
|
private var storedAppContext: Context? = null
|
||||||
|
private var ringtoneTimeout: Runnable? = null
|
||||||
|
private var ringWakeLock: PowerManager.WakeLock? = null
|
||||||
|
private var callbackRegistered = false
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The plugin stops only the sound player owned by [FlutterCallkitIncomingPlugin].
|
||||||
|
* Incoming pushes start a different player, so accept/decline never reached it
|
||||||
|
* and the ringtone kept looping until the process died.
|
||||||
|
*/
|
||||||
|
private val incomingCallEventCallback = object : CallkitEventCallback {
|
||||||
|
override fun onCallEvent(event: CallkitEventCallback.CallEvent, callData: Bundle) {
|
||||||
|
val context = storedAppContext ?: return
|
||||||
|
Log.i(TAG, "incoming call event=$event, stopping ringtone")
|
||||||
|
silenceIncomingCall(context)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun isIncomingVideoCall(data: Map<String, String>): Boolean {
|
fun isIncomingVideoCall(data: Map<String, String>): Boolean {
|
||||||
val rawType = data["type"]
|
val rawType = data["type"]
|
||||||
@@ -89,18 +118,191 @@ object VideoCallPushBridge {
|
|||||||
|
|
||||||
fun showIncomingCall(context: Context, data: Map<String, String>) {
|
fun showIncomingCall(context: Context, data: Map<String, String>) {
|
||||||
val appContext = context.applicationContext
|
val appContext = context.applicationContext
|
||||||
|
storedAppContext = appContext
|
||||||
|
ensureIncomingCallCallbackRegistered()
|
||||||
|
|
||||||
|
val serverCallId = callId(data)
|
||||||
|
if (isTombstoned(serverCallId)) {
|
||||||
|
Log.i(TAG, "showIncomingCall: skip tombstoned call_id=$serverCallId")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
val callData = buildCallDataBundle(data)
|
val callData = buildCallDataBundle(data)
|
||||||
if (callData == null) {
|
if (callData == null) {
|
||||||
Log.w(TAG, "showIncomingCall: missing conversation uuid, data=$data")
|
Log.w(TAG, "showIncomingCall: missing conversation uuid, data=$data")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
Log.i(TAG, "showIncomingCall: conversation=${callData.getString(CallkitConstants.EXTRA_CALLKIT_ID)}")
|
val callId = callData.getString(CallkitConstants.EXTRA_CALLKIT_ID)
|
||||||
|
val seenGeneration = playbackGeneration.get()
|
||||||
|
Log.i(TAG, "showIncomingCall: id=$callId conversation=${conversationUuid(data)}")
|
||||||
|
|
||||||
|
// Ringtone.play() and stop() must run on the same thread. FCM delivers
|
||||||
|
// pushes on a background thread, while Answer runs on the main thread.
|
||||||
|
// A second show for the same conversation must not bump the generation:
|
||||||
|
// that would cancel the timeout of the call that is already ringing.
|
||||||
|
mainHandler.post {
|
||||||
|
synchronized(playbackLock) {
|
||||||
|
if (seenGeneration != playbackGeneration.get()) {
|
||||||
|
Log.i(TAG, "showIncomingCall: skipped after silence")
|
||||||
|
return@post
|
||||||
|
}
|
||||||
|
val alreadyRinging = activeCallBundle?.getString(CallkitConstants.EXTRA_CALLKIT_ID)
|
||||||
|
if (!callId.isNullOrBlank() && callId == alreadyRinging) {
|
||||||
|
Log.i(TAG, "showIncomingCall: already ringing $callId")
|
||||||
|
return@post
|
||||||
|
}
|
||||||
|
val generation = playbackGeneration.incrementAndGet()
|
||||||
|
startIncomingCallLocked(appContext, callData, generation)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stops the ringtone that [showIncomingCall] started and removes the incoming
|
||||||
|
* notification. Safe to call more than once.
|
||||||
|
*/
|
||||||
|
fun silenceIncomingCall(context: Context) {
|
||||||
|
val appContext = context.applicationContext
|
||||||
|
storedAppContext = appContext
|
||||||
|
Log.i(TAG, "silenceIncomingCall")
|
||||||
|
playbackGeneration.incrementAndGet()
|
||||||
|
val stop = Runnable {
|
||||||
|
synchronized(playbackLock) {
|
||||||
|
stopPlaybackLocked(appContext)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||||
|
stop.run()
|
||||||
|
} else {
|
||||||
|
mainHandler.post(stop)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The plugin's sound player stops on ACTION_SCREEN_OFF. The ringing screen turns
|
||||||
|
* the display on itself, so keep ringing through that transition.
|
||||||
|
*/
|
||||||
|
fun keepRingingOnFullScreen() {
|
||||||
|
synchronized(playbackLock) {
|
||||||
|
activeSoundManager?.keepRingingOnFullScreen()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun dismissIncomingCalls(
|
||||||
|
context: Context,
|
||||||
|
callId: String? = null,
|
||||||
|
conversationUuid: String? = null,
|
||||||
|
) {
|
||||||
|
val normalizedCallId = callId?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
|
val normalizedConversation = conversationUuid?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
|
if (normalizedCallId != null) {
|
||||||
|
markTombstone(normalizedCallId)
|
||||||
|
}
|
||||||
|
|
||||||
|
val appContext = context.applicationContext
|
||||||
|
val calls = getDataActiveCalls(appContext)
|
||||||
|
Log.i(
|
||||||
|
TAG,
|
||||||
|
"dismissIncomingCalls: active=${calls.size} call_id=${normalizedCallId ?: "-"} " +
|
||||||
|
"conversation=${normalizedConversation ?: "-"}",
|
||||||
|
)
|
||||||
|
playbackGeneration.incrementAndGet()
|
||||||
|
|
||||||
|
val dismiss = Runnable {
|
||||||
|
synchronized(playbackLock) {
|
||||||
|
val notificationManager = resolveNotificationManager(appContext)
|
||||||
|
val allBundles = calls.map { it.toBundle() }
|
||||||
|
val targeted = hasDismissTarget(normalizedCallId, normalizedConversation)
|
||||||
|
val bundles = if (targeted) {
|
||||||
|
allBundles.filter { bundleMatches(it, normalizedCallId, normalizedConversation) }
|
||||||
|
} else {
|
||||||
|
allBundles
|
||||||
|
}
|
||||||
|
|
||||||
|
val activeMatches = activeCallBundle?.let { bundle ->
|
||||||
|
!targeted || bundleMatches(bundle, normalizedCallId, normalizedConversation)
|
||||||
|
} == true
|
||||||
|
if (activeMatches || !targeted) {
|
||||||
|
stopPlaybackLocked(appContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
for (bundle in bundles) {
|
||||||
|
try {
|
||||||
|
dismissIncomingCallNotification(appContext, notificationManager, bundle)
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(
|
||||||
|
TAG,
|
||||||
|
"dismissIncomingCalls: failed for call ${bundle.getString(CallkitConstants.EXTRA_CALLKIT_ID)}",
|
||||||
|
error,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!targeted || bundles.isNotEmpty()) {
|
||||||
|
try {
|
||||||
|
CallkitNotificationService.stopService(appContext)
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(TAG, "dismissIncomingCalls: failed to stop callkit service", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!targeted) {
|
||||||
|
try {
|
||||||
|
removeAllCalls(appContext)
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(TAG, "dismissIncomingCalls: failed to remove persisted calls", error)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (bundle in bundles) {
|
||||||
|
try {
|
||||||
|
removeCall(appContext, Data.fromBundle(bundle))
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(TAG, "dismissIncomingCalls: failed to remove targeted call", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (activeMatches || !targeted) {
|
||||||
|
stopIncomingRingtone()
|
||||||
|
}
|
||||||
|
scheduleMissedCallCleanup(notificationManager, bundles)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||||
|
dismiss.run()
|
||||||
|
} else {
|
||||||
|
mainHandler.post(dismiss)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun dismissAllIncomingCalls(context: Context) {
|
||||||
|
dismissIncomingCalls(context)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun dismissEndedVideoCall(context: Context, data: Map<String, String>) {
|
||||||
|
dismissIncomingCalls(
|
||||||
|
context = context,
|
||||||
|
callId = callId(data),
|
||||||
|
conversationUuid = conversationUuid(data),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ensureIncomingCallCallbackRegistered() {
|
||||||
|
if (callbackRegistered) return
|
||||||
|
FlutterCallkitIncomingPlugin.registerEventCallback(incomingCallEventCallback)
|
||||||
|
callbackRegistered = true
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startIncomingCallLocked(appContext: Context, callData: Bundle, generation: Int) {
|
||||||
|
stopPlaybackLocked(appContext)
|
||||||
|
|
||||||
val soundManager = CallkitSoundPlayerManager(appContext)
|
val soundManager = CallkitSoundPlayerManager(appContext)
|
||||||
val notificationManager = CallkitNotificationManager(appContext, soundManager)
|
val notificationManager = CallkitNotificationManager(appContext, soundManager)
|
||||||
activeSoundManager = soundManager
|
activeSoundManager = soundManager
|
||||||
activeNotificationManager = notificationManager
|
activeNotificationManager = notificationManager
|
||||||
|
activeCallBundle = callData
|
||||||
notificationManager.createNotificationChanel(callData)
|
notificationManager.createNotificationChanel(callData)
|
||||||
notificationManager.showIncomingNotification(callData)
|
notificationManager.showIncomingNotification(callData)
|
||||||
|
|
||||||
@@ -109,46 +311,78 @@ object VideoCallPushBridge {
|
|||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
Log.w(TAG, "showIncomingCall: failed to persist active call", error)
|
Log.w(TAG, "showIncomingCall: failed to persist active call", error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val durationMs = callData.getLong(CallkitConstants.EXTRA_CALLKIT_DURATION, 45_000L)
|
||||||
|
wakeScreenLocked(appContext, if (durationMs > 0L) durationMs else 45_000L)
|
||||||
|
if (durationMs > 0L) {
|
||||||
|
val timeout = Runnable {
|
||||||
|
synchronized(playbackLock) {
|
||||||
|
if (generation != playbackGeneration.get()) return@Runnable
|
||||||
|
Log.i(TAG, "incoming ringtone timed out")
|
||||||
|
stopPlaybackLocked(appContext)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ringtoneTimeout = timeout
|
||||||
|
mainHandler.postDelayed(timeout, durationMs)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun dismissAllIncomingCalls(context: Context) {
|
/**
|
||||||
val appContext = context.applicationContext
|
* Turns the screen on while the call rings. The full-screen intent of the
|
||||||
val calls = getDataActiveCalls(appContext)
|
* notification does the same only when the system grants it; the wake lock
|
||||||
Log.i(TAG, "dismissAllIncomingCalls: active calls=${calls.size}")
|
* works without any grant, so the lock screen with the call card lights up.
|
||||||
|
*/
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
private fun wakeScreenLocked(appContext: Context, durationMs: Long) {
|
||||||
|
releaseScreenWakeLockLocked()
|
||||||
|
try {
|
||||||
|
val powerManager = appContext.getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||||
|
val lock = powerManager.newWakeLock(
|
||||||
|
PowerManager.SCREEN_BRIGHT_WAKE_LOCK or
|
||||||
|
PowerManager.ACQUIRE_CAUSES_WAKEUP or
|
||||||
|
PowerManager.ON_AFTER_RELEASE,
|
||||||
|
WAKE_LOCK_TAG,
|
||||||
|
)
|
||||||
|
lock.acquire(durationMs)
|
||||||
|
ringWakeLock = lock
|
||||||
|
Log.i(TAG, "wakeScreen: screen on for ${durationMs}ms, interactive=${powerManager.isInteractive}")
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(TAG, "wakeScreen: failed to acquire wake lock", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
stopIncomingRingtone(appContext)
|
private fun releaseScreenWakeLockLocked() {
|
||||||
|
val lock = ringWakeLock ?: return
|
||||||
|
ringWakeLock = null
|
||||||
|
try {
|
||||||
|
if (lock.isHeld) lock.release()
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(TAG, "wakeScreen: failed to release wake lock", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val notificationManager = resolveNotificationManager(appContext)
|
private fun stopPlaybackLocked(appContext: Context) {
|
||||||
val bundles = calls.map { it.toBundle() }
|
cancelRingtoneTimeoutLocked()
|
||||||
|
releaseScreenWakeLockLocked()
|
||||||
for (bundle in bundles) {
|
val notificationManager = activeNotificationManager
|
||||||
|
val bundle = activeCallBundle
|
||||||
|
stopIncomingRingtone()
|
||||||
|
if (notificationManager != null && bundle != null) {
|
||||||
try {
|
try {
|
||||||
dismissIncomingCallNotification(appContext, notificationManager, bundle)
|
dismissIncomingCallNotification(appContext, notificationManager, bundle)
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
Log.w(
|
Log.w(TAG, "stopPlayback: failed to dismiss incoming notification", error)
|
||||||
TAG,
|
|
||||||
"dismissAllIncomingCalls: failed for call ${bundle.getString(CallkitConstants.EXTRA_CALLKIT_ID)}",
|
|
||||||
error,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
|
||||||
CallkitNotificationService.stopService(appContext)
|
|
||||||
} catch (error: Exception) {
|
|
||||||
Log.w(TAG, "dismissAllIncomingCalls: failed to stop callkit service", error)
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
removeAllCalls(appContext)
|
|
||||||
} catch (error: Exception) {
|
|
||||||
Log.w(TAG, "dismissAllIncomingCalls: failed to remove persisted calls", error)
|
|
||||||
}
|
|
||||||
|
|
||||||
stopIncomingRingtone(appContext)
|
|
||||||
scheduleMissedCallCleanup(notificationManager, bundles)
|
|
||||||
activeSoundManager = null
|
activeSoundManager = null
|
||||||
activeNotificationManager = null
|
activeNotificationManager = null
|
||||||
|
activeCallBundle = null
|
||||||
|
EatvioCallkitIncomingBridgeActivity.dismissRingingScreen()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cancelRingtoneTimeoutLocked() {
|
||||||
|
ringtoneTimeout?.let { mainHandler.removeCallbacks(it) }
|
||||||
|
ringtoneTimeout = null
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun resolveNotificationManager(context: Context): CallkitNotificationManager {
|
private fun resolveNotificationManager(context: Context): CallkitNotificationManager {
|
||||||
@@ -161,11 +395,19 @@ object VideoCallPushBridge {
|
|||||||
return CallkitNotificationManager(context, soundManager)
|
return CallkitNotificationManager(context, soundManager)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun stopIncomingRingtone(context: Context) {
|
private fun stopIncomingRingtone() {
|
||||||
activeSoundManager?.stop()
|
try {
|
||||||
FlutterCallkitIncomingPlugin.getInstance()
|
activeSoundManager?.stop()
|
||||||
?.getCallkitSoundPlayerManager()
|
} catch (error: Exception) {
|
||||||
?.stop()
|
Log.w(TAG, "stopIncomingRingtone: active player", error)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
FlutterCallkitIncomingPlugin.getInstance()
|
||||||
|
?.getCallkitSoundPlayerManager()
|
||||||
|
?.stop()
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(TAG, "stopIncomingRingtone: plugin player", error)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -222,6 +464,8 @@ object VideoCallPushBridge {
|
|||||||
|
|
||||||
private fun buildCallDataBundle(data: Map<String, String>): Bundle? {
|
private fun buildCallDataBundle(data: Map<String, String>): Bundle? {
|
||||||
val conversationUuid = conversationUuid(data) ?: return null
|
val conversationUuid = conversationUuid(data) ?: return null
|
||||||
|
val serverCallId = callId(data)
|
||||||
|
val callKitId = serverCallId ?: conversationUuid
|
||||||
val callerName = data["counterpartName"]
|
val callerName = data["counterpartName"]
|
||||||
?: data["counterpart_name"]
|
?: data["counterpart_name"]
|
||||||
?: data["caller_name"]
|
?: data["caller_name"]
|
||||||
@@ -247,6 +491,9 @@ object VideoCallPushBridge {
|
|||||||
|
|
||||||
val extra = HashMap<String, Any?>()
|
val extra = HashMap<String, Any?>()
|
||||||
extra["conversationUuid"] = conversationUuid
|
extra["conversationUuid"] = conversationUuid
|
||||||
|
if (!serverCallId.isNullOrBlank()) {
|
||||||
|
extra["call_id"] = serverCallId
|
||||||
|
}
|
||||||
extra["counterpartName"] = callerName
|
extra["counterpartName"] = callerName
|
||||||
if (avatarUrl.isNotBlank()) {
|
if (avatarUrl.isNotBlank()) {
|
||||||
extra["counterpartAvatarUrl"] = avatarUrl
|
extra["counterpartAvatarUrl"] = avatarUrl
|
||||||
@@ -257,9 +504,13 @@ object VideoCallPushBridge {
|
|||||||
if (counterpartIsConsultant) {
|
if (counterpartIsConsultant) {
|
||||||
extra["counterpartIsConsultant"] = true
|
extra["counterpartIsConsultant"] = true
|
||||||
}
|
}
|
||||||
|
val messageId = data["message_id"] ?: data["messageId"]
|
||||||
|
if (!messageId.isNullOrBlank()) {
|
||||||
|
extra["message_id"] = messageId
|
||||||
|
}
|
||||||
|
|
||||||
return Bundle().apply {
|
return Bundle().apply {
|
||||||
putString(CallkitConstants.EXTRA_CALLKIT_ID, conversationUuid)
|
putString(CallkitConstants.EXTRA_CALLKIT_ID, callKitId)
|
||||||
putString(CallkitConstants.EXTRA_CALLKIT_NAME_CALLER, callerName)
|
putString(CallkitConstants.EXTRA_CALLKIT_NAME_CALLER, callerName)
|
||||||
putString(CallkitConstants.EXTRA_CALLKIT_APP_NAME, "Итвио")
|
putString(CallkitConstants.EXTRA_CALLKIT_APP_NAME, "Итвио")
|
||||||
putString(CallkitConstants.EXTRA_CALLKIT_HANDLE, conversationUuid)
|
putString(CallkitConstants.EXTRA_CALLKIT_HANDLE, conversationUuid)
|
||||||
@@ -284,6 +535,77 @@ object VideoCallPushBridge {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun callId(data: Map<String, String>): String? {
|
||||||
|
return data["call_id"]?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
|
?: data["callId"]?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hasDismissTarget(callId: String?, conversationUuid: String?): Boolean {
|
||||||
|
return !callId.isNullOrBlank() || !conversationUuid.isNullOrBlank()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun bundleMatches(
|
||||||
|
bundle: Bundle,
|
||||||
|
callId: String?,
|
||||||
|
conversationUuid: String?,
|
||||||
|
): Boolean {
|
||||||
|
val normalizedCallId = callId?.trim()?.lowercase()
|
||||||
|
if (!normalizedCallId.isNullOrEmpty()) {
|
||||||
|
val id = bundle.getString(CallkitConstants.EXTRA_CALLKIT_ID)?.trim()?.lowercase()
|
||||||
|
if (id != null && id == normalizedCallId) return true
|
||||||
|
val extraCallId = extraString(bundle, "call_id")
|
||||||
|
?: extraString(bundle, "callId")
|
||||||
|
if (extraCallId != null && extraCallId.lowercase() == normalizedCallId) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// A ring that already stores its own call id must not be closed by
|
||||||
|
// another call in the same chat. Legacy rings have no call id and
|
||||||
|
// still match the conversation.
|
||||||
|
if (!extraCallId.isNullOrBlank()) return false
|
||||||
|
}
|
||||||
|
|
||||||
|
val normalizedConversation = conversationUuid?.trim()?.lowercase() ?: return false
|
||||||
|
val handle = bundle.getString(CallkitConstants.EXTRA_CALLKIT_HANDLE)?.trim()?.lowercase()
|
||||||
|
if (handle != null && handle == normalizedConversation) return true
|
||||||
|
val extraConversation = extraString(bundle, "conversationUuid")
|
||||||
|
?: extraString(bundle, "conversation_uuid")
|
||||||
|
return extraConversation?.lowercase() == normalizedConversation
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
private fun extraString(bundle: Bundle, key: String): String? {
|
||||||
|
val extra = bundle.getSerializable(CallkitConstants.EXTRA_CALLKIT_EXTRA) as? HashMap<String, Any?>
|
||||||
|
?: return null
|
||||||
|
val value = extra[key] ?: return null
|
||||||
|
val text = value.toString().trim()
|
||||||
|
return text.takeIf { it.isNotEmpty() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun markTombstone(callId: String) {
|
||||||
|
val normalized = callId.trim().lowercase()
|
||||||
|
if (normalized.isEmpty()) return
|
||||||
|
pruneTombstones()
|
||||||
|
tombstonedCallIds[normalized] = System.currentTimeMillis() + TOMBSTONE_TTL_MS
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isTombstoned(callId: String?): Boolean {
|
||||||
|
val normalized = callId?.trim()?.lowercase() ?: return false
|
||||||
|
if (normalized.isEmpty()) return false
|
||||||
|
pruneTombstones()
|
||||||
|
return tombstonedCallIds.containsKey(normalized)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pruneTombstones() {
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
val iterator = tombstonedCallIds.entries.iterator()
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
val entry = iterator.next()
|
||||||
|
if (entry.value <= now) {
|
||||||
|
iterator.remove()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun conversationUuid(data: Map<String, String>): String? {
|
private fun conversationUuid(data: Map<String, String>): String? {
|
||||||
val fromData = data["conversationUuid"]
|
val fromData = data["conversationUuid"]
|
||||||
?: data["conversation_uuid"]
|
?: data["conversation_uuid"]
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package com.eatvioapp.app
|
||||||
|
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class IncomingCallRingtonePolicyTest {
|
||||||
|
@Test
|
||||||
|
fun answerDeclineEndAndTimeoutStopTheRingtone() {
|
||||||
|
assertTrue(
|
||||||
|
IncomingCallRingtonePolicy.actionStopsRingtone(
|
||||||
|
"com.hiennv.flutter_callkit_incoming.ACTION_CALL_ACCEPT",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertTrue(
|
||||||
|
IncomingCallRingtonePolicy.actionStopsRingtone(
|
||||||
|
"com.hiennv.flutter_callkit_incoming.ACTION_CALL_DECLINE",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertTrue(
|
||||||
|
IncomingCallRingtonePolicy.actionStopsRingtone(
|
||||||
|
"com.hiennv.flutter_callkit_incoming.ACTION_CALL_ENDED",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertTrue(
|
||||||
|
IncomingCallRingtonePolicy.actionStopsRingtone(
|
||||||
|
"com.hiennv.flutter_callkit_incoming.ACTION_CALL_TIMEOUT",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun incomingAndStartActionsKeepTheRingtonePlaying() {
|
||||||
|
assertFalse(
|
||||||
|
IncomingCallRingtonePolicy.actionStopsRingtone(
|
||||||
|
"com.hiennv.flutter_callkit_incoming.ACTION_CALL_INCOMING",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertFalse(
|
||||||
|
IncomingCallRingtonePolicy.actionStopsRingtone(
|
||||||
|
"com.hiennv.flutter_callkit_incoming.ACTION_CALL_START",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
package com.eatvioapp.app
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class VideoCallDeclineRequestTest {
|
||||||
|
private val baseUrl = "https://eatvio.example"
|
||||||
|
private val token = "sanctum-token"
|
||||||
|
private val hwId = "install-hw-id-01"
|
||||||
|
private val conversation = "11111111-1111-1111-1111-111111111111"
|
||||||
|
private val callId = "22222222-2222-2222-2222-222222222222"
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun buildsDeclinePostWithCallId() {
|
||||||
|
val request = request(callId = callId)
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"https://eatvio.example/api/v2/chat/$conversation/video-call/decline",
|
||||||
|
request?.url,
|
||||||
|
)
|
||||||
|
assertEquals(token, request?.token)
|
||||||
|
assertEquals(
|
||||||
|
"""{"hw_id":"$hwId","call_id":"$callId"}""",
|
||||||
|
request?.body,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun omitsCallIdWhenItIsTheConversationUuid() {
|
||||||
|
val request = request(callId = conversation.uppercase())
|
||||||
|
|
||||||
|
assertEquals("""{"hw_id":"$hwId"}""", request?.body)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun omitsCallIdThatIsNotAUuid() {
|
||||||
|
val request = request(callId = "message-15")
|
||||||
|
|
||||||
|
assertEquals("""{"hw_id":"$hwId"}""", request?.body)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun readsConversationFromHandleWhenExtraHasNone() {
|
||||||
|
val fields = VideoCallDeclineRequestFactory.fields(conversation, emptyMap<String, Any?>())
|
||||||
|
val request = VideoCallDeclineRequestFactory.build(baseUrl, token, hwId, fields)
|
||||||
|
|
||||||
|
assertTrue(request?.url?.contains(conversation) == true)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun skipsEndedPush() {
|
||||||
|
val fields = VideoCallDeclineRequestFactory.fields(
|
||||||
|
conversation,
|
||||||
|
mapOf("conversationUuid" to conversation, "endedPush" to true),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertNull(VideoCallDeclineRequestFactory.build(baseUrl, token, hwId, fields))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun skipsMissingTokenBaseUrlOrShortHwId() {
|
||||||
|
val fields = VideoCallDeclineRequestFactory.fields(
|
||||||
|
null,
|
||||||
|
mapOf("conversationUuid" to conversation, "call_id" to callId),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertNull(VideoCallDeclineRequestFactory.build(null, token, hwId, fields))
|
||||||
|
assertNull(VideoCallDeclineRequestFactory.build(baseUrl, " ", hwId, fields))
|
||||||
|
assertNull(VideoCallDeclineRequestFactory.build(baseUrl, token, "short", fields))
|
||||||
|
assertNull(VideoCallDeclineRequestFactory.build("eatvio.example", token, hwId, fields))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun trimsATrailingSlashOnTheBaseUrl() {
|
||||||
|
val request = VideoCallDeclineRequestFactory.build(
|
||||||
|
"$baseUrl/",
|
||||||
|
token,
|
||||||
|
hwId,
|
||||||
|
VideoCallDeclineRequestFactory.fields(
|
||||||
|
null,
|
||||||
|
mapOf("conversationUuid" to conversation),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"https://eatvio.example/api/v2/chat/$conversation/video-call/decline",
|
||||||
|
request?.url,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun request(callId: String?): VideoCallDeclineRequest? {
|
||||||
|
val fields = VideoCallDeclineRequestFactory.fields(
|
||||||
|
null,
|
||||||
|
mapOf(
|
||||||
|
"conversationUuid" to conversation,
|
||||||
|
"call_id" to callId,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return VideoCallDeclineRequestFactory.build(baseUrl, token, hwId, fields)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -650,7 +650,7 @@ code + .copy-button {
|
|||||||
<script type="text/javascript">
|
<script type="text/javascript">
|
||||||
function configurationCacheProblems() { return (
|
function configurationCacheProblems() { return (
|
||||||
// begin-report-data
|
// begin-report-data
|
||||||
{"diagnostics":[{"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/9.0.0/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('url = <value>') instead."}]]}],"problemsReport":{"totalProblemCount":1,"requestedTasks":":app:compileDebugKotlin","documentationLink":"https://docs.gradle.org/9.0.0/userguide/reporting_problems.html","documentationLinkCaption":"Problem report","summaries":[]}}
|
{"diagnostics":[{"problem":[{"text":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10."}],"contextualLabel":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/9.0.0/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"properties-should-be-assigned-using-the-propname-value-syntax-setting-a-property-via-the-gradle-generated-propname-value-or-propname-value-syntax-in-groovy-dsl","displayName":"Properties should be assigned using the 'propName = value' syntax. Setting a property via the Gradle-generated 'propName value' or 'propName(value)' syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('url = <value>') instead."}]]}],"problemsReport":{"totalProblemCount":1,"requestedTasks":":app:testDebugUnitTest --tests com.eatvioapp.app.VideoCallDeclineRequestTest","documentationLink":"https://docs.gradle.org/9.0.0/userguide/reporting_problems.html","documentationLinkCaption":"Problem report","summaries":[]}}
|
||||||
// end-report-data
|
// end-report-data
|
||||||
);}
|
);}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -11,6 +11,8 @@
|
|||||||
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
|
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
|
||||||
46B43B96F809CEC6058EFDD3 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 15ADDB2A35F334AF0AE50011 /* Pods_Runner.framework */; };
|
46B43B96F809CEC6058EFDD3 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 15ADDB2A35F334AF0AE50011 /* Pods_Runner.framework */; };
|
||||||
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
|
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
|
||||||
|
E47D0C1B2F0B4D1000EA7A01 /* VideoCallDeclineClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = E47D0C1A2F0B4D1000EA7A01 /* VideoCallDeclineClient.swift */; };
|
||||||
|
C4A8E2022E9A4B1000123456 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4A8E2012E9A4B1000123456 /* SceneDelegate.swift */; };
|
||||||
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
|
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
|
||||||
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
|
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
|
||||||
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
|
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
|
||||||
@@ -37,6 +39,8 @@
|
|||||||
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
|
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
|
||||||
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
|
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
|
||||||
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||||
|
E47D0C1A2F0B4D1000EA7A01 /* VideoCallDeclineClient.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VideoCallDeclineClient.swift; sourceTree = "<group>"; };
|
||||||
|
C4A8E2012E9A4B1000123456 /* SceneDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
|
||||||
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
|
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
|
||||||
938EE8FB5BAA359AAEDEFFF8 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };
|
938EE8FB5BAA359AAEDEFFF8 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };
|
||||||
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };
|
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };
|
||||||
@@ -115,6 +119,8 @@
|
|||||||
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
|
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
|
||||||
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
|
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
|
||||||
74858FAE1ED2DC5600515810 /* AppDelegate.swift */,
|
74858FAE1ED2DC5600515810 /* AppDelegate.swift */,
|
||||||
|
E47D0C1A2F0B4D1000EA7A01 /* VideoCallDeclineClient.swift */,
|
||||||
|
C4A8E2012E9A4B1000123456 /* SceneDelegate.swift */,
|
||||||
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
|
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
|
||||||
FEE92A0E2D772EA300E6E989 /* Runner.entitlements */,
|
FEE92A0E2D772EA300E6E989 /* Runner.entitlements */,
|
||||||
);
|
);
|
||||||
@@ -300,6 +306,8 @@
|
|||||||
buildActionMask = 2147483647;
|
buildActionMask = 2147483647;
|
||||||
files = (
|
files = (
|
||||||
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
|
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
|
||||||
|
E47D0C1B2F0B4D1000EA7A01 /* VideoCallDeclineClient.swift in Sources */,
|
||||||
|
C4A8E2022E9A4B1000123456 /* SceneDelegate.swift in Sources */,
|
||||||
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
|
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
|
||||||
);
|
);
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -41,6 +41,27 @@
|
|||||||
<string>Может использоваться для стабильного поддержания связи во время звонка.</string>
|
<string>Может использоваться для стабильного поддержания связи во время звонка.</string>
|
||||||
<key>NSPhotoLibraryUsageDescription</key>
|
<key>NSPhotoLibraryUsageDescription</key>
|
||||||
<string>Предоставление доступа позволит Вам добавлять фото к записям</string>
|
<string>Предоставление доступа позволит Вам добавлять фото к записям</string>
|
||||||
|
<key>UIApplicationSceneManifest</key>
|
||||||
|
<dict>
|
||||||
|
<key>UIApplicationSupportsMultipleScenes</key>
|
||||||
|
<false/>
|
||||||
|
<key>UISceneConfigurations</key>
|
||||||
|
<dict>
|
||||||
|
<key>UIWindowSceneSessionRoleApplication</key>
|
||||||
|
<array>
|
||||||
|
<dict>
|
||||||
|
<key>UISceneClassName</key>
|
||||||
|
<string>UIWindowScene</string>
|
||||||
|
<key>UISceneConfigurationName</key>
|
||||||
|
<string>flutter</string>
|
||||||
|
<key>UISceneDelegateClassName</key>
|
||||||
|
<string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
|
||||||
|
<key>UISceneStoryboardFile</key>
|
||||||
|
<string>Main</string>
|
||||||
|
</dict>
|
||||||
|
</array>
|
||||||
|
</dict>
|
||||||
|
</dict>
|
||||||
<key>UIApplicationSupportsIndirectInputEvents</key>
|
<key>UIApplicationSupportsIndirectInputEvents</key>
|
||||||
<true/>
|
<true/>
|
||||||
<key>UIBackgroundModes</key>
|
<key>UIBackgroundModes</key>
|
||||||
|
|||||||
90
ios/Runner/SceneDelegate.swift
Normal file
90
ios/Runner/SceneDelegate.swift
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
import Flutter
|
||||||
|
import UIKit
|
||||||
|
import YandexLoginSDK
|
||||||
|
|
||||||
|
/// iOS 27 requires a UIScene lifecycle. Flutter 3.38 does not yet have
|
||||||
|
/// `FlutterImplicitEngineDelegate`, so channels and URL handling are wired
|
||||||
|
/// here after the scene creates the Flutter view.
|
||||||
|
class SceneDelegate: FlutterSceneDelegate {
|
||||||
|
override func scene(
|
||||||
|
_ scene: UIScene,
|
||||||
|
willConnectTo session: UISceneSession,
|
||||||
|
options connectionOptions: UIScene.ConnectionOptions
|
||||||
|
) {
|
||||||
|
super.scene(scene, willConnectTo: session, options: connectionOptions)
|
||||||
|
registerCallChannels()
|
||||||
|
handleConnectionOptions(connectionOptions)
|
||||||
|
}
|
||||||
|
|
||||||
|
override func sceneDidBecomeActive(_ scene: UIScene) {
|
||||||
|
super.sceneDidBecomeActive(scene)
|
||||||
|
registerCallChannels()
|
||||||
|
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
appDelegate.deliverStoredAcceptedCall()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
|
||||||
|
var handledCustomURL = false
|
||||||
|
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
|
||||||
|
for context in URLContexts {
|
||||||
|
if appDelegate.handleOpenURL(
|
||||||
|
context.url,
|
||||||
|
sourceApplication: context.options.sourceApplication
|
||||||
|
) {
|
||||||
|
handledCustomURL = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !handledCustomURL {
|
||||||
|
super.scene(scene, openURLContexts: URLContexts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
|
||||||
|
if YXLSdk.shared.processUserActivity(userActivity) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
super.scene(scene, continue: userActivity)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func registerCallChannels() {
|
||||||
|
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
appDelegate.registerCallChannels(from: flutterViewController)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var flutterViewController: FlutterViewController? {
|
||||||
|
if let controller = window?.rootViewController as? FlutterViewController {
|
||||||
|
return controller
|
||||||
|
}
|
||||||
|
for scene in UIApplication.shared.connectedScenes {
|
||||||
|
guard let windowScene = scene as? UIWindowScene else { continue }
|
||||||
|
for sceneWindow in windowScene.windows {
|
||||||
|
if let controller = sceneWindow.rootViewController as? FlutterViewController {
|
||||||
|
return controller
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
private func handleConnectionOptions(_ options: UIScene.ConnectionOptions) {
|
||||||
|
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for context in options.urlContexts {
|
||||||
|
_ = appDelegate.handleOpenURL(
|
||||||
|
context.url,
|
||||||
|
sourceApplication: context.options.sourceApplication
|
||||||
|
)
|
||||||
|
}
|
||||||
|
for activity in options.userActivities {
|
||||||
|
if YXLSdk.shared.processUserActivity(activity) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
163
ios/Runner/VideoCallDeclineClient.swift
Normal file
163
ios/Runner/VideoCallDeclineClient.swift
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
import Foundation
|
||||||
|
import UIKit
|
||||||
|
|
||||||
|
enum VideoCallDeclineClient {
|
||||||
|
private static let uuidPattern =
|
||||||
|
#"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"#
|
||||||
|
|
||||||
|
/// `POST /video-call/decline` from the CallKit callback. The process is
|
||||||
|
/// awake here even when the user never opens the app afterwards.
|
||||||
|
static func send(extra: [String: Any], handle: String) {
|
||||||
|
post(action: "decline", extra: extra, handle: handle)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `POST /video-call/accept` from the CallKit answer callback. Flutter may
|
||||||
|
/// still be frozen on the splash snapshot, so the other device must be
|
||||||
|
/// told from here. A later Dart retry with the same hw_id is idempotent.
|
||||||
|
static func sendAccept(extra: [String: Any], handle: String) {
|
||||||
|
post(action: "accept", extra: extra, handle: handle)
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func post(action: String, extra: [String: Any], handle: String) {
|
||||||
|
let fields = declineFields(extra: extra, handle: handle)
|
||||||
|
guard let request = makeRequest(
|
||||||
|
baseUrl: prefsString("apiBaseUrl") ?? prefsString("customBaseUrl"),
|
||||||
|
token: prefsString("token"),
|
||||||
|
hwId: UIDevice.current.identifierForVendor?.uuidString,
|
||||||
|
fields: fields,
|
||||||
|
action: action
|
||||||
|
) else {
|
||||||
|
NSLog(
|
||||||
|
"[EatvioVoIP] \(action) POST skipped conversation=\(fields.conversationUuid) ended=\(fields.endedPush)"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let task = EatvioBackgroundTask()
|
||||||
|
task.begin(name: "video-call-\(action)")
|
||||||
|
let urlTask = URLSession.shared.dataTask(with: request) { _, response, error in
|
||||||
|
let code = (response as? HTTPURLResponse)?.statusCode ?? -1
|
||||||
|
NSLog(
|
||||||
|
"[EatvioVoIP] \(action) POST status=\(code) conversation=\(fields.conversationUuid) error=\(error?.localizedDescription ?? "-")"
|
||||||
|
)
|
||||||
|
task.end()
|
||||||
|
}
|
||||||
|
urlTask.resume()
|
||||||
|
}
|
||||||
|
|
||||||
|
static func makeRequest(
|
||||||
|
baseUrl: String?,
|
||||||
|
token: String?,
|
||||||
|
hwId: String?,
|
||||||
|
fields: VideoCallDeclineFields,
|
||||||
|
action: String = "decline"
|
||||||
|
) -> URLRequest? {
|
||||||
|
if fields.endedPush { return nil }
|
||||||
|
let conversation = fields.conversationUuid.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
let authToken = token?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||||
|
let deviceId = hwId?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||||
|
var root = baseUrl?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||||
|
while root.hasSuffix("/") {
|
||||||
|
root.removeLast()
|
||||||
|
}
|
||||||
|
guard !conversation.isEmpty, !authToken.isEmpty else { return nil }
|
||||||
|
guard deviceId.count >= 8, deviceId.count <= 64 else { return nil }
|
||||||
|
guard root.hasPrefix("http://") || root.hasPrefix("https://") else { return nil }
|
||||||
|
guard action == "accept" || action == "decline" else { return nil }
|
||||||
|
guard let encoded = conversation.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed),
|
||||||
|
let url = URL(string: "\(root)/api/v2/chat/\(encoded)/video-call/\(action)")
|
||||||
|
else { return nil }
|
||||||
|
|
||||||
|
var body: [String: String] = ["hw_id": deviceId]
|
||||||
|
if let callId = fields.callId {
|
||||||
|
body["call_id"] = callId
|
||||||
|
}
|
||||||
|
guard let data = try? JSONSerialization.data(withJSONObject: body) else { return nil }
|
||||||
|
|
||||||
|
var request = URLRequest(url: url)
|
||||||
|
request.httpMethod = "POST"
|
||||||
|
request.timeoutInterval = 10
|
||||||
|
request.setValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization")
|
||||||
|
request.setValue("application/json", forHTTPHeaderField: "Accept")
|
||||||
|
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
|
||||||
|
request.httpBody = data
|
||||||
|
return request
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func declineFields(extra: [String: Any], handle: String) -> VideoCallDeclineFields {
|
||||||
|
let conversation = firstString(extra, keys: ["conversationUuid", "conversation_uuid"])
|
||||||
|
?? handle.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
let rawCallId = firstString(extra, keys: ["call_id", "callId"])
|
||||||
|
return VideoCallDeclineFields(
|
||||||
|
conversationUuid: conversation,
|
||||||
|
callId: backendCallId(rawCallId, conversation: conversation),
|
||||||
|
endedPush: marksEndedPush(extra["endedPush"])
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func backendCallId(_ callId: String?, conversation: String) -> String? {
|
||||||
|
let id = callId?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||||
|
guard let regex = try? NSRegularExpression(pattern: uuidPattern),
|
||||||
|
regex.firstMatch(in: id, range: NSRange(id.startIndex..., in: id)) != nil
|
||||||
|
else { return nil }
|
||||||
|
if id.compare(conversation.trimmingCharacters(in: .whitespacesAndNewlines), options: .caseInsensitive) == .orderedSame {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func firstString(_ extra: [String: Any], keys: [String]) -> String? {
|
||||||
|
for key in keys {
|
||||||
|
guard let value = extra[key] as? String else { continue }
|
||||||
|
let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
if !trimmed.isEmpty { return trimmed }
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func marksEndedPush(_ value: Any?) -> Bool {
|
||||||
|
if let bool = value as? Bool { return bool }
|
||||||
|
if let number = value as? NSNumber { return number.intValue != 0 }
|
||||||
|
if let text = value as? String {
|
||||||
|
let normalized = text.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
|
||||||
|
return normalized == "true" || normalized == "1"
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func prefsString(_ key: String) -> String? {
|
||||||
|
let value = UserDefaults.standard.string(forKey: "flutter.\(key)")?
|
||||||
|
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
if let value, !value.isEmpty { return value }
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct VideoCallDeclineFields {
|
||||||
|
var conversationUuid: String
|
||||||
|
var callId: String?
|
||||||
|
var endedPush: Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
private final class EatvioBackgroundTask {
|
||||||
|
private let lock = NSLock()
|
||||||
|
private var id: UIBackgroundTaskIdentifier = .invalid
|
||||||
|
|
||||||
|
func begin(name: String) {
|
||||||
|
let taskId = UIApplication.shared.beginBackgroundTask(withName: name) { [weak self] in
|
||||||
|
self?.end()
|
||||||
|
}
|
||||||
|
lock.lock()
|
||||||
|
id = taskId
|
||||||
|
lock.unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func end() {
|
||||||
|
lock.lock()
|
||||||
|
let current = id
|
||||||
|
id = .invalid
|
||||||
|
lock.unlock()
|
||||||
|
guard current != .invalid else { return }
|
||||||
|
UIApplication.shared.endBackgroundTask(current)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -43,37 +43,95 @@ platform :ios do
|
|||||||
end
|
end
|
||||||
|
|
||||||
UI.message "Using auth_key_path: #{auth_key_path}"
|
UI.message "Using auth_key_path: #{auth_key_path}"
|
||||||
|
|
||||||
|
# Authenticate to App Store Connect early:
|
||||||
|
# needed here by latest_testflight_build_number, not only by upload_to_testflight.
|
||||||
|
app_store_connect_api_key(
|
||||||
|
key_id: "325JS9JCZH",
|
||||||
|
issuer_id: "dfa27d1d-2bb8-4d4d-847e-0b32f9b880b3",
|
||||||
|
key_filepath: auth_key_path,
|
||||||
|
duration: 1200,
|
||||||
|
in_house: false
|
||||||
|
)
|
||||||
|
|
||||||
# Configure Flutter for release mode
|
# Configure Flutter for release mode
|
||||||
UI.message "Configuring Flutter for release mode..."
|
UI.message "Configuring Flutter for release mode..."
|
||||||
sh("cd .. && flutter build ios --config-only --release")
|
sh("cd .. && flutter build ios --config-only --release")
|
||||||
|
|
||||||
# Read build number from Flutter Generated.xcconfig
|
# Read version and build number from Flutter Generated.xcconfig.
|
||||||
|
# They are only a floor: the actual build number is derived from TestFlight below,
|
||||||
|
# so repeated CI runs on the same commit can never hit
|
||||||
|
# ENTITY_ERROR.ATTRIBUTE.INVALID.DUPLICATE ("bundle version must be higher").
|
||||||
generated_xcconfig_path = File.join("..", "Flutter", "Generated.xcconfig")
|
generated_xcconfig_path = File.join("..", "Flutter", "Generated.xcconfig")
|
||||||
|
flutter_build_name = nil
|
||||||
flutter_build_number = nil
|
flutter_build_number = nil
|
||||||
|
|
||||||
if File.exist?(generated_xcconfig_path)
|
if File.exist?(generated_xcconfig_path)
|
||||||
File.foreach(generated_xcconfig_path) do |line|
|
File.foreach(generated_xcconfig_path) do |line|
|
||||||
matches = line.match(/FLUTTER_BUILD_NUMBER=(.*)/)
|
if (m = line.match(/FLUTTER_BUILD_NAME=(.*)/))
|
||||||
if matches
|
flutter_build_name = m[1].strip
|
||||||
flutter_build_number = matches[1].strip
|
elsif (m = line.match(/FLUTTER_BUILD_NUMBER=(.*)/))
|
||||||
break
|
flutter_build_number = m[1].strip
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
if flutter_build_number.nil?
|
if flutter_build_name.nil? || flutter_build_number.nil?
|
||||||
UI.user_error!("Could not find FLUTTER_BUILD_NUMBER in #{generated_xcconfig_path}")
|
UI.user_error!("Could not find FLUTTER_BUILD_NAME/FLUTTER_BUILD_NUMBER in #{generated_xcconfig_path}")
|
||||||
end
|
end
|
||||||
|
|
||||||
UI.message "Flutter build number: #{flutter_build_number}"
|
UI.message "Flutter version from pubspec: #{flutter_build_name} (#{flutter_build_number})"
|
||||||
|
|
||||||
|
# Apple closes a version train once that version is approved/released.
|
||||||
|
# Uploading into a closed train wastes a full ~8 min build and fails only
|
||||||
|
# at the upload step with altool 90186 ("closed for new build submissions")
|
||||||
|
# / 90062 ("must be higher than the previously approved version").
|
||||||
|
# Fail fast here, before building.
|
||||||
|
closed_train_states = [
|
||||||
|
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::READY_FOR_DISTRIBUTION,
|
||||||
|
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::PROCESSING_FOR_DISTRIBUTION,
|
||||||
|
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::PENDING_DEVELOPER_RELEASE,
|
||||||
|
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::PENDING_APPLE_RELEASE
|
||||||
|
].join(",")
|
||||||
|
asc_app = Spaceship::ConnectAPI::App.find("com.eatvioapp.app")
|
||||||
|
closed_train = nil
|
||||||
|
if asc_app.nil?
|
||||||
|
UI.important("App com.eatvioapp.app not found in App Store Connect, skipping closed-train guard")
|
||||||
|
else
|
||||||
|
closed_train = asc_app.get_app_store_versions(
|
||||||
|
filter: {
|
||||||
|
appVersionState: closed_train_states,
|
||||||
|
platform: Spaceship::ConnectAPI::Platform::IOS
|
||||||
|
}
|
||||||
|
).find do |v|
|
||||||
|
(Gem::Version.new(v.version_string) >= Gem::Version.new(flutter_build_name))
|
||||||
|
rescue ArgumentError
|
||||||
|
false
|
||||||
|
end
|
||||||
|
end
|
||||||
|
if closed_train
|
||||||
|
UI.user_error!(
|
||||||
|
"Version train #{closed_train.version_string} is closed for new submissions " \
|
||||||
|
"(#{closed_train.app_version_state}), pubspec version is #{flutter_build_name}. " \
|
||||||
|
"Bump the version in pubspec.yaml above #{closed_train.version_string} and re-run."
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
asc_latest_build_number = latest_testflight_build_number(
|
||||||
|
app_identifier: "com.eatvioapp.app",
|
||||||
|
version: flutter_build_name,
|
||||||
|
initial_build_number: flutter_build_number.to_i
|
||||||
|
)
|
||||||
|
|
||||||
|
new_build_number = [flutter_build_number.to_i, asc_latest_build_number].max + 1
|
||||||
|
UI.message "Latest TestFlight build number: #{asc_latest_build_number} -> uploading build #{new_build_number}"
|
||||||
|
|
||||||
match(type: "appstore", readonly: true)
|
match(type: "appstore", readonly: true)
|
||||||
|
|
||||||
# Set build number explicitly instead of incrementing
|
# Set build number explicitly instead of incrementing
|
||||||
increment_build_number(
|
increment_build_number(
|
||||||
xcodeproj: "Runner.xcodeproj",
|
xcodeproj: "Runner.xcodeproj",
|
||||||
build_number: flutter_build_number
|
build_number: new_build_number
|
||||||
)
|
)
|
||||||
|
|
||||||
update_code_signing_settings(
|
update_code_signing_settings(
|
||||||
@@ -93,28 +151,33 @@ platform :ios do
|
|||||||
export_team_id: "VL68C36HYS"
|
export_team_id: "VL68C36HYS"
|
||||||
)
|
)
|
||||||
|
|
||||||
app_store_connect_api_key(
|
|
||||||
key_id: "325JS9JCZH",
|
|
||||||
issuer_id: "dfa27d1d-2bb8-4d4d-847e-0b32f9b880b3",
|
|
||||||
key_filepath: auth_key_path,
|
|
||||||
duration: 1200,
|
|
||||||
in_house: false
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
begin
|
begin
|
||||||
upload_to_testflight(
|
upload_to_testflight(
|
||||||
skip_waiting_for_build_processing: true,
|
skip_waiting_for_build_processing: true,
|
||||||
skip_submission: true,
|
skip_submission: true,
|
||||||
distribute_external: false,
|
distribute_external: false,
|
||||||
notify_external_testers: false,
|
notify_external_testers: false,
|
||||||
changelog: "TestFlight build #{flutter_build_number}",
|
changelog: "TestFlight build #{new_build_number}",
|
||||||
verbose: true
|
verbose: true
|
||||||
)
|
)
|
||||||
rescue => ex
|
rescue => ex
|
||||||
UI.error "Upload to TestFlight failed: #{ex.message}"
|
# Xcode 26 altool prints a harmless "ERROR: ... CDUploaderStateInfoResumeFilePath"
|
||||||
UI.error "Full error: #{ex.backtrace.join("\n")}"
|
# line even when the package was delivered fine (UPLOAD SUCCEEDED appears in the
|
||||||
raise ex
|
# same output). fastlane < 2.240.0 treats every ERROR line as a failure
|
||||||
|
# (fastlane#30130), so the lane would die after a successful upload.
|
||||||
|
# Real Apple rejections (90186 closed train, 90062 version too low, ...) always
|
||||||
|
# contain UPLOAD FAILED and/or iris-code - those must still fail the lane.
|
||||||
|
if ex.message.include?("CDUploaderStateInfoResumeFilePath") &&
|
||||||
|
!ex.message.include?("UPLOAD FAILED") &&
|
||||||
|
!ex.message.include?("iris-code")
|
||||||
|
UI.important("altool delivered the package but reported a bogus resume-file ERROR " \
|
||||||
|
"(fastlane#30130). Treating upload as successful - " \
|
||||||
|
"verify the build appears in TestFlight.")
|
||||||
|
else
|
||||||
|
UI.error "Upload to TestFlight failed: #{ex.message}"
|
||||||
|
UI.error "Full error: #{ex.backtrace.join("\n")}"
|
||||||
|
raise ex
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:eatvio_app/core/app_initializer.dart';
|
import 'package:eatvio_app/core/app_initializer.dart';
|
||||||
import 'package:eatvio_app/core/cubit/marketing/marketing_cubit.dart';
|
import 'package:eatvio_app/core/cubit/marketing/marketing_cubit.dart';
|
||||||
import 'package:eatvio_app/core/env_config.dart';
|
import 'package:eatvio_app/core/env_config.dart';
|
||||||
import 'package:eatvio_app/core/internet_connection_cubit/internet_connection_cubit.dart';
|
import 'package:eatvio_app/core/internet_connection_cubit/internet_connection_cubit.dart';
|
||||||
import 'package:eatvio_app/core/locator_service.dart';
|
import 'package:eatvio_app/core/locator_service.dart';
|
||||||
|
import 'package:eatvio_app/core/prefs.dart';
|
||||||
|
import 'package:eatvio_app/core/prefs_keys.dart';
|
||||||
import 'package:eatvio_app/core/views/cubit/views_cubit.dart';
|
import 'package:eatvio_app/core/views/cubit/views_cubit.dart';
|
||||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart';
|
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart';
|
||||||
import 'package:eatvio_app/features/notifications/presentation/notifications_cubit/notifications_cubit.dart';
|
import 'package:eatvio_app/features/notifications/presentation/notifications_cubit/notifications_cubit.dart';
|
||||||
@@ -29,22 +33,67 @@ class AppConfig {
|
|||||||
late String _baseUrl;
|
late String _baseUrl;
|
||||||
String get baseUrl => _baseUrl;
|
String get baseUrl => _baseUrl;
|
||||||
|
|
||||||
|
/// Продуктовые хосты API. Сравнение по хосту целиком: поддомены
|
||||||
|
/// (например `*-hasan.eatvio.ru`) — это стенды разработки, не прод.
|
||||||
|
static const List<String> prodApiHosts = ['eatvio.ru', 'eatvio.com'];
|
||||||
|
|
||||||
|
/// Текущий base URL указывает на продуктовый API?
|
||||||
|
bool get isProdApi {
|
||||||
|
final host = Uri.tryParse(baseUrl)?.host.toLowerCase() ?? '';
|
||||||
|
if (host.isEmpty) return false;
|
||||||
|
return prodApiHosts.any((prodHost) => host == prodHost || host == 'www.$prodHost');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Работаем на стенде разработки/stage (не на продуктовом API)?
|
||||||
|
bool get isDevOrStageStand => !isProdApi;
|
||||||
|
|
||||||
void setBaseUrl(String baseUrls) {
|
void setBaseUrl(String baseUrls) {
|
||||||
_baseUrl = baseUrls;
|
_baseUrl = baseUrls;
|
||||||
|
_persistBaseUrl(baseUrls);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _persistBaseUrl(String baseUrl) {
|
||||||
|
if (!sl.isRegistered<Prefs>()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final normalized = baseUrl.trim();
|
||||||
|
if (normalized.isEmpty) {
|
||||||
|
unawaited(sl<Prefs>().remove(PrefsKeys.customBaseUrl));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
unawaited(sl<Prefs>().setString(PrefsKeys.customBaseUrl, normalized));
|
||||||
|
unawaited(sl<Prefs>().setString(PrefsKeys.apiBaseUrl, normalized));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Список глобальных BlocProvider'ов
|
/// Список глобальных BlocProvider'ов
|
||||||
/// Используются lazy: true для отложенной инициализации, чтобы не блокировать старт приложения
|
/// Используются lazy: true для отложенной инициализации, чтобы не блокировать старт приложения
|
||||||
List<BlocProvider> get globalBlocProviders => [
|
List<BlocProvider> get globalBlocProviders => [
|
||||||
BlocProvider<VideoCallSessionCubit>.value(value: sl<VideoCallSessionCubit>()),
|
BlocProvider<VideoCallSessionCubit>.value(
|
||||||
BlocProvider<NewMessagesCubit>(lazy: true, create: (context) => sl<NewMessagesCubit>()),
|
value: sl<VideoCallSessionCubit>(),
|
||||||
BlocProvider<NotificationsCubit>(lazy: true, create: (context) => sl<NotificationsCubit>()),
|
),
|
||||||
|
BlocProvider<NewMessagesCubit>(
|
||||||
|
lazy: true,
|
||||||
|
create: (context) => sl<NewMessagesCubit>(),
|
||||||
|
),
|
||||||
|
BlocProvider<NotificationsCubit>(
|
||||||
|
lazy: true,
|
||||||
|
create: (context) => sl<NotificationsCubit>(),
|
||||||
|
),
|
||||||
BlocProvider<FeedCubit>(lazy: true, create: (context) => sl<FeedCubit>()),
|
BlocProvider<FeedCubit>(lazy: true, create: (context) => sl<FeedCubit>()),
|
||||||
BlocProvider<ProfileAvatarCubit>(lazy: true, create: (context) => sl<ProfileAvatarCubit>()),
|
BlocProvider<ProfileAvatarCubit>(
|
||||||
|
lazy: true,
|
||||||
|
create: (context) => sl<ProfileAvatarCubit>(),
|
||||||
|
),
|
||||||
BlocProvider<ChatsCubit>(lazy: true, create: (context) => sl<ChatsCubit>()),
|
BlocProvider<ChatsCubit>(lazy: true, create: (context) => sl<ChatsCubit>()),
|
||||||
BlocProvider<ViewsCubit>(lazy: true, create: (context) => sl<ViewsCubit>()),
|
BlocProvider<ViewsCubit>(lazy: true, create: (context) => sl<ViewsCubit>()),
|
||||||
BlocProvider<InternetConnectionCubit>(lazy: false, create: (context) => sl<InternetConnectionCubit>()),
|
BlocProvider<InternetConnectionCubit>(
|
||||||
BlocProvider<MarketingCubit>(lazy: true, create: (context) => sl<MarketingCubit>()),
|
lazy: false,
|
||||||
|
create: (context) => sl<InternetConnectionCubit>(),
|
||||||
|
),
|
||||||
|
BlocProvider<MarketingCubit>(
|
||||||
|
lazy: true,
|
||||||
|
create: (context) => sl<MarketingCubit>(),
|
||||||
|
),
|
||||||
];
|
];
|
||||||
|
|
||||||
/// Делегаты локализации
|
/// Делегаты локализации
|
||||||
@@ -56,5 +105,7 @@ class AppConfig {
|
|||||||
];
|
];
|
||||||
|
|
||||||
/// Поддерживаемые локали
|
/// Поддерживаемые локали
|
||||||
List<Locale> get supportedLocales => [const Locale.fromSubtags(languageCode: 'ru')];
|
List<Locale> get supportedLocales => [
|
||||||
|
const Locale.fromSubtags(languageCode: 'ru'),
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
30
lib/core/cached_base_url.dart
Normal file
30
lib/core/cached_base_url.dart
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:eatvio_app/core/app_config.dart';
|
||||||
|
import 'package:eatvio_app/core/locator_service.dart';
|
||||||
|
import 'package:eatvio_app/core/prefs.dart';
|
||||||
|
import 'package:eatvio_app/core/prefs_keys.dart';
|
||||||
|
|
||||||
|
/// Подставляет сохранённый base URL до создания HTTP-клиента.
|
||||||
|
///
|
||||||
|
/// Действующий адрес также пишется в [PrefsKeys.apiBaseUrl], чтобы нативный
|
||||||
|
/// decline мог собрать `POST /video-call/decline`, когда Flutter не запущен.
|
||||||
|
void applyCachedBaseUrl() {
|
||||||
|
if (!sl.isRegistered<Prefs>() || !sl.isRegistered<AppConfig>()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final cached = sl<Prefs>().getString(PrefsKeys.customBaseUrl)?.trim();
|
||||||
|
if (cached != null && cached.isNotEmpty) {
|
||||||
|
sl<AppConfig>().setBaseUrl(cached);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_persistApiBaseUrl(sl<AppConfig>().baseUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _persistApiBaseUrl(String baseUrl) {
|
||||||
|
final normalized = baseUrl.trim();
|
||||||
|
if (normalized.isEmpty || !sl.isRegistered<Prefs>()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
unawaited(sl<Prefs>().setString(PrefsKeys.apiBaseUrl, normalized));
|
||||||
|
}
|
||||||
@@ -1,16 +1,70 @@
|
|||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
import 'dart:math';
|
||||||
|
|
||||||
import 'package:device_info_plus/device_info_plus.dart';
|
import 'package:device_info_plus/device_info_plus.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
/// Stable id of this install, sent as `hw_id` on push registration and on
|
||||||
|
/// video-call accept/decline.
|
||||||
|
///
|
||||||
|
/// Android `Build.ID` is the firmware id. Two phones on the same build share
|
||||||
|
/// it, so the backend treats them as one device and a decline on one does not
|
||||||
|
/// reach the other. A per-install id stays unique.
|
||||||
abstract final class DeviceHwIdProvider {
|
abstract final class DeviceHwIdProvider {
|
||||||
static Future<String?> current() async {
|
static const androidInstallIdKey = 'eatvio.android_install_hw_id';
|
||||||
final deviceInfo = DeviceInfoPlugin();
|
static const androidTokenMigratedKey = 'eatvio.android_hw_id_token_migrated';
|
||||||
|
|
||||||
|
static Future<String?> current({SharedPreferences? preferences}) async {
|
||||||
if (Platform.isIOS) {
|
if (Platform.isIOS) {
|
||||||
return (await deviceInfo.iosInfo).identifierForVendor;
|
return (await DeviceInfoPlugin().iosInfo).identifierForVendor;
|
||||||
}
|
}
|
||||||
if (Platform.isAndroid) {
|
if (Platform.isAndroid) {
|
||||||
return (await deviceInfo.androidInfo).id;
|
return androidInstallId(preferences: preferences);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static Future<String> androidInstallId({
|
||||||
|
SharedPreferences? preferences,
|
||||||
|
}) async {
|
||||||
|
final prefs = preferences ?? await SharedPreferences.getInstance();
|
||||||
|
final existing = prefs.getString(androidInstallIdKey)?.trim();
|
||||||
|
if (existing != null && existing.length >= 8) return existing;
|
||||||
|
|
||||||
|
final created = _newInstallId();
|
||||||
|
await prefs.setString(androidInstallIdKey, created);
|
||||||
|
return created;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The previous Android registration used `Build.ID`. Drop that token once
|
||||||
|
/// and register again with the install id.
|
||||||
|
static Future<bool> androidTokenNeedsReregister({
|
||||||
|
SharedPreferences? preferences,
|
||||||
|
}) async {
|
||||||
|
if (!Platform.isAndroid) return false;
|
||||||
|
final prefs = preferences ?? await SharedPreferences.getInstance();
|
||||||
|
return prefs.getBool(androidTokenMigratedKey) != true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Future<void> markAndroidTokenReregistered({
|
||||||
|
SharedPreferences? preferences,
|
||||||
|
}) async {
|
||||||
|
final prefs = preferences ?? await SharedPreferences.getInstance();
|
||||||
|
await prefs.setBool(androidTokenMigratedKey, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String _newInstallId() {
|
||||||
|
final random = Random.secure();
|
||||||
|
final bytes = List<int>.generate(16, (_) => random.nextInt(256));
|
||||||
|
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||||
|
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||||
|
final hex = bytes
|
||||||
|
.map((byte) => byte.toRadixString(16).padLeft(2, '0'))
|
||||||
|
.join();
|
||||||
|
return '${hex.substring(0, 8)}-'
|
||||||
|
'${hex.substring(8, 12)}-'
|
||||||
|
'${hex.substring(12, 16)}-'
|
||||||
|
'${hex.substring(16, 20)}-'
|
||||||
|
'${hex.substring(20)}';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,7 +42,8 @@ import 'package:eatvio_app/features/order_info/cubit/order_info_cubit.dart';
|
|||||||
import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_cubit.dart';
|
import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_cubit.dart';
|
||||||
import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart';
|
import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart';
|
||||||
import 'package:eatvio_app/features/plans/presentation/cubit/about_plan_cubit.dart';
|
import 'package:eatvio_app/features/plans/presentation/cubit/about_plan_cubit.dart';
|
||||||
import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart' as profile_plans;
|
import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart'
|
||||||
|
as profile_plans;
|
||||||
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart';
|
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart';
|
||||||
import 'package:eatvio_app/features/profile/presentation/bloc/sub_cubit/sub_cubit.dart';
|
import 'package:eatvio_app/features/profile/presentation/bloc/sub_cubit/sub_cubit.dart';
|
||||||
import 'package:eatvio_app/features/recipe/presentation/cubit/about_recipe_cubit.dart';
|
import 'package:eatvio_app/features/recipe/presentation/cubit/about_recipe_cubit.dart';
|
||||||
@@ -54,6 +55,7 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se
|
|||||||
import 'package:eatvio_app/features/user_details/presentation/cubit/user_details_cubit.dart';
|
import 'package:eatvio_app/features/user_details/presentation/cubit/user_details_cubit.dart';
|
||||||
import 'package:eatvio_app/features/video_calls/managers/video_call_manager.dart';
|
import 'package:eatvio_app/features/video_calls/managers/video_call_manager.dart';
|
||||||
import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart';
|
import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart';
|
||||||
|
import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart';
|
||||||
import 'package:eatvio_app/core/comments/comments_cubit/comments_cubit.dart';
|
import 'package:eatvio_app/core/comments/comments_cubit/comments_cubit.dart';
|
||||||
import 'package:get_it/get_it.dart';
|
import 'package:get_it/get_it.dart';
|
||||||
|
|
||||||
@@ -70,69 +72,174 @@ class CubitRegistrations {
|
|||||||
/// Регистрация Cubit'ов как синглтонов
|
/// Регистрация Cubit'ов как синглтонов
|
||||||
static void _registerSingletonCubits() {
|
static void _registerSingletonCubits() {
|
||||||
sl.registerLazySingleton<NewMessagesCubit>(() => NewMessagesCubit());
|
sl.registerLazySingleton<NewMessagesCubit>(() => NewMessagesCubit());
|
||||||
sl.registerLazySingleton<NotificationsCubit>(() => NotificationsCubit(wsManager: sl(), notificationsRepository: sl()));
|
sl.registerLazySingleton<NotificationsCubit>(
|
||||||
sl.registerLazySingleton<ProfileAvatarCubit>(() => ProfileAvatarCubit(profileRepository: sl()));
|
() => NotificationsCubit(wsManager: sl(), notificationsRepository: sl()),
|
||||||
sl.registerLazySingleton<ChatsCubit>(() => ChatsCubit(chatRepository: sl(), wsManager: sl(), profileRepository: sl()));
|
);
|
||||||
sl.registerLazySingleton<InternetConnectionCubit>(() => InternetConnectionCubit());
|
sl.registerLazySingleton<ProfileAvatarCubit>(
|
||||||
sl.registerLazySingleton<VideoCallManager>(
|
() => ProfileAvatarCubit(profileRepository: sl()),
|
||||||
() => VideoCallManager(
|
);
|
||||||
videoCallRepository: sl(),
|
sl.registerLazySingleton<ChatsCubit>(
|
||||||
|
() => ChatsCubit(
|
||||||
|
chatRepository: sl(),
|
||||||
|
wsManager: sl(),
|
||||||
profileRepository: sl(),
|
profileRepository: sl(),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
sl.registerLazySingleton<InternetConnectionCubit>(
|
||||||
|
() => InternetConnectionCubit(),
|
||||||
|
);
|
||||||
|
sl.registerLazySingleton<VideoCallManager>(
|
||||||
|
() =>
|
||||||
|
VideoCallManager(videoCallRepository: sl(), profileRepository: sl()),
|
||||||
|
);
|
||||||
sl.registerLazySingleton<VideoCallSessionCubit>(
|
sl.registerLazySingleton<VideoCallSessionCubit>(
|
||||||
() => VideoCallSessionCubit(
|
() => VideoCallSessionCubit(
|
||||||
videoCallManager: sl(),
|
videoCallManager: sl(),
|
||||||
systemPipCoordinator: sl(),
|
systemPipCoordinator: sl(),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
sl.registerLazySingleton<FeedCubit>(() => FeedCubit(feedRepository: sl()));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Регистрация Cubit'ов как фабрик
|
/// Регистрация Cubit'ов как фабрик
|
||||||
static void _registerFactoryCubits() {
|
static void _registerFactoryCubits() {
|
||||||
// Auth related cubits
|
// Auth related cubits
|
||||||
sl.registerFactory<AuthCubit>(() => AuthCubit(authRepository: sl(), firebaseApi: sl(), prefs: sl(), profileRepository: sl()));
|
sl.registerFactory<AuthCubit>(
|
||||||
sl.registerFactory<RegistrationCubit>(() => RegistrationCubit(registrationRepository: sl(), prefs: sl()));
|
() => AuthCubit(
|
||||||
sl.registerFactory<ResetPasswordCubit>(() => ResetPasswordCubit(resetPasswordRepository: sl()));
|
authRepository: sl(),
|
||||||
sl.registerFactory<VerifyEmailCubit>(() => VerifyEmailCubit(profileRepository: sl(), prefs: sl()));
|
firebaseApi: sl(),
|
||||||
sl.registerFactory<OAuthCubit>(() => OAuthCubit(authRepository: sl(), prefs: sl()));
|
prefs: sl(),
|
||||||
sl.registerFactory<RegistrationCubitV2>(() => RegistrationCubitV2(registrationRepository: sl()));
|
profileRepository: sl(),
|
||||||
|
sessionLifecycleService: sl(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
sl.registerFactory<RegistrationCubit>(
|
||||||
|
() => RegistrationCubit(
|
||||||
|
registrationRepository: sl(),
|
||||||
|
prefs: sl(),
|
||||||
|
sessionLifecycleService: sl(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
sl.registerFactory<ResetPasswordCubit>(
|
||||||
|
() => ResetPasswordCubit(resetPasswordRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<VerifyEmailCubit>(
|
||||||
|
() => VerifyEmailCubit(profileRepository: sl(), prefs: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<OAuthCubit>(
|
||||||
|
() => OAuthCubit(
|
||||||
|
authRepository: sl(),
|
||||||
|
firebaseApi: sl(),
|
||||||
|
prefs: sl(),
|
||||||
|
sessionLifecycleService: sl(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
sl.registerFactory<RegistrationCubitV2>(
|
||||||
|
() => RegistrationCubitV2(
|
||||||
|
registrationRepository: sl(),
|
||||||
|
firebaseApi: sl(),
|
||||||
|
sessionLifecycleService: sl(),
|
||||||
|
),
|
||||||
|
);
|
||||||
// Feed related cubits
|
// Feed related cubits
|
||||||
sl.registerFactory<FeedCubit>(() => FeedCubit(feedRepository: sl()));
|
sl.registerFactory<RecipesCubit>(
|
||||||
sl.registerFactory<RecipesCubit>(() => RecipesCubit(feedRepository: sl(), recipeRepository: sl(), aboutRecipeRepository: sl()));
|
() => RecipesCubit(
|
||||||
sl.registerFactory<DietsCubit>(() => DietsCubit(feedRepository: sl(), dietsRepository: sl()));
|
feedRepository: sl(),
|
||||||
sl.registerFactory<PlansCubit>(() => PlansCubit(feedRepository: sl(), planRepository: sl()));
|
recipeRepository: sl(),
|
||||||
sl.registerFactory<ConsultantsCubit>(() => ConsultantsCubit(feedRepository: sl()));
|
aboutRecipeRepository: sl(),
|
||||||
sl.registerFactory<CommentsCubit>(() => CommentsCubit(feedRepository: sl(), commentsRepository: sl()));
|
),
|
||||||
sl.registerFactory<FeedProfileCubit>(() => FeedProfileCubit(profileRepository: sl()));
|
);
|
||||||
|
sl.registerFactory<DietsCubit>(
|
||||||
|
() => DietsCubit(feedRepository: sl(), dietsRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<PlansCubit>(
|
||||||
|
() => PlansCubit(feedRepository: sl(), planRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<ConsultantsCubit>(
|
||||||
|
() => ConsultantsCubit(feedRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<CommentsCubit>(
|
||||||
|
() => CommentsCubit(feedRepository: sl(), commentsRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<FeedProfileCubit>(
|
||||||
|
() => FeedProfileCubit(profileRepository: sl()),
|
||||||
|
);
|
||||||
|
|
||||||
// Chat related cubits
|
// Chat related cubits
|
||||||
sl.registerFactory<ChatRoomCubit>(() => ChatRoomCubit(cardsRepository: sl(), chatRepository: sl(), wsManager: sl()));
|
sl.registerFactory<ChatRoomCubit>(
|
||||||
|
() => ChatRoomCubit(
|
||||||
|
cardsRepository: sl(),
|
||||||
|
chatRepository: sl(),
|
||||||
|
wsManager: sl(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
// Profile related cubits
|
// Profile related cubits
|
||||||
sl.registerFactory<ProfileCubit>(() => ProfileCubit(profileRepository: sl(), chatRepository: sl(), consultantRepository: sl()));
|
sl.registerFactory<ProfileCubit>(
|
||||||
sl.registerFactory<profile_plans.PlansCubit>(() => profile_plans.PlansCubit(plansRepository: sl()));
|
() => ProfileCubit(
|
||||||
|
profileRepository: sl(),
|
||||||
|
chatRepository: sl(),
|
||||||
|
consultantRepository: sl(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
sl.registerFactory<profile_plans.PlansCubit>(
|
||||||
|
() => profile_plans.PlansCubit(plansRepository: sl()),
|
||||||
|
);
|
||||||
sl.registerFactory<SubCubit>(() => SubCubit(profileRepository: sl()));
|
sl.registerFactory<SubCubit>(() => SubCubit(profileRepository: sl()));
|
||||||
|
|
||||||
// Content creation cubits
|
// Content creation cubits
|
||||||
sl.registerFactory<CreateDietCubit>(() => CreateDietCubit(profileRepository: sl(), createDietRepository: sl(), glossaryRepository: sl()));
|
sl.registerFactory<CreateDietCubit>(
|
||||||
sl.registerFactory<CreatePlanCubit>(() => CreatePlanCubit(createPlanRepository: sl()));
|
() => CreateDietCubit(
|
||||||
sl.registerFactory<CreateRecipeCubit>(() => CreateRecipeCubit(recipeRepository: sl(), glossaryRepository: sl()));
|
profileRepository: sl(),
|
||||||
sl.registerFactory<BlogPostCreateCubit>(() => BlogPostCreateCubit(blogPostRepository: sl()));
|
createDietRepository: sl(),
|
||||||
|
glossaryRepository: sl(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
sl.registerFactory<CreatePlanCubit>(
|
||||||
|
() => CreatePlanCubit(createPlanRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<CreateRecipeCubit>(
|
||||||
|
() => CreateRecipeCubit(recipeRepository: sl(), glossaryRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<BlogPostCreateCubit>(
|
||||||
|
() => BlogPostCreateCubit(blogPostRepository: sl()),
|
||||||
|
);
|
||||||
|
|
||||||
// Content viewing cubits
|
// Content viewing cubits
|
||||||
sl.registerFactory<AboutDietCubit>(() => AboutDietCubit(dietsRepository: sl(), profileRepository: sl()));
|
sl.registerFactory<AboutDietCubit>(
|
||||||
sl.registerFactory<AboutPlanCubit>(() => AboutPlanCubit(planRepository: sl(), profileRepository: sl(), dietRepository: sl()));
|
() => AboutDietCubit(dietsRepository: sl(), profileRepository: sl()),
|
||||||
sl.registerFactory<AboutRecipeCubit>(() => AboutRecipeCubit(recipeRepository: sl(), profileRepository: sl()));
|
);
|
||||||
|
sl.registerFactory<AboutPlanCubit>(
|
||||||
|
() => AboutPlanCubit(
|
||||||
|
planRepository: sl(),
|
||||||
|
profileRepository: sl(),
|
||||||
|
dietRepository: sl(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
sl.registerFactory<AboutRecipeCubit>(
|
||||||
|
() => AboutRecipeCubit(recipeRepository: sl(), profileRepository: sl()),
|
||||||
|
);
|
||||||
sl.registerFactory<BlogPostCubit>(() => BlogPostCubit(sl()));
|
sl.registerFactory<BlogPostCubit>(() => BlogPostCubit(sl()));
|
||||||
|
|
||||||
// User content cubits
|
// User content cubits
|
||||||
sl.registerFactory<MyDietsCubit>(() => MyDietsCubit(myDietsRepository: sl(), createDietRepository: sl()));
|
sl.registerFactory<MyDietsCubit>(
|
||||||
sl.registerFactory<MyPlansCubit>(() => MyPlansCubit(myPlansRepository: sl()));
|
() => MyDietsCubit(myDietsRepository: sl(), createDietRepository: sl()),
|
||||||
sl.registerFactory<MyRecipesCubit>(() => MyRecipesCubit(myRecipesRepository: sl(), aboutRecipeRepository: sl(), recipeRepository: sl()));
|
);
|
||||||
|
sl.registerFactory<MyPlansCubit>(
|
||||||
|
() => MyPlansCubit(myPlansRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<MyRecipesCubit>(
|
||||||
|
() => MyRecipesCubit(
|
||||||
|
myRecipesRepository: sl(),
|
||||||
|
aboutRecipeRepository: sl(),
|
||||||
|
recipeRepository: sl(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
// Other feature cubits
|
// Other feature cubits
|
||||||
sl.registerFactory<CalendarCubit>(() => CalendarCubit(calendarRepository: sl()));
|
sl.registerFactory<CalendarCubit>(
|
||||||
|
() => CalendarCubit(calendarRepository: sl()),
|
||||||
|
);
|
||||||
sl.registerFactory<DiaryCubit>(
|
sl.registerFactory<DiaryCubit>(
|
||||||
() => DiaryCubit(
|
() => DiaryCubit(
|
||||||
chatRepository: sl(),
|
chatRepository: sl(),
|
||||||
@@ -144,28 +251,77 @@ class CubitRegistrations {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
sl.registerFactory<SettingsCubit>(
|
sl.registerFactory<SettingsCubit>(
|
||||||
() => SettingsCubit(profileRepository: sl(), settingsRepository: sl(), consultantRepository: sl(), consultationsRepository: sl()),
|
() => SettingsCubit(
|
||||||
|
profileRepository: sl(),
|
||||||
|
settingsRepository: sl(),
|
||||||
|
consultantRepository: sl(),
|
||||||
|
consultationsRepository: sl(),
|
||||||
|
sessionLifecycleService: sl(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
sl.registerFactory<RegisterConsultantCubit>(
|
||||||
|
() => RegisterConsultantCubit(consultantRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<ComplainingCubit>(
|
||||||
|
() => ComplainingCubit(repository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<UserCardsCubit>(
|
||||||
|
() => UserCardsCubit(cardsRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<OrderInfoCubit>(
|
||||||
|
() => OrderInfoCubit(chatRepository: sl(), profileRepository: sl()),
|
||||||
);
|
);
|
||||||
sl.registerFactory<RegisterConsultantCubit>(() => RegisterConsultantCubit(consultantRepository: sl()));
|
|
||||||
sl.registerFactory<ComplainingCubit>(() => ComplainingCubit(repository: sl()));
|
|
||||||
sl.registerFactory<UserCardsCubit>(() => UserCardsCubit(cardsRepository: sl()));
|
|
||||||
sl.registerFactory<OrderInfoCubit>(() => OrderInfoCubit(chatRepository: sl(), profileRepository: sl()));
|
|
||||||
sl.registerFactory<ConsultationPaymentCubit>(
|
sl.registerFactory<ConsultationPaymentCubit>(
|
||||||
() => ConsultationPaymentCubit(paymentRepository: sl(), sbpRepository: sl()),
|
() => ConsultationPaymentCubit(
|
||||||
|
paymentRepository: sl(),
|
||||||
|
sbpRepository: sl(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
sl.registerFactory<ConsultationsCubit>(
|
||||||
|
() => ConsultationsCubit(consultationsRepository: sl(), chatRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<ConsultantCommentsCubit>(
|
||||||
|
() => ConsultantCommentsCubit(diaryRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<CancelPlanCubit>(
|
||||||
|
() => CancelPlanCubit(cancelPlanRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<ConsultationsArchiveCubit>(
|
||||||
|
() => ConsultationsArchiveCubit(consultationsRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<ConsultantFinancesCubit>(
|
||||||
|
() => ConsultantFinancesCubit(consultationsRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<UserPurchasesCubit>(
|
||||||
|
() => UserPurchasesCubit(consultationsRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<BlockedUsersCubit>(
|
||||||
|
() => BlockedUsersCubit(blockedUsersRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<NotificationSettingsCubit>(
|
||||||
|
() => NotificationSettingsCubit(notificationSettingsRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<ConsultantRatingCubit>(
|
||||||
|
() => ConsultantRatingCubit(
|
||||||
|
feedRepository: sl(),
|
||||||
|
repository: sl(),
|
||||||
|
profileRepository: sl(),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
sl.registerFactory<ConsultationsCubit>(() => ConsultationsCubit(consultationsRepository: sl()));
|
|
||||||
sl.registerFactory<ConsultantCommentsCubit>(() => ConsultantCommentsCubit(diaryRepository: sl()));
|
|
||||||
sl.registerFactory<CancelPlanCubit>(() => CancelPlanCubit(cancelPlanRepository: sl()));
|
|
||||||
sl.registerFactory<ConsultationsArchiveCubit>(() => ConsultationsArchiveCubit(consultationsRepository: sl()));
|
|
||||||
sl.registerFactory<ConsultantFinancesCubit>(() => ConsultantFinancesCubit(consultationsRepository: sl()));
|
|
||||||
sl.registerFactory<UserPurchasesCubit>(() => UserPurchasesCubit(consultationsRepository: sl()));
|
|
||||||
sl.registerFactory<BlockedUsersCubit>(() => BlockedUsersCubit(blockedUsersRepository: sl()));
|
|
||||||
sl.registerFactory<NotificationSettingsCubit>(() => NotificationSettingsCubit(notificationSettingsRepository: sl()));
|
|
||||||
sl.registerFactory<ConsultantRatingCubit>(() => ConsultantRatingCubit(feedRepository: sl(), repository: sl(), profileRepository: sl()));
|
|
||||||
sl.registerFactory<ViewsCubit>(() => ViewsCubit(viewsRepository: sl()));
|
sl.registerFactory<ViewsCubit>(() => ViewsCubit(viewsRepository: sl()));
|
||||||
sl.registerFactory<UserDetailsCubit>(() => UserDetailsCubit(profileRepository: sl()));
|
sl.registerFactory<UserDetailsCubit>(
|
||||||
sl.registerFactory<MenuCubit>(() => MenuCubit(sl()));
|
() => UserDetailsCubit(profileRepository: sl()),
|
||||||
|
);
|
||||||
|
sl.registerFactory<MenuCubit>(() => MenuCubit(sl(), sl()));
|
||||||
sl.registerFactory<MarketingCubit>(() => MarketingCubit(sl()));
|
sl.registerFactory<MarketingCubit>(() => MarketingCubit(sl()));
|
||||||
sl.registerFactory<PersonalDietSuggestionCubit>(() => PersonalDietSuggestionCubit(dietRepository: sl(), personalDietSuggestionService: sl()));
|
sl.registerFactory<PersonalDietSuggestionCubit>(
|
||||||
|
() => PersonalDietSuggestionCubit(
|
||||||
|
dietRepository: sl(),
|
||||||
|
personalDietSuggestionService: sl(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
sl.registerFactory<VideoCallRecordingsCubit>(
|
||||||
|
() => VideoCallRecordingsCubit(repository: sl()),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ import 'package:eatvio_app/features/recipe/repositories/my_recipes_repository.da
|
|||||||
import 'package:eatvio_app/features/registration/repositories/registration_repository.dart';
|
import 'package:eatvio_app/features/registration/repositories/registration_repository.dart';
|
||||||
import 'package:eatvio_app/features/registration_v2/repositories/registration_repository_v2.dart';
|
import 'package:eatvio_app/features/registration_v2/repositories/registration_repository_v2.dart';
|
||||||
import 'package:eatvio_app/features/settings/repositories/service_repository.dart';
|
import 'package:eatvio_app/features/settings/repositories/service_repository.dart';
|
||||||
|
import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart';
|
||||||
import 'package:eatvio_app/features/video_calls/repositories/video_call_repository.dart';
|
import 'package:eatvio_app/features/video_calls/repositories/video_call_repository.dart';
|
||||||
import 'package:get_it/get_it.dart';
|
import 'package:get_it/get_it.dart';
|
||||||
|
|
||||||
@@ -53,6 +54,9 @@ class RepositoryRegistrations {
|
|||||||
// Core repositories
|
// Core repositories
|
||||||
sl.registerLazySingleton<ChatRepository>(() => ChatRepository(chatService: sl()));
|
sl.registerLazySingleton<ChatRepository>(() => ChatRepository(chatService: sl()));
|
||||||
sl.registerLazySingleton<VideoCallRepository>(() => VideoCallRepository(videoCallService: sl()));
|
sl.registerLazySingleton<VideoCallRepository>(() => VideoCallRepository(videoCallService: sl()));
|
||||||
|
sl.registerLazySingleton<VideoCallRecordingsRepository>(
|
||||||
|
() => VideoCallRecordingsRepository(videoCallService: sl(), dio: sl()),
|
||||||
|
);
|
||||||
sl.registerLazySingleton<FeedRepository>(() => FeedRepository(feedService: sl()));
|
sl.registerLazySingleton<FeedRepository>(() => FeedRepository(feedService: sl()));
|
||||||
sl.registerLazySingleton<ProfileRepository>(() => ProfileRepository(profileService: sl()));
|
sl.registerLazySingleton<ProfileRepository>(() => ProfileRepository(profileService: sl()));
|
||||||
sl.registerLazySingleton<CalendarRepository>(() => CalendarRepository(calendarService: sl()));
|
sl.registerLazySingleton<CalendarRepository>(() => CalendarRepository(calendarService: sl()));
|
||||||
|
|||||||
15
lib/core/di/session_registrations.dart
Normal file
15
lib/core/di/session_registrations.dart
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import 'package:eatvio_app/core/error_reporting/error_reporter.dart';
|
||||||
|
import 'package:eatvio_app/core/locator_service.dart';
|
||||||
|
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||||
|
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
||||||
|
|
||||||
|
class SessionRegistrations {
|
||||||
|
static void registerAll() {
|
||||||
|
sl.registerLazySingleton<SessionLifecycleService>(
|
||||||
|
() => SessionLifecycleService(
|
||||||
|
wsManager: sl<WsManager>(),
|
||||||
|
errorReporter: sl<ErrorReporter>(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import 'dart:developer';
|
|||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
import 'package:eatvio_app/core/app_config.dart';
|
import 'package:eatvio_app/core/app_config.dart';
|
||||||
import 'package:eatvio_app/core/app_initializer.dart';
|
import 'package:eatvio_app/core/app_initializer.dart';
|
||||||
|
import 'package:eatvio_app/core/device/device_hw_id_provider.dart';
|
||||||
import 'package:eatvio_app/core/notifications/notification_permission_requester.dart';
|
import 'package:eatvio_app/core/notifications/notification_permission_requester.dart';
|
||||||
import 'package:eatvio_app/core/push/hms_client_error.dart';
|
import 'package:eatvio_app/core/push/hms_client_error.dart';
|
||||||
import 'package:device_info_plus/device_info_plus.dart';
|
import 'package:device_info_plus/device_info_plus.dart';
|
||||||
@@ -44,15 +45,16 @@ class FirebaseApi {
|
|||||||
Future<void> registerAnonymousPushToken() async {
|
Future<void> registerAnonymousPushToken() async {
|
||||||
try {
|
try {
|
||||||
await _requestNotificationPermission();
|
await _requestNotificationPermission();
|
||||||
final deviceInfo = DeviceInfoPlugin();
|
|
||||||
final credentials = await _resolvePushCredentials();
|
final credentials = await _resolvePushCredentials();
|
||||||
final token = credentials.token;
|
final token = credentials.token;
|
||||||
if (token == null || token.isEmpty) return;
|
if (token == null || token.isEmpty) return;
|
||||||
|
final hwId = await DeviceHwIdProvider.current();
|
||||||
|
if (hwId == null || hwId.length < 8) return;
|
||||||
await sl<Dio>().post(
|
await sl<Dio>().post(
|
||||||
'/api/anonymous_token',
|
'/api/anonymous_token',
|
||||||
data: {
|
data: {
|
||||||
'platform': credentials.platform,
|
'platform': credentials.platform,
|
||||||
'hw_id': Platform.isIOS ? (await deviceInfo.iosInfo).identifierForVendor : (await deviceInfo.androidInfo).id,
|
'hw_id': hwId,
|
||||||
'token': token,
|
'token': token,
|
||||||
},
|
},
|
||||||
).timeout(
|
).timeout(
|
||||||
@@ -69,34 +71,52 @@ class FirebaseApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> registerPushToken() async {
|
Future<void> registerPushToken() async {
|
||||||
if (await TokenStorage.haveTokenInStorage()) {
|
if (!await TokenStorage.haveTokenInStorage()) return;
|
||||||
try {
|
try {
|
||||||
await _requestNotificationPermission();
|
await _requestNotificationPermission();
|
||||||
final deviceInfo = DeviceInfoPlugin();
|
final credentials = await _resolvePushCredentials();
|
||||||
final credentials = await _resolvePushCredentials();
|
final token = credentials.token;
|
||||||
final token = credentials.token;
|
final hwId = await DeviceHwIdProvider.current();
|
||||||
if (token == null || token.isEmpty) return;
|
final reregisterAndroid =
|
||||||
await sl<Dio>().post(
|
await DeviceHwIdProvider.androidTokenNeedsReregister();
|
||||||
'/api/profile/notification/token/register',
|
if (token != null &&
|
||||||
data: {
|
token.isNotEmpty &&
|
||||||
'platform': credentials.platform,
|
hwId != null &&
|
||||||
'hw_id': Platform.isIOS ? (await deviceInfo.iosInfo).identifierForVendor : (await deviceInfo.androidInfo).id,
|
hwId.length >= 8) {
|
||||||
'token': token,
|
if (reregisterAndroid) {
|
||||||
},
|
try {
|
||||||
).timeout(
|
await unregisterPushToken();
|
||||||
const Duration(seconds: 10),
|
} catch (_) {}
|
||||||
onTimeout: () {
|
}
|
||||||
throw TimeoutException('registerPushToken timeout');
|
await sl<Dio>()
|
||||||
},
|
.post(
|
||||||
);
|
'/api/profile/notification/token/register',
|
||||||
if (Platform.isIOS) {
|
data: {
|
||||||
await _registerIosVoipPushToken();
|
'platform': credentials.platform,
|
||||||
|
'hw_id': hwId,
|
||||||
|
'token': token,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.timeout(
|
||||||
|
const Duration(seconds: 10),
|
||||||
|
onTimeout: () {
|
||||||
|
throw TimeoutException('registerPushToken timeout');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (reregisterAndroid) {
|
||||||
|
await DeviceHwIdProvider.markAndroidTokenReregistered();
|
||||||
}
|
}
|
||||||
} catch (e, st) {
|
|
||||||
log(e.toString(), stackTrace: st);
|
|
||||||
await _errorReporter.report(e, st, origin: 'FirebaseApi');
|
|
||||||
// Не пробрасываем ошибку дальше, так как это не критичная операция
|
|
||||||
}
|
}
|
||||||
|
} catch (e, st) {
|
||||||
|
log(e.toString(), stackTrace: st);
|
||||||
|
await _errorReporter.report(e, st, origin: 'FirebaseApi');
|
||||||
|
// Не пробрасываем ошибку дальше, так как это не критичная операция
|
||||||
|
}
|
||||||
|
// Incoming calls on iOS come only through the VoIP token. It does not
|
||||||
|
// depend on the FCM token, so a missing or failed FCM registration must
|
||||||
|
// not leave the device without calls.
|
||||||
|
if (Platform.isIOS) {
|
||||||
|
await _registerIosVoipPushToken();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,12 +162,13 @@ class FirebaseApi {
|
|||||||
final token = (await FlutterCallkitIncoming.getDevicePushTokenVoIP())?.trim();
|
final token = (await FlutterCallkitIncoming.getDevicePushTokenVoIP())?.trim();
|
||||||
if (token == null || token.isEmpty) return;
|
if (token == null || token.isEmpty) return;
|
||||||
|
|
||||||
final deviceInfo = DeviceInfoPlugin();
|
final hwId = await DeviceHwIdProvider.current();
|
||||||
|
if (hwId == null || hwId.length < 8) return;
|
||||||
await sl<Dio>().post(
|
await sl<Dio>().post(
|
||||||
'/api/profile/notification/token/voip/register',
|
'/api/profile/notification/token/voip/register',
|
||||||
data: {
|
data: {
|
||||||
'platform': 'ios',
|
'platform': 'ios',
|
||||||
'hw_id': (await deviceInfo.iosInfo).identifierForVendor,
|
'hw_id': hwId,
|
||||||
'token': token,
|
'token': token,
|
||||||
},
|
},
|
||||||
).timeout(
|
).timeout(
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import 'package:dio/dio.dart';
|
import 'package:dio/dio.dart';
|
||||||
import 'package:eatvio_app/core/app_router.dart';
|
import 'package:eatvio_app/core/app_router.dart';
|
||||||
|
import 'package:eatvio_app/core/interceptors/verification_requirement.dart';
|
||||||
import 'package:eatvio_app/core/locator_service.dart';
|
import 'package:eatvio_app/core/locator_service.dart';
|
||||||
import 'package:eatvio_app/core/routing/route_constants.dart';
|
import 'package:eatvio_app/core/routing/route_constants.dart';
|
||||||
import 'package:eatvio_app/core/widgets/show_error_dialog.dart';
|
import 'package:eatvio_app/core/widgets/show_error_dialog.dart';
|
||||||
@@ -9,28 +10,77 @@ import 'package:go_router/go_router.dart';
|
|||||||
class PhoneVerifyErrorInterceptor extends Interceptor {
|
class PhoneVerifyErrorInterceptor extends Interceptor {
|
||||||
@override
|
@override
|
||||||
void onError(DioException err, ErrorInterceptorHandler handler) async {
|
void onError(DioException err, ErrorInterceptorHandler handler) async {
|
||||||
if (err.response?.statusCode == 405) {
|
if (err.response?.statusCode != 405) {
|
||||||
final data = err.response?.data;
|
return handler.next(err);
|
||||||
|
}
|
||||||
if (data is Map<String, dynamic> && data['type'] == 'unverificated_phone') {
|
|
||||||
final String phone = await sl<ProfileRepository>().getMyPhone();
|
final requirement = VerificationRequirement.tryParse(err.response?.data);
|
||||||
final String passKey = await sl<ProfileRepository>().getPassKey(routeName: 'user_detailz.change-phone-verify', routeParams: {"phone": phone});
|
if (requirement == null) {
|
||||||
await showErrorDialog(
|
return handler.next(err);
|
||||||
AppRouter.navigatorKey.currentContext!,
|
}
|
||||||
title: 'Привяжите номер телефона',
|
|
||||||
description: 'Для того, что бы выполнить это действие необходимо привязать номер телефона',
|
// Бэкенд может требовать подтверждения почты, телефона или обоих каналов сразу.
|
||||||
);
|
if (requirement.needsEmail) {
|
||||||
final currentContext = AppRouter.navigatorKey.currentContext;
|
await _handleEmailVerificationRequired();
|
||||||
|
} else {
|
||||||
if (currentContext != null && currentContext.mounted && GoRouter.of(currentContext).state.path == RouteConstants.stepperBecomeConsultantScreen) {
|
await _handlePhoneVerificationRequired();
|
||||||
GoRouter.of(currentContext).pop();
|
}
|
||||||
}
|
|
||||||
AppRouter.navigatorKey.currentContext?.pushNamed('verifyScreen', extra: passKey);
|
return handler.reject(
|
||||||
return handler.reject(
|
DioException(
|
||||||
DioException(requestOptions: err.requestOptions, response: err.response, error: 'Phone number not verified', type: DioExceptionType.badResponse),
|
requestOptions: err.requestOptions,
|
||||||
);
|
response: err.response,
|
||||||
}
|
error: 'Phone number not verified',
|
||||||
|
type: DioExceptionType.badResponse,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Старый сценарий: показывает привязку телефона и открывает passkey-экран.
|
||||||
|
Future<void> _handlePhoneVerificationRequired() async {
|
||||||
|
final String phone = await sl<ProfileRepository>().getMyPhone();
|
||||||
|
final String passKey = await sl<ProfileRepository>().getPassKey(
|
||||||
|
routeName: 'user_detailz.change-phone-verify',
|
||||||
|
routeParams: {"phone": phone},
|
||||||
|
);
|
||||||
|
await showErrorDialog(
|
||||||
|
AppRouter.navigatorKey.currentContext!,
|
||||||
|
title: 'Привяжите номер телефона',
|
||||||
|
description:
|
||||||
|
'Для того, что бы выполнить это действие необходимо привязать номер телефона',
|
||||||
|
);
|
||||||
|
final currentContext = AppRouter.navigatorKey.currentContext;
|
||||||
|
|
||||||
|
if (currentContext != null &&
|
||||||
|
currentContext.mounted &&
|
||||||
|
GoRouter.of(currentContext).state.path ==
|
||||||
|
RouteConstants.stepperBecomeConsultantScreen) {
|
||||||
|
GoRouter.of(currentContext).pop();
|
||||||
|
}
|
||||||
|
AppRouter.navigatorKey.currentContext?.pushNamed(
|
||||||
|
'verifyScreen',
|
||||||
|
extra: passKey,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Новый сценарий: предлагает подтвердить e-mail и открывает экран ввода кода.
|
||||||
|
Future<void> _handleEmailVerificationRequired() async {
|
||||||
|
final context = AppRouter.navigatorKey.currentContext;
|
||||||
|
|
||||||
|
if (context == null || !context.mounted) {
|
||||||
|
// UI недоступен (например, в тестах) — просто отклоняем запрос, без падения.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await showErrorDialog(
|
||||||
|
context,
|
||||||
|
title: 'Подтвердите e-mail',
|
||||||
|
description:
|
||||||
|
'Чтобы публиковать материалы, подтвердите адрес электронной почты. Мы отправим код на вашу почту.',
|
||||||
|
);
|
||||||
|
|
||||||
|
if (context.mounted) {
|
||||||
|
context.pushNamed('verifyEmailScreen', extra: true);
|
||||||
}
|
}
|
||||||
return handler.next(err);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import 'package:dio/dio.dart';
|
import 'package:dio/dio.dart';
|
||||||
import 'package:eatvio_app/core/app_router.dart';
|
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||||
import 'package:eatvio_app/core/token_storage.dart';
|
import 'package:eatvio_app/core/token_storage.dart';
|
||||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
|
||||||
import 'package:eatvio_app/core/locator_service.dart';
|
import 'package:eatvio_app/core/locator_service.dart';
|
||||||
import 'package:go_router/go_router.dart';
|
|
||||||
|
|
||||||
class TokenInterceptor extends Interceptor {
|
class TokenInterceptor extends Interceptor {
|
||||||
@override
|
@override
|
||||||
@@ -14,6 +12,7 @@ class TokenInterceptor extends Interceptor {
|
|||||||
final token = await TokenStorage.getTokenFromStorage();
|
final token = await TokenStorage.getTokenFromStorage();
|
||||||
if (token != null && token.isNotEmpty) {
|
if (token != null && token.isNotEmpty) {
|
||||||
options.headers['Authorization'] = 'Bearer $token';
|
options.headers['Authorization'] = 'Bearer $token';
|
||||||
|
options.extra['authToken'] = token;
|
||||||
}
|
}
|
||||||
|
|
||||||
super.onRequest(options, handler);
|
super.onRequest(options, handler);
|
||||||
@@ -25,9 +24,18 @@ class TokenInterceptor extends Interceptor {
|
|||||||
ErrorInterceptorHandler handler,
|
ErrorInterceptorHandler handler,
|
||||||
) async {
|
) async {
|
||||||
if (err.response?.statusCode == 401) {
|
if (err.response?.statusCode == 401) {
|
||||||
await sl<WsManager>().clear();
|
final requestCarriedAuth = err.requestOptions.headers.containsKey(
|
||||||
await TokenStorage.removeTokenInStorage();
|
'Authorization',
|
||||||
AppRouter.navigatorKey.currentContext?.go('/auth-screen');
|
);
|
||||||
|
final requestToken = err.requestOptions.extra['authToken'];
|
||||||
|
final currentToken = await TokenStorage.getTokenFromStorage();
|
||||||
|
if (requestCarriedAuth &&
|
||||||
|
requestToken != null &&
|
||||||
|
requestToken == currentToken) {
|
||||||
|
await sl<SessionLifecycleService>().endSession(
|
||||||
|
reason: SessionEndReason.unauthorized,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
super.onError(err, handler);
|
super.onError(err, handler);
|
||||||
}
|
}
|
||||||
|
|||||||
61
lib/core/interceptors/verification_requirement.dart
Normal file
61
lib/core/interceptors/verification_requirement.dart
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
/// Канал верификации, которого не хватает для публичного действия.
|
||||||
|
enum VerificationChannel { phone, email }
|
||||||
|
|
||||||
|
/// Разбор 405-контракта верификации (type/reason/missing) в список каналов.
|
||||||
|
///
|
||||||
|
/// Бэкенд отвечает на публичное действие без подтверждения так:
|
||||||
|
/// `{"type": "unverificated_phone", "reason": "verification_required", "missing": ["email"]}`.
|
||||||
|
/// Старые ответы не содержали поля `missing` — тогда не хватало только телефона.
|
||||||
|
class VerificationRequirement {
|
||||||
|
const VerificationRequirement({required this.missing});
|
||||||
|
|
||||||
|
/// Каналы, подтверждение которых требует бэкенд.
|
||||||
|
final List<VerificationChannel> missing;
|
||||||
|
|
||||||
|
bool get needsEmail => missing.contains(VerificationChannel.email);
|
||||||
|
|
||||||
|
bool get needsPhone => missing.contains(VerificationChannel.phone);
|
||||||
|
|
||||||
|
/// Возвращает null, если ответ не является отказом верификации.
|
||||||
|
static VerificationRequirement? tryParse(Object? data) {
|
||||||
|
if (data is! Map) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (data['type'] != 'unverificated_phone') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
final Object? rawMissing = data['missing'];
|
||||||
|
if (rawMissing is! List) {
|
||||||
|
// Legacy-контракт: поля missing не было, значит не подтверждён телефон.
|
||||||
|
return const VerificationRequirement(
|
||||||
|
missing: [VerificationChannel.phone],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
var hasPhone = false;
|
||||||
|
var hasEmail = false;
|
||||||
|
for (final Object? value in rawMissing) {
|
||||||
|
// Неизвестные значения игнорируем, чтобы новые каналы бэкенда не ломали разбор.
|
||||||
|
if (value == 'phone') {
|
||||||
|
hasPhone = true;
|
||||||
|
} else if (value == 'email') {
|
||||||
|
hasEmail = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Пустой или нераспознанный missing трактуем как legacy-контракт «телефон».
|
||||||
|
if (!hasPhone && !hasEmail) {
|
||||||
|
return const VerificationRequirement(
|
||||||
|
missing: [VerificationChannel.phone],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return VerificationRequirement(
|
||||||
|
missing: [
|
||||||
|
if (hasPhone) VerificationChannel.phone,
|
||||||
|
if (hasEmail) VerificationChannel.email,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
import 'package:eatvio_app/core/app_initializer.dart';
|
import 'package:eatvio_app/core/app_initializer.dart';
|
||||||
|
import 'package:eatvio_app/core/cached_base_url.dart';
|
||||||
import 'package:eatvio_app/core/di/app_config_registration.dart';
|
import 'package:eatvio_app/core/di/app_config_registration.dart';
|
||||||
import 'package:eatvio_app/core/di/cubit_registrations.dart';
|
import 'package:eatvio_app/core/di/cubit_registrations.dart';
|
||||||
import 'package:eatvio_app/core/di/external_registrations.dart';
|
import 'package:eatvio_app/core/di/external_registrations.dart';
|
||||||
import 'package:eatvio_app/core/di/repository_registrations.dart';
|
import 'package:eatvio_app/core/di/repository_registrations.dart';
|
||||||
import 'package:eatvio_app/core/di/service_registrations.dart';
|
import 'package:eatvio_app/core/di/service_registrations.dart';
|
||||||
|
import 'package:eatvio_app/core/di/session_registrations.dart';
|
||||||
import 'package:eatvio_app/core/prefs.dart';
|
import 'package:eatvio_app/core/prefs.dart';
|
||||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
||||||
import 'package:get_it/get_it.dart';
|
import 'package:get_it/get_it.dart';
|
||||||
@@ -21,6 +23,8 @@ Future<void> init({required AppBuildType buildType}) async {
|
|||||||
|
|
||||||
// Ожидание инициализации асинхронных зависимостей
|
// Ожидание инициализации асинхронных зависимостей
|
||||||
await sl.getAsync<Prefs>();
|
await sl.getAsync<Prefs>();
|
||||||
|
// До создания Dio и любых запросов к бэкенду.
|
||||||
|
applyCachedBaseUrl();
|
||||||
|
|
||||||
// Регистрация сервисов
|
// Регистрация сервисов
|
||||||
ServiceRegistrations.registerAll();
|
ServiceRegistrations.registerAll();
|
||||||
@@ -32,5 +36,9 @@ Future<void> init({required AppBuildType buildType}) async {
|
|||||||
CubitRegistrations.registerAll();
|
CubitRegistrations.registerAll();
|
||||||
|
|
||||||
// Регистрация WebSocket менеджера
|
// Регистрация WebSocket менеджера
|
||||||
sl.registerLazySingleton<WsManager>(() => WsManager(wsService: sl(), errorReporter: sl()));
|
sl.registerLazySingleton<WsManager>(
|
||||||
|
() => WsManager(wsService: sl(), errorReporter: sl()),
|
||||||
|
);
|
||||||
|
|
||||||
|
SessionRegistrations.registerAll();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,10 +62,18 @@ class PushNavigationHandler {
|
|||||||
final endedPayload = VideoCallEndedPushPayload.tryParse(data);
|
final endedPayload = VideoCallEndedPushPayload.tryParse(data);
|
||||||
if (endedPayload != null) {
|
if (endedPayload != null) {
|
||||||
developer.log(
|
developer.log(
|
||||||
'PushNavigationHandler: dismiss incoming call UI, source=$source',
|
'PushNavigationHandler: dismiss incoming call UI, source=$source '
|
||||||
|
'call_id=${endedPayload.callId ?? '-'} '
|
||||||
|
'reason=${endedPayload.reason?.name ?? '-'}',
|
||||||
name: 'PushNavigationHandler',
|
name: 'PushNavigationHandler',
|
||||||
);
|
);
|
||||||
unawaited(VideoCallEndedPushHandler.dismissIncomingCallUi());
|
unawaited(
|
||||||
|
VideoCallEndedPushHandler.dismissIncomingCallUi(
|
||||||
|
conversationUuid: endedPayload.conversationUuid,
|
||||||
|
callId: endedPayload.callId,
|
||||||
|
reason: endedPayload.reason,
|
||||||
|
),
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1 +1,9 @@
|
|||||||
enum PrefsKeys { hasAnonymousTokenBeenSent, welcomeScreenWasShowed, registrationDate, marketingBottomSheetHasBeenShown, isEmailVerificationSkipped }
|
enum PrefsKeys {
|
||||||
|
hasAnonymousTokenBeenSent,
|
||||||
|
welcomeScreenWasShowed,
|
||||||
|
registrationDate,
|
||||||
|
marketingBottomSheetHasBeenShown,
|
||||||
|
isEmailVerificationSkipped,
|
||||||
|
customBaseUrl,
|
||||||
|
apiBaseUrl,
|
||||||
|
}
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ class AuthRoutes {
|
|||||||
name: 'verifyScreen',
|
name: 'verifyScreen',
|
||||||
builder: (context, state) => VerifyScreen(passKey: state.extra as String),
|
builder: (context, state) => VerifyScreen(passKey: state.extra as String),
|
||||||
),
|
),
|
||||||
GoRoute(path: RouteConstants.verifyEmailScreen, name: 'verifyEmailScreen', builder: (context, state) => const VerifyEmailScreen()),
|
GoRoute(path: RouteConstants.verifyEmailScreen, name: 'verifyEmailScreen', builder: (context, state) => VerifyEmailScreen(returnOnSuccess: state.extra == true)),
|
||||||
GoRoute(
|
GoRoute(
|
||||||
path: RouteConstants.registerViaSocialScreen,
|
path: RouteConstants.registerViaSocialScreen,
|
||||||
name: 'registerViaSocialScreen',
|
name: 'registerViaSocialScreen',
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import 'package:eatvio_app/core/routing/route_constants.dart';
|
import 'package:eatvio_app/core/routing/route_constants.dart';
|
||||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
|
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
|
||||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_state.dart';
|
|
||||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/widgets/bottom_nav_scope.dart';
|
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/widgets/bottom_nav_scope.dart';
|
||||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart';
|
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart';
|
||||||
import 'package:eatvio_app/features/chat/presentation/pages/chats_screen.dart';
|
import 'package:eatvio_app/features/chat/presentation/pages/chats_screen.dart';
|
||||||
@@ -24,14 +23,10 @@ class MainNavigationRoutes {
|
|||||||
return [
|
return [
|
||||||
ShellRoute(
|
ShellRoute(
|
||||||
builder: (context, state, child) {
|
builder: (context, state, child) {
|
||||||
// Инициализация ProfileAvatarCubit при первом использовании ShellRoute
|
|
||||||
final profileAvatarCubit = context.read<ProfileAvatarCubit>();
|
final profileAvatarCubit = context.read<ProfileAvatarCubit>();
|
||||||
if (profileAvatarCubit.state is ProfileAvatarStateLoading) {
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
// Вызываем getMyProfile() только если состояние loading (первый запуск)
|
profileAvatarCubit.ensureFreshForCurrentSession();
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
});
|
||||||
profileAvatarCubit.getMyProfile();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return _MainShellWithNavScope(currentLocation: state.matchedLocation, child: child);
|
return _MainShellWithNavScope(currentLocation: state.matchedLocation, child: child);
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -16,6 +16,9 @@ import 'package:eatvio_app/features/chat/presentation/pages/payment_screen.dart'
|
|||||||
import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart';
|
import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart';
|
||||||
import 'package:eatvio_app/features/video_calls/presentation/pages/video_call_screen.dart';
|
import 'package:eatvio_app/features/video_calls/presentation/pages/video_call_screen.dart';
|
||||||
import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_state.dart';
|
import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_state.dart';
|
||||||
|
import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart';
|
||||||
|
import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recording_player_screen.dart';
|
||||||
|
import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart';
|
||||||
import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/become_consultant_screen.dart';
|
import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/become_consultant_screen.dart';
|
||||||
import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/stepper_become_consultant_screen.dart';
|
import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/stepper_become_consultant_screen.dart';
|
||||||
import 'package:eatvio_app/features/consultant_rating/presentation/consultant_rating_screen.dart';
|
import 'package:eatvio_app/features/consultant_rating/presentation/consultant_rating_screen.dart';
|
||||||
@@ -140,6 +143,19 @@ class OtherRoutes {
|
|||||||
GoRoute(path: ConsultationsArchiveScreen.path, name: ConsultationsArchiveScreen.name, builder: (context, state) => const ConsultationsArchiveScreen()),
|
GoRoute(path: ConsultationsArchiveScreen.path, name: ConsultationsArchiveScreen.name, builder: (context, state) => const ConsultationsArchiveScreen()),
|
||||||
GoRoute(path: ConsultantFinancesScreen.path, name: ConsultantFinancesScreen.name, builder: (context, state) => const ConsultantFinancesScreen()),
|
GoRoute(path: ConsultantFinancesScreen.path, name: ConsultantFinancesScreen.name, builder: (context, state) => const ConsultantFinancesScreen()),
|
||||||
GoRoute(path: UserPurchasesScreen.path, name: UserPurchasesScreen.name, builder: (context, state) => const UserPurchasesScreen()),
|
GoRoute(path: UserPurchasesScreen.path, name: UserPurchasesScreen.name, builder: (context, state) => const UserPurchasesScreen()),
|
||||||
|
GoRoute(
|
||||||
|
path: VideoCallRecordingsScreen.path,
|
||||||
|
name: VideoCallRecordingsScreen.name,
|
||||||
|
builder: (context, state) => const VideoCallRecordingsScreen(),
|
||||||
|
),
|
||||||
|
GoRoute(
|
||||||
|
path: VideoCallRecordingPlayerScreen.path,
|
||||||
|
name: VideoCallRecordingPlayerScreen.name,
|
||||||
|
builder: (context, state) {
|
||||||
|
final recording = state.extra as VideoCallRecordingModel;
|
||||||
|
return VideoCallRecordingPlayerScreen(recording: recording);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
|
||||||
// Finance routes
|
// Finance routes
|
||||||
GoRoute(path: RouteConstants.userFinanceScreen, name: 'userFinanceScreen', builder: (context, state) => const UserFinanceScreen()),
|
GoRoute(path: RouteConstants.userFinanceScreen, name: 'userFinanceScreen', builder: (context, state) => const UserFinanceScreen()),
|
||||||
@@ -192,7 +208,18 @@ class OtherRoutes {
|
|||||||
return CreatePlanScreen(plan: plan);
|
return CreatePlanScreen(plan: plan);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
GoRoute(path: MyDietsScreen.path, name: MyDietsScreen.name, builder: (context, state) => const MyDietsScreen()),
|
GoRoute(
|
||||||
|
path: MyDietsScreen.path,
|
||||||
|
name: MyDietsScreen.name,
|
||||||
|
builder: (context, state) {
|
||||||
|
final initialTabIndex = int.tryParse(
|
||||||
|
state.uri.queryParameters['initialTabIndex'] ?? '',
|
||||||
|
);
|
||||||
|
return MyDietsScreen(
|
||||||
|
initialTabIndex: initialTabIndex ?? 0,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
GoRoute(path: MyPlansScreen.path, name: MyPlansScreen.name, builder: (context, state) => const MyPlansScreen()),
|
GoRoute(path: MyPlansScreen.path, name: MyPlansScreen.name, builder: (context, state) => const MyPlansScreen()),
|
||||||
GoRoute(path: MyRecipesScreen.path, name: MyRecipesScreen.name, builder: (context, state) => const MyRecipesScreen()),
|
GoRoute(path: MyRecipesScreen.path, name: MyRecipesScreen.name, builder: (context, state) => const MyRecipesScreen()),
|
||||||
|
|
||||||
|
|||||||
122
lib/core/session/session_lifecycle_service.dart
Normal file
122
lib/core/session/session_lifecycle_service.dart
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:appmetrica_plugin/appmetrica_plugin.dart';
|
||||||
|
import 'package:dio/dio.dart';
|
||||||
|
import 'package:eatvio_app/core/app_config.dart';
|
||||||
|
import 'package:eatvio_app/core/app_router.dart';
|
||||||
|
import 'package:eatvio_app/core/error_reporting/error_reporter.dart';
|
||||||
|
import 'package:eatvio_app/core/firebase_api.dart';
|
||||||
|
import 'package:eatvio_app/core/locator_service.dart';
|
||||||
|
import 'package:eatvio_app/core/prefs.dart';
|
||||||
|
import 'package:eatvio_app/core/prefs_keys.dart';
|
||||||
|
import 'package:eatvio_app/core/routing/route_constants.dart';
|
||||||
|
import 'package:eatvio_app/core/token_storage.dart';
|
||||||
|
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
||||||
|
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart';
|
||||||
|
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
|
||||||
|
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
|
||||||
|
import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart';
|
||||||
|
import 'package:eatvio_app/features/notifications/presentation/notifications_cubit/notifications_cubit.dart';
|
||||||
|
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart';
|
||||||
|
import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart';
|
||||||
|
import 'package:go_router/go_router.dart';
|
||||||
|
|
||||||
|
enum SessionEndReason { logout, unauthorized, accountDeleted }
|
||||||
|
|
||||||
|
class SessionLifecycleService {
|
||||||
|
SessionLifecycleService({
|
||||||
|
required WsManager wsManager,
|
||||||
|
required ErrorReporter errorReporter,
|
||||||
|
}) : _wsManager = wsManager,
|
||||||
|
_errorReporter = errorReporter;
|
||||||
|
|
||||||
|
final WsManager _wsManager;
|
||||||
|
final ErrorReporter _errorReporter;
|
||||||
|
|
||||||
|
int? _authenticatedFingerprint;
|
||||||
|
bool _endingSession = false;
|
||||||
|
|
||||||
|
Future<void> endSession({required SessionEndReason reason}) async {
|
||||||
|
if (_endingSession) return;
|
||||||
|
_endingSession = true;
|
||||||
|
try {
|
||||||
|
await _run(() => _wsManager.clear());
|
||||||
|
await _run(TokenStorage.removeTokenInStorage);
|
||||||
|
await _run(SocketIdStorage.removeSocketIdInStorage);
|
||||||
|
await _run(() => sl<ProfileAvatarCubit>().reset());
|
||||||
|
await _run(() => sl<ChatsCubit>().reset());
|
||||||
|
await _run(() => sl<NotificationsCubit>().reset());
|
||||||
|
await _run(() => sl<NewMessagesCubit>().reset());
|
||||||
|
await _run(() => sl<FeedCubit>().reset());
|
||||||
|
await _run(() async => ProfileCubit.clearMyProfileReference());
|
||||||
|
await _run(() => sl<VideoCallSessionCubit>().endCall());
|
||||||
|
await _run(() async => AppMetrica.setUserProfileID(null));
|
||||||
|
await _run(
|
||||||
|
() => sl<Prefs>().remove(PrefsKeys.isEmailVerificationSkipped),
|
||||||
|
);
|
||||||
|
await _run(() => sl<Prefs>().remove(PrefsKeys.registrationDate));
|
||||||
|
_authenticatedFingerprint = null;
|
||||||
|
await _run(() async {
|
||||||
|
final context = AppRouter.navigatorKey.currentContext;
|
||||||
|
if (context == null) return;
|
||||||
|
final path =
|
||||||
|
AppRouter.appRouter.routeInformationProvider.value.uri.path;
|
||||||
|
if (path != RouteConstants.authScreen) {
|
||||||
|
context.go(RouteConstants.authScreen);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
_endingSession = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> onAuthenticated() async {
|
||||||
|
String? token;
|
||||||
|
try {
|
||||||
|
token = await TokenStorage.getTokenFromStorage();
|
||||||
|
} catch (e, st) {
|
||||||
|
await _report(e, st);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (token == null || token.isEmpty) return;
|
||||||
|
final fingerprint = token.hashCode;
|
||||||
|
if (_authenticatedFingerprint == fingerprint) return;
|
||||||
|
_authenticatedFingerprint = fingerprint;
|
||||||
|
|
||||||
|
await _run(() async {
|
||||||
|
await _wsManager.clear();
|
||||||
|
await _wsManager.initialize();
|
||||||
|
});
|
||||||
|
await _run(() => sl<ProfileAvatarCubit>().getMyProfile());
|
||||||
|
await _run(() => sl<ChatsCubit>().getChatRoomsWithLoading());
|
||||||
|
await _run(() => sl<NotificationsCubit>().getNotifications());
|
||||||
|
await _run(() => sl<FirebaseApi>().registerPushToken());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> logout() async {
|
||||||
|
try {
|
||||||
|
await _run(() => sl<FirebaseApi>().unregisterPushTokens());
|
||||||
|
await _run(
|
||||||
|
() => sl<Dio>().post('${sl<AppConfig>().baseUrl}/api/profile/logout'),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await endSession(reason: SessionEndReason.logout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _run(FutureOr<void> Function() action) async {
|
||||||
|
try {
|
||||||
|
await action();
|
||||||
|
} catch (e, st) {
|
||||||
|
await _report(e, st);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _report(Object error, StackTrace stackTrace) {
|
||||||
|
return _errorReporter.report(
|
||||||
|
error,
|
||||||
|
stackTrace,
|
||||||
|
origin: 'SessionLifecycleService',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,7 +18,7 @@ class WsManager {
|
|||||||
final ErrorReporter _errorReporter;
|
final ErrorReporter _errorReporter;
|
||||||
|
|
||||||
WsManager({required this.wsService, required ErrorReporter errorReporter})
|
WsManager({required this.wsService, required ErrorReporter errorReporter})
|
||||||
: _errorReporter = errorReporter;
|
: _errorReporter = errorReporter;
|
||||||
|
|
||||||
PusherChannelsClient? client;
|
PusherChannelsClient? client;
|
||||||
int? userId;
|
int? userId;
|
||||||
@@ -43,19 +43,41 @@ class WsManager {
|
|||||||
/// Контроллер создаётся один раз и не закрывается в [clear]: подписчики
|
/// Контроллер создаётся один раз и не закрывается в [clear]: подписчики
|
||||||
/// (чаты, окно чата) переживают логаут/повторный вход и продолжают получать
|
/// (чаты, окно чата) переживают логаут/повторный вход и продолжают получать
|
||||||
/// сигналы. Если контроллер всё же закрыт, он пересоздаётся в [initialize].
|
/// сигналы. Если контроллер всё же закрыт, он пересоздаётся в [initialize].
|
||||||
StreamController<void> _reconnectController = StreamController<void>.broadcast();
|
StreamController<void> _reconnectController =
|
||||||
|
StreamController<void>.broadcast();
|
||||||
|
|
||||||
Stream<ChannelReadEvent>? _directChatStream;
|
Stream<ChannelReadEvent>? _directChatStream;
|
||||||
Stream<ChannelReadEvent>? _clientTypingStream;
|
Stream<ChannelReadEvent>? _clientTypingStream;
|
||||||
|
Stream<ChannelReadEvent>? _chosenPlanStateChangedStream;
|
||||||
|
|
||||||
Stream<ChannelReadEvent>? get newMessagesStream => _privateMessagesChannel?.bind('App\\Events\\ChatMessageUpdated');
|
Stream<ChannelReadEvent>? get newMessagesStream =>
|
||||||
|
_privateMessagesChannel?.bind('App\\Events\\ChatMessageUpdated');
|
||||||
|
|
||||||
Stream<ChannelReadEvent>? get newNotificationsStream => _privateNotificationChannel?.bind('Illuminate\\Notifications\\Events\\BroadcastNotificationCreated');
|
/// The callee rejected the ring. Broadcast to the caller and the callee.
|
||||||
|
Stream<ChannelReadEvent>? get videoCallDeclinedStream =>
|
||||||
|
_privateMessagesChannel?.bind('video-call-declined');
|
||||||
|
|
||||||
|
/// The call was cancelled or hung up. Same channel the web client uses.
|
||||||
|
Stream<ChannelReadEvent>? get videoCallEndedStream =>
|
||||||
|
_privateMessagesChannel?.bind('video-call-ended');
|
||||||
|
|
||||||
|
/// Another device accepted the ring. Ringing on this device must stop,
|
||||||
|
/// except on the device that accepted.
|
||||||
|
Stream<ChannelReadEvent>? get videoCallAcceptedStream =>
|
||||||
|
_privateMessagesChannel?.bind('video-call-accepted');
|
||||||
|
|
||||||
|
Stream<ChannelReadEvent>? get newNotificationsStream =>
|
||||||
|
_privateNotificationChannel?.bind(
|
||||||
|
'Illuminate\\Notifications\\Events\\BroadcastNotificationCreated',
|
||||||
|
);
|
||||||
|
|
||||||
Stream<ChannelReadEvent>? get directChatStream => _directChatStream;
|
Stream<ChannelReadEvent>? get directChatStream => _directChatStream;
|
||||||
|
|
||||||
Stream<ChannelReadEvent>? get clientTypingStream => _clientTypingStream;
|
Stream<ChannelReadEvent>? get clientTypingStream => _clientTypingStream;
|
||||||
|
|
||||||
|
Stream<ChannelReadEvent>? get chosenPlanStateChangedStream =>
|
||||||
|
_chosenPlanStateChangedStream;
|
||||||
|
|
||||||
/// Сигнал о реконнекте сокета: эмитится после повторной подписки на каналы.
|
/// Сигнал о реконнекте сокета: эмитится после повторной подписки на каналы.
|
||||||
///
|
///
|
||||||
/// Подписчики используют его, чтобы догрузить пропущенные за время обрыва
|
/// Подписчики используют его, чтобы догрузить пропущенные за время обрыва
|
||||||
@@ -86,15 +108,9 @@ class WsManager {
|
|||||||
connectionErrorHandler: (exception, trace, refresh) {
|
connectionErrorHandler: (exception, trace, refresh) {
|
||||||
refresh();
|
refresh();
|
||||||
},
|
},
|
||||||
minimumReconnectDelayDuration: const Duration(
|
minimumReconnectDelayDuration: const Duration(seconds: 1),
|
||||||
seconds: 1,
|
defaultActivityDuration: const Duration(seconds: 30),
|
||||||
),
|
waitForPongDuration: const Duration(seconds: 30),
|
||||||
defaultActivityDuration: const Duration(
|
|
||||||
seconds: 30,
|
|
||||||
),
|
|
||||||
waitForPongDuration: const Duration(
|
|
||||||
seconds: 30,
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
String? extractSocketId(String? data) {
|
String? extractSocketId(String? data) {
|
||||||
@@ -107,7 +123,9 @@ class WsManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_connectionEstablishedSubscription = client?.eventStream.listen((event) async {
|
_connectionEstablishedSubscription = client?.eventStream.listen((
|
||||||
|
event,
|
||||||
|
) async {
|
||||||
if (event.name == 'pusher:connection_established') {
|
if (event.name == 'pusher:connection_established') {
|
||||||
final data = event.data;
|
final data = event.data;
|
||||||
final socketId = extractSocketId(data);
|
final socketId = extractSocketId(data);
|
||||||
@@ -124,7 +142,8 @@ class WsManager {
|
|||||||
await _initPrivateMessagesChannel();
|
await _initPrivateMessagesChannel();
|
||||||
|
|
||||||
_lifecycleSubscription = client?.lifecycleStream.listen((data) {
|
_lifecycleSubscription = client?.lifecycleStream.listen((data) {
|
||||||
if (data == PusherChannelsClientLifeCycleState.establishedConnection) {
|
if (data ==
|
||||||
|
PusherChannelsClientLifeCycleState.establishedConnection) {
|
||||||
handleConnectionEstablished();
|
handleConnectionEstablished();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -166,12 +185,13 @@ class WsManager {
|
|||||||
final token = await TokenStorage.getTokenFromStorage();
|
final token = await TokenStorage.getTokenFromStorage();
|
||||||
_privateNotificationChannel = client?.privateChannel(
|
_privateNotificationChannel = client?.privateChannel(
|
||||||
'$newNotificationsChannelName.$userId',
|
'$newNotificationsChannelName.$userId',
|
||||||
authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel(
|
authorizationDelegate:
|
||||||
authorizationEndpoint: Uri.parse('${sl<AppConfig>().baseUrl}/broadcasting/auth'),
|
EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel(
|
||||||
headers: {
|
authorizationEndpoint: Uri.parse(
|
||||||
'Authorization': 'Bearer $token',
|
'${sl<AppConfig>().baseUrl}/broadcasting/auth',
|
||||||
},
|
),
|
||||||
),
|
headers: {'Authorization': 'Bearer $token'},
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,12 +199,13 @@ class WsManager {
|
|||||||
final token = await TokenStorage.getTokenFromStorage();
|
final token = await TokenStorage.getTokenFromStorage();
|
||||||
_privateMessagesChannel = client?.privateChannel(
|
_privateMessagesChannel = client?.privateChannel(
|
||||||
'$newMessagesChannelName.$userId',
|
'$newMessagesChannelName.$userId',
|
||||||
authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel(
|
authorizationDelegate:
|
||||||
authorizationEndpoint: Uri.parse('${sl<AppConfig>().baseUrl}/broadcasting/auth'),
|
EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel(
|
||||||
headers: {
|
authorizationEndpoint: Uri.parse(
|
||||||
'Authorization': 'Bearer $token',
|
'${sl<AppConfig>().baseUrl}/broadcasting/auth',
|
||||||
},
|
),
|
||||||
),
|
headers: {'Authorization': 'Bearer $token'},
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -193,27 +214,34 @@ class WsManager {
|
|||||||
final token = await TokenStorage.getTokenFromStorage();
|
final token = await TokenStorage.getTokenFromStorage();
|
||||||
_privateDirectChatChannel = client?.privateChannel(
|
_privateDirectChatChannel = client?.privateChannel(
|
||||||
'$directChatChannelName.$chatId',
|
'$directChatChannelName.$chatId',
|
||||||
authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel(
|
authorizationDelegate:
|
||||||
authorizationEndpoint: Uri.parse('${sl<AppConfig>().baseUrl}/broadcasting/auth'),
|
EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel(
|
||||||
headers: {
|
authorizationEndpoint: Uri.parse(
|
||||||
'Authorization': 'Bearer $token',
|
'${sl<AppConfig>().baseUrl}/broadcasting/auth',
|
||||||
},
|
),
|
||||||
),
|
headers: {'Authorization': 'Bearer $token'},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
_directChatStream = _privateDirectChatChannel?.bind(
|
||||||
|
'App\\Events\\ChatMessageUpdated',
|
||||||
);
|
);
|
||||||
_directChatStream = _privateDirectChatChannel?.bind('App\\Events\\ChatMessageUpdated');
|
|
||||||
_clientTypingStream = _privateDirectChatChannel?.bind('client-typing');
|
_clientTypingStream = _privateDirectChatChannel?.bind('client-typing');
|
||||||
|
_chosenPlanStateChangedStream = _privateDirectChatChannel?.bind(
|
||||||
|
'chosen-plan-state-changed',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> initPresenceDirectChatChannel(String chatId) async {
|
Future<void> initPresenceDirectChatChannel(String chatId) async {
|
||||||
final token = await TokenStorage.getTokenFromStorage();
|
final token = await TokenStorage.getTokenFromStorage();
|
||||||
_presenceDirectChatChannel = client?.presenceChannel(
|
_presenceDirectChatChannel = client?.presenceChannel(
|
||||||
'$presenceDirectChatChannelName.$chatId',
|
'$presenceDirectChatChannelName.$chatId',
|
||||||
authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPresenceChannel(
|
authorizationDelegate:
|
||||||
authorizationEndpoint: Uri.parse('${sl<AppConfig>().baseUrl}/broadcasting/auth'),
|
EndpointAuthorizableChannelTokenAuthorizationDelegate.forPresenceChannel(
|
||||||
headers: {
|
authorizationEndpoint: Uri.parse(
|
||||||
'Authorization': 'Bearer $token',
|
'${sl<AppConfig>().baseUrl}/broadcasting/auth',
|
||||||
},
|
),
|
||||||
),
|
headers: {'Authorization': 'Bearer $token'},
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -240,7 +268,8 @@ class WsManager {
|
|||||||
void Function(bool isOnline) onCounterpartOnlineChanged,
|
void Function(bool isOnline) onCounterpartOnlineChanged,
|
||||||
) {
|
) {
|
||||||
_presenceDirectChatListeners.removeWhere(
|
_presenceDirectChatListeners.removeWhere(
|
||||||
(listener) => listener.onCounterpartOnlineChanged == onCounterpartOnlineChanged,
|
(listener) =>
|
||||||
|
listener.onCounterpartOnlineChanged == onCounterpartOnlineChanged,
|
||||||
);
|
);
|
||||||
if (_presenceDirectChatListeners.isEmpty) {
|
if (_presenceDirectChatListeners.isEmpty) {
|
||||||
unsubscribePresenceDirectChatChannel();
|
unsubscribePresenceDirectChatChannel();
|
||||||
@@ -254,21 +283,26 @@ class WsManager {
|
|||||||
|
|
||||||
_presenceChannelEventsBound = true;
|
_presenceChannelEventsBound = true;
|
||||||
|
|
||||||
_presenceSubscriptionSucceededSubscription =
|
_presenceSubscriptionSucceededSubscription = channel
|
||||||
channel.whenSubscriptionSucceeded().listen((_) {
|
.whenSubscriptionSucceeded()
|
||||||
final counterpartIds = _presenceDirectChatListeners
|
.listen((_) {
|
||||||
.map((listener) => listener.counterpartUserId)
|
final counterpartIds = _presenceDirectChatListeners
|
||||||
.toSet();
|
.map((listener) => listener.counterpartUserId)
|
||||||
for (final counterpartUserId in counterpartIds) {
|
.toSet();
|
||||||
_emitCounterpartPresence(counterpartUserId);
|
for (final counterpartUserId in counterpartIds) {
|
||||||
}
|
_emitCounterpartPresence(counterpartUserId);
|
||||||
});
|
}
|
||||||
_presenceMemberAddedSubscription = channel.whenMemberAdded().listen((event) {
|
});
|
||||||
|
_presenceMemberAddedSubscription = channel.whenMemberAdded().listen((
|
||||||
|
event,
|
||||||
|
) {
|
||||||
final memberUserId = _parsePresenceMemberUserId(event.data);
|
final memberUserId = _parsePresenceMemberUserId(event.data);
|
||||||
if (memberUserId == null) return;
|
if (memberUserId == null) return;
|
||||||
_notifyPresenceListeners(memberUserId, isOnline: true);
|
_notifyPresenceListeners(memberUserId, isOnline: true);
|
||||||
});
|
});
|
||||||
_presenceMemberRemovedSubscription = channel.whenMemberRemoved().listen((event) {
|
_presenceMemberRemovedSubscription = channel.whenMemberRemoved().listen((
|
||||||
|
event,
|
||||||
|
) {
|
||||||
final memberUserId = _parsePresenceMemberUserId(event.data);
|
final memberUserId = _parsePresenceMemberUserId(event.data);
|
||||||
if (memberUserId == null) return;
|
if (memberUserId == null) return;
|
||||||
_notifyPresenceListeners(memberUserId, isOnline: false);
|
_notifyPresenceListeners(memberUserId, isOnline: false);
|
||||||
@@ -280,11 +314,15 @@ class WsManager {
|
|||||||
if (channel == null) return;
|
if (channel == null) return;
|
||||||
final members = channel.state?.members;
|
final members = channel.state?.members;
|
||||||
if (members == null) return;
|
if (members == null) return;
|
||||||
final isOnline = members.getMemberInfo(counterpartUserId.toString()) != null;
|
final isOnline =
|
||||||
|
members.getMemberInfo(counterpartUserId.toString()) != null;
|
||||||
_notifyPresenceListeners(counterpartUserId, isOnline: isOnline);
|
_notifyPresenceListeners(counterpartUserId, isOnline: isOnline);
|
||||||
}
|
}
|
||||||
|
|
||||||
void _notifyPresenceListeners(int counterpartUserId, {required bool isOnline}) {
|
void _notifyPresenceListeners(
|
||||||
|
int counterpartUserId, {
|
||||||
|
required bool isOnline,
|
||||||
|
}) {
|
||||||
for (final listener in _presenceDirectChatListeners) {
|
for (final listener in _presenceDirectChatListeners) {
|
||||||
if (listener.counterpartUserId == counterpartUserId) {
|
if (listener.counterpartUserId == counterpartUserId) {
|
||||||
listener.onCounterpartOnlineChanged(isOnline);
|
listener.onCounterpartOnlineChanged(isOnline);
|
||||||
@@ -336,6 +374,7 @@ class WsManager {
|
|||||||
_privateDirectChatChannel?.unsubscribe();
|
_privateDirectChatChannel?.unsubscribe();
|
||||||
_directChatStream = null;
|
_directChatStream = null;
|
||||||
_clientTypingStream = null;
|
_clientTypingStream = null;
|
||||||
|
_chosenPlanStateChangedStream = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
void unsubscribePresenceDirectChatChannel() {
|
void unsubscribePresenceDirectChatChannel() {
|
||||||
@@ -370,6 +409,7 @@ class WsManager {
|
|||||||
_privateNotificationChannel = null;
|
_privateNotificationChannel = null;
|
||||||
_directChatStream = null;
|
_directChatStream = null;
|
||||||
_clientTypingStream = null;
|
_clientTypingStream = null;
|
||||||
|
_chosenPlanStateChangedStream = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,11 @@ import 'dart:ui';
|
|||||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
Future<void> showBottomSheetWithBlur({
|
/// Показывает modal bottom sheet с blur-фоном.
|
||||||
|
///
|
||||||
|
/// Дженерик [T] пробрасывает значение, переданное в `Navigator.pop(T)`
|
||||||
|
/// внутри шита (по умолчанию `null`).
|
||||||
|
Future<T?> showBottomSheetWithBlur<T>({
|
||||||
required BuildContext context,
|
required BuildContext context,
|
||||||
required Widget child,
|
required Widget child,
|
||||||
double? height = 200,
|
double? height = 200,
|
||||||
@@ -11,7 +15,7 @@ Future<void> showBottomSheetWithBlur({
|
|||||||
bool enableDrag = true,
|
bool enableDrag = true,
|
||||||
bool userRootNavigator = false,
|
bool userRootNavigator = false,
|
||||||
}) {
|
}) {
|
||||||
return showModalBottomSheet(
|
return showModalBottomSheet<T>(
|
||||||
context: context,
|
context: context,
|
||||||
isScrollControlled: true,
|
isScrollControlled: true,
|
||||||
barrierColor: appTheme.transparentBlack,
|
barrierColor: appTheme.transparentBlack,
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import 'dart:developer';
|
|||||||
import 'package:eatvio_app/core/firebase_api.dart';
|
import 'package:eatvio_app/core/firebase_api.dart';
|
||||||
import 'package:eatvio_app/core/prefs.dart';
|
import 'package:eatvio_app/core/prefs.dart';
|
||||||
import 'package:eatvio_app/core/prefs_keys.dart';
|
import 'package:eatvio_app/core/prefs_keys.dart';
|
||||||
|
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||||
import 'package:eatvio_app/core/token_storage.dart';
|
import 'package:eatvio_app/core/token_storage.dart';
|
||||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||||
import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_state.dart';
|
import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_state.dart';
|
||||||
@@ -17,15 +18,26 @@ class AuthCubit extends Cubit<AuthState> {
|
|||||||
final ProfileRepository profileRepository;
|
final ProfileRepository profileRepository;
|
||||||
final FirebaseApi firebaseApi;
|
final FirebaseApi firebaseApi;
|
||||||
final Prefs prefs;
|
final Prefs prefs;
|
||||||
|
final SessionLifecycleService sessionLifecycleService;
|
||||||
|
|
||||||
AuthCubit({required this.authRepository, required this.prefs, required this.profileRepository, required this.firebaseApi}) : super(const AuthState());
|
AuthCubit({
|
||||||
|
required this.authRepository,
|
||||||
|
required this.prefs,
|
||||||
|
required this.profileRepository,
|
||||||
|
required this.firebaseApi,
|
||||||
|
required this.sessionLifecycleService,
|
||||||
|
}) : super(const AuthState());
|
||||||
|
|
||||||
Future<bool> getTokenByCredentials(String email, String password) async {
|
Future<bool> getTokenByCredentials(String email, String password) async {
|
||||||
emit(const AuthState.loading());
|
emit(const AuthState.loading());
|
||||||
try {
|
try {
|
||||||
final token = (await authRepository.getTokenByCredentials(email, password)).token;
|
final token = (await authRepository.getTokenByCredentials(
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
)).token;
|
||||||
emit(AuthState.loaded(token: token));
|
emit(AuthState.loaded(token: token));
|
||||||
await TokenStorage.saveTokenInStorage(token);
|
await TokenStorage.saveTokenInStorage(token);
|
||||||
|
await sessionLifecycleService.onAuthenticated();
|
||||||
return true;
|
return true;
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
await reportFrom(e, st, this);
|
await reportFrom(e, st, this);
|
||||||
@@ -48,7 +60,8 @@ class AuthCubit extends Cubit<AuthState> {
|
|||||||
|
|
||||||
Future<void> registerAnonymousPushToken() async {
|
Future<void> registerAnonymousPushToken() async {
|
||||||
try {
|
try {
|
||||||
final hasAnonymousTokenBeenSent = prefs.getBool(PrefsKeys.hasAnonymousTokenBeenSent) ?? false;
|
final hasAnonymousTokenBeenSent =
|
||||||
|
prefs.getBool(PrefsKeys.hasAnonymousTokenBeenSent) ?? false;
|
||||||
if (!hasAnonymousTokenBeenSent) {
|
if (!hasAnonymousTokenBeenSent) {
|
||||||
await firebaseApi.registerAnonymousPushToken();
|
await firebaseApi.registerAnonymousPushToken();
|
||||||
prefs.setBool(PrefsKeys.hasAnonymousTokenBeenSent, true);
|
prefs.setBool(PrefsKeys.hasAnonymousTokenBeenSent, true);
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import 'dart:developer';
|
import 'dart:developer';
|
||||||
import 'package:dio/dio.dart';
|
import 'package:dio/dio.dart';
|
||||||
|
import 'package:eatvio_app/core/firebase_api.dart';
|
||||||
import 'package:eatvio_app/core/mixins/registration_date_cache_mixin.dart';
|
import 'package:eatvio_app/core/mixins/registration_date_cache_mixin.dart';
|
||||||
import 'package:eatvio_app/core/prefs.dart';
|
import 'package:eatvio_app/core/prefs.dart';
|
||||||
|
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||||
import 'package:eatvio_app/core/token_storage.dart';
|
import 'package:eatvio_app/core/token_storage.dart';
|
||||||
import 'package:eatvio_app/features/auth/models/oauth_verification_request_response.dart';
|
import 'package:eatvio_app/features/auth/models/oauth_verification_request_response.dart';
|
||||||
import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_state.dart';
|
import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_state.dart';
|
||||||
@@ -11,12 +13,24 @@ import 'package:eatvio_app/core/error_reporting/report_from.dart';
|
|||||||
|
|
||||||
class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
||||||
final AuthRepository authRepository;
|
final AuthRepository authRepository;
|
||||||
|
final FirebaseApi firebaseApi;
|
||||||
|
final SessionLifecycleService sessionLifecycleService;
|
||||||
|
|
||||||
OAuthCubit({required this.authRepository, required Prefs prefs}) : super(const OAuthState()) {
|
OAuthCubit({
|
||||||
|
required this.authRepository,
|
||||||
|
required this.firebaseApi,
|
||||||
|
required this.sessionLifecycleService,
|
||||||
|
required Prefs prefs,
|
||||||
|
}) : super(const OAuthState()) {
|
||||||
this.prefs = prefs;
|
this.prefs = prefs;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> signInViaSocialMedia({required String provider, required String accessToken, required String refreshToken, required String clientId}) async {
|
Future<void> signInViaSocialMedia({
|
||||||
|
required String provider,
|
||||||
|
required String accessToken,
|
||||||
|
required String refreshToken,
|
||||||
|
required String clientId,
|
||||||
|
}) async {
|
||||||
try {
|
try {
|
||||||
emit(const OAuthState.loading());
|
emit(const OAuthState.loading());
|
||||||
|
|
||||||
@@ -28,7 +42,8 @@ class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
|||||||
);
|
);
|
||||||
|
|
||||||
log('OAuthCubit: Got token model: ${tokenModel.token}');
|
log('OAuthCubit: Got token model: ${tokenModel.token}');
|
||||||
TokenStorage.saveTokenInStorage(tokenModel.token);
|
await TokenStorage.saveTokenInStorage(tokenModel.token);
|
||||||
|
await sessionLifecycleService.onAuthenticated();
|
||||||
emit(OAuthState.loaded(token: tokenModel.token));
|
emit(OAuthState.loaded(token: tokenModel.token));
|
||||||
} on DioException catch (e, st) {
|
} on DioException catch (e, st) {
|
||||||
await reportFrom(e, st, this);
|
await reportFrom(e, st, this);
|
||||||
@@ -45,7 +60,8 @@ class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
|||||||
if (errorStr.contains('Некорректный формат email')) {
|
if (errorStr.contains('Некорректный формат email')) {
|
||||||
errorsList.add(RegistrationValidationErrors.incorrectEmailFormat);
|
errorsList.add(RegistrationValidationErrors.incorrectEmailFormat);
|
||||||
}
|
}
|
||||||
if (errorStr.contains('почта уже существует') || errorStr.contains('Эл. почта уже существует')) {
|
if (errorStr.contains('почта уже существует') ||
|
||||||
|
errorStr.contains('Эл. почта уже существует')) {
|
||||||
errorsList.add(RegistrationValidationErrors.emailExist);
|
errorsList.add(RegistrationValidationErrors.emailExist);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -53,14 +69,20 @@ class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
|||||||
if (phoneErrors != null && phoneErrors.isNotEmpty) {
|
if (phoneErrors != null && phoneErrors.isNotEmpty) {
|
||||||
for (final error in phoneErrors) {
|
for (final error in phoneErrors) {
|
||||||
final errorStr = error.toString();
|
final errorStr = error.toString();
|
||||||
if (errorStr.contains('phone уже существует') || errorStr.contains('телефон уже существует')) {
|
if (errorStr.contains('phone уже существует') ||
|
||||||
|
errorStr.contains('телефон уже существует')) {
|
||||||
errorsList.add(RegistrationValidationErrors.phoneExist);
|
errorsList.add(RegistrationValidationErrors.phoneExist);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (errorsList.isNotEmpty) {
|
if (errorsList.isNotEmpty) {
|
||||||
emit(OAuthState.error(errorMessage: 'validation_error', registrationValidationErrors: errorsList));
|
emit(
|
||||||
|
OAuthState.error(
|
||||||
|
errorMessage: 'validation_error',
|
||||||
|
registrationValidationErrors: errorsList,
|
||||||
|
),
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
emit(OAuthState.error(errorMessage: e.toString()));
|
emit(OAuthState.error(errorMessage: e.toString()));
|
||||||
}
|
}
|
||||||
@@ -103,7 +125,8 @@ class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
|||||||
height: height,
|
height: height,
|
||||||
clientId: clientId,
|
clientId: clientId,
|
||||||
);
|
);
|
||||||
TokenStorage.saveTokenInStorage(token);
|
await TokenStorage.saveTokenInStorage(token);
|
||||||
|
await sessionLifecycleService.onAuthenticated();
|
||||||
cacheRegistrationDate(DateTime.now());
|
cacheRegistrationDate(DateTime.now());
|
||||||
emit(OAuthState.loaded(token: token));
|
emit(OAuthState.loaded(token: token));
|
||||||
} on DioException catch (e, st) {
|
} on DioException catch (e, st) {
|
||||||
@@ -120,7 +143,8 @@ class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
|||||||
if (errorStr.contains('Некорректный формат email')) {
|
if (errorStr.contains('Некорректный формат email')) {
|
||||||
errorsList.add(RegistrationValidationErrors.incorrectEmailFormat);
|
errorsList.add(RegistrationValidationErrors.incorrectEmailFormat);
|
||||||
}
|
}
|
||||||
if (errorStr.contains('почта уже существует') || errorStr.contains('Эл. почта уже существует')) {
|
if (errorStr.contains('почта уже существует') ||
|
||||||
|
errorStr.contains('Эл. почта уже существует')) {
|
||||||
errorsList.add(RegistrationValidationErrors.emailExist);
|
errorsList.add(RegistrationValidationErrors.emailExist);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -128,14 +152,17 @@ class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
|||||||
if (phoneErrors != null && phoneErrors.isNotEmpty) {
|
if (phoneErrors != null && phoneErrors.isNotEmpty) {
|
||||||
for (final error in phoneErrors) {
|
for (final error in phoneErrors) {
|
||||||
final errorStr = error.toString();
|
final errorStr = error.toString();
|
||||||
if (errorStr.contains('phone уже существует') || errorStr.contains('телефон уже существует')) {
|
if (errorStr.contains('phone уже существует') ||
|
||||||
|
errorStr.contains('телефон уже существует')) {
|
||||||
errorsList.add(RegistrationValidationErrors.phoneExist);
|
errorsList.add(RegistrationValidationErrors.phoneExist);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (dateOfBirth != null && dateOfBirth.isNotEmpty) {
|
if (dateOfBirth != null && dateOfBirth.isNotEmpty) {
|
||||||
if (dateOfBirth.contains('Некорректный формат даты рождения')) {
|
if (dateOfBirth.contains('Некорректный формат даты рождения')) {
|
||||||
errorsList.add(RegistrationValidationErrors.incorrectDateOfBirthFormat);
|
errorsList.add(
|
||||||
|
RegistrationValidationErrors.incorrectDateOfBirthFormat,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (errorsList.isNotEmpty) {
|
if (errorsList.isNotEmpty) {
|
||||||
@@ -146,13 +173,23 @@ class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<OAuthVerificationRequestResponse?> requestOAuthVerification({String? email, String? phone}) async {
|
Future<OAuthVerificationRequestResponse?> requestOAuthVerification({
|
||||||
|
String? email,
|
||||||
|
String? phone,
|
||||||
|
}) async {
|
||||||
try {
|
try {
|
||||||
emit(const OAuthState.loading());
|
emit(const OAuthState.loading());
|
||||||
log('OAuthCubit: Requesting verification code for email: $email, phone: $phone');
|
log(
|
||||||
final response = await authRepository.requestOAuthVerification(email: email, phone: phone);
|
'OAuthCubit: Requesting verification code for email: $email, phone: $phone',
|
||||||
|
);
|
||||||
|
final response = await authRepository.requestOAuthVerification(
|
||||||
|
email: email,
|
||||||
|
phone: phone,
|
||||||
|
);
|
||||||
if (response != null) {
|
if (response != null) {
|
||||||
log('OAuthCubit: Verification code requested successfully, masked email: ${response.email}');
|
log(
|
||||||
|
'OAuthCubit: Verification code requested successfully, masked email: ${response.email}',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
// Сбрасываем состояние после успешного запроса кода
|
// Сбрасываем состояние после успешного запроса кода
|
||||||
emit(const OAuthState());
|
emit(const OAuthState());
|
||||||
@@ -184,7 +221,9 @@ class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
|||||||
}) async {
|
}) async {
|
||||||
try {
|
try {
|
||||||
emit(const OAuthState.loading());
|
emit(const OAuthState.loading());
|
||||||
log('OAuthCubit: Confirming OAuth verification - provider: $provider, verificationType: $verificationType, code: $code');
|
log(
|
||||||
|
'OAuthCubit: Confirming OAuth verification - provider: $provider, verificationType: $verificationType, code: $code',
|
||||||
|
);
|
||||||
final response = await authRepository.confirmOAuthVerification(
|
final response = await authRepository.confirmOAuthVerification(
|
||||||
provider: provider,
|
provider: provider,
|
||||||
accessToken: accessToken,
|
accessToken: accessToken,
|
||||||
@@ -202,8 +241,11 @@ class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
|||||||
weight: weight,
|
weight: weight,
|
||||||
height: height,
|
height: height,
|
||||||
);
|
);
|
||||||
log('OAuthCubit: OAuth verification confirmed successfully, token received');
|
log(
|
||||||
TokenStorage.saveTokenInStorage(response.token);
|
'OAuthCubit: OAuth verification confirmed successfully, token received',
|
||||||
|
);
|
||||||
|
await TokenStorage.saveTokenInStorage(response.token);
|
||||||
|
await sessionLifecycleService.onAuthenticated();
|
||||||
emit(OAuthState.loaded(token: response.token));
|
emit(OAuthState.loaded(token: response.token));
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
await reportFrom(e, st, this);
|
await reportFrom(e, st, this);
|
||||||
@@ -212,4 +254,3 @@ class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,12 +4,10 @@ import 'package:eatvio_app/app_keys.dart';
|
|||||||
import 'package:eatvio_app/core/app_config.dart';
|
import 'package:eatvio_app/core/app_config.dart';
|
||||||
import 'package:eatvio_app/core/app_router.dart';
|
import 'package:eatvio_app/core/app_router.dart';
|
||||||
import 'package:eatvio_app/core/const.dart';
|
import 'package:eatvio_app/core/const.dart';
|
||||||
import 'package:eatvio_app/core/firebase_api.dart';
|
|
||||||
import 'package:eatvio_app/core/locator_service.dart';
|
import 'package:eatvio_app/core/locator_service.dart';
|
||||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||||
import 'package:eatvio_app/core/utils/image_constant.dart';
|
import 'package:eatvio_app/core/utils/image_constant.dart';
|
||||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
|
||||||
import 'package:eatvio_app/core/widgets/custom_divider.dart';
|
import 'package:eatvio_app/core/widgets/custom_divider.dart';
|
||||||
import 'package:eatvio_app/core/widgets/custom_text_form_field.dart';
|
import 'package:eatvio_app/core/widgets/custom_text_form_field.dart';
|
||||||
import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart';
|
import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart';
|
||||||
@@ -18,8 +16,6 @@ import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_cub
|
|||||||
import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_state.dart';
|
import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_state.dart';
|
||||||
import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart';
|
import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart';
|
||||||
import 'package:eatvio_app/core/di/cubit_registrations.dart';
|
import 'package:eatvio_app/core/di/cubit_registrations.dart';
|
||||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
|
|
||||||
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
|
|
||||||
import 'package:eatvio_app/features/dev_tools/presentation/dev_tools_screen.dart';
|
import 'package:eatvio_app/features/dev_tools/presentation/dev_tools_screen.dart';
|
||||||
import 'package:eatvio_app/generated/l10n.dart';
|
import 'package:eatvio_app/generated/l10n.dart';
|
||||||
import 'package:flutter/cupertino.dart';
|
import 'package:flutter/cupertino.dart';
|
||||||
@@ -68,23 +64,8 @@ class _AuthScreenState extends State<AuthScreen> {
|
|||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _reconnectWebSocket(BuildContext context) async {
|
Future<void> _reconnectWebSocket() async {
|
||||||
try {
|
showSuccessToast('Успешный вход');
|
||||||
await sl<WsManager>().clear();
|
|
||||||
await sl<WsManager>().initialize();
|
|
||||||
} catch (e) {
|
|
||||||
rethrow;
|
|
||||||
}
|
|
||||||
if (context.mounted) {
|
|
||||||
try {
|
|
||||||
await sl<ProfileAvatarCubit>().getMyProfile();
|
|
||||||
await sl<ChatsCubit>().getChatRoomsWithLoading();
|
|
||||||
await sl<FirebaseApi>().registerPushToken();
|
|
||||||
showSuccessToast('Успешный вход');
|
|
||||||
} catch (e) {
|
|
||||||
rethrow;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
AppRouter.navigatorKey.currentContext?.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
|
AppRouter.navigatorKey.currentContext?.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -202,18 +183,7 @@ class _AuthScreenState extends State<AuthScreen> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _reconnectAfterAuth() async {
|
Future<void> _reconnectAfterAuth() async {
|
||||||
final context = AppRouter.navigatorKey.currentContext;
|
showSuccessToast('Успешный вход');
|
||||||
if (context == null) return;
|
|
||||||
try {
|
|
||||||
await sl<WsManager>().clear();
|
|
||||||
await sl<WsManager>().initialize();
|
|
||||||
await sl<ProfileAvatarCubit>().getMyProfile();
|
|
||||||
await sl<ChatsCubit>().getChatRoomsWithLoading();
|
|
||||||
await sl<FirebaseApi>().registerPushToken();
|
|
||||||
showSuccessToast('Успешный вход');
|
|
||||||
} catch (e) {
|
|
||||||
log(e.toString());
|
|
||||||
}
|
|
||||||
AppRouter.navigatorKey.currentContext?.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
|
AppRouter.navigatorKey.currentContext?.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -395,7 +365,7 @@ class _AuthScreenState extends State<AuthScreen> {
|
|||||||
final isAuthenticated = await authCubit.getTokenByCredentials(emailController.text, passwordController.text);
|
final isAuthenticated = await authCubit.getTokenByCredentials(emailController.text, passwordController.text);
|
||||||
if (isAuthenticated) {
|
if (isAuthenticated) {
|
||||||
if (context.mounted) {
|
if (context.mounted) {
|
||||||
await _reconnectWebSocket(context);
|
await _reconnectWebSocket();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setState(() {
|
setState(() {
|
||||||
|
|||||||
@@ -9,11 +9,7 @@ import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_sta
|
|||||||
import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart';
|
import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart';
|
||||||
import 'package:eatvio_app/core/app_router.dart';
|
import 'package:eatvio_app/core/app_router.dart';
|
||||||
import 'package:eatvio_app/core/locator_service.dart';
|
import 'package:eatvio_app/core/locator_service.dart';
|
||||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
|
||||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
|
|
||||||
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
|
|
||||||
import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart';
|
import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart';
|
||||||
import 'package:eatvio_app/core/firebase_api.dart';
|
|
||||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||||
import 'package:eatvio_app/core/utils/validation_utils.dart';
|
import 'package:eatvio_app/core/utils/validation_utils.dart';
|
||||||
import 'package:flutter/gestures.dart';
|
import 'package:flutter/gestures.dart';
|
||||||
@@ -62,23 +58,8 @@ class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
|
|||||||
_initializeFieldsFromAuthResult();
|
_initializeFieldsFromAuthResult();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _reconnectWebSocket(BuildContext context) async {
|
Future<void> _reconnectWebSocket() async {
|
||||||
try {
|
showSuccessToast('Успешная регистрация');
|
||||||
await sl<WsManager>().clear();
|
|
||||||
await sl<WsManager>().initialize();
|
|
||||||
} catch (e) {
|
|
||||||
rethrow;
|
|
||||||
}
|
|
||||||
if (context.mounted) {
|
|
||||||
try {
|
|
||||||
await sl<ProfileAvatarCubit>().getMyProfile();
|
|
||||||
await sl<ChatsCubit>().getChatRoomsWithLoading();
|
|
||||||
await sl<FirebaseApi>().registerPushToken();
|
|
||||||
showSuccessToast('Успешная регистрация');
|
|
||||||
} catch (e) {
|
|
||||||
rethrow;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
AppRouter.appRouter.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
|
AppRouter.appRouter.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -451,7 +432,7 @@ class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
|
|||||||
Builder(
|
Builder(
|
||||||
builder: (context) {
|
builder: (context) {
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
_reconnectWebSocket(context);
|
_reconnectWebSocket();
|
||||||
});
|
});
|
||||||
return const SizedBox.shrink();
|
return const SizedBox.shrink();
|
||||||
},
|
},
|
||||||
@@ -795,7 +776,7 @@ class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
|
|||||||
|
|
||||||
// Перезагружаем веб-сокет и переходим на главный экран
|
// Перезагружаем веб-сокет и переходим на главный экран
|
||||||
if (widgetContext.mounted) {
|
if (widgetContext.mounted) {
|
||||||
_reconnectWebSocket(widgetContext);
|
_reconnectWebSocket();
|
||||||
}
|
}
|
||||||
} catch (e, stackTrace) {
|
} catch (e, stackTrace) {
|
||||||
log('OAuth Verification Confirm Error: $e', error: e, stackTrace: stackTrace);
|
log('OAuth Verification Confirm Error: $e', error: e, stackTrace: stackTrace);
|
||||||
|
|||||||
@@ -3,13 +3,10 @@ import 'dart:io';
|
|||||||
import 'package:dio/dio.dart';
|
import 'package:dio/dio.dart';
|
||||||
import 'package:eatvio_app/core/app_config.dart';
|
import 'package:eatvio_app/core/app_config.dart';
|
||||||
import 'package:eatvio_app/core/app_router.dart';
|
import 'package:eatvio_app/core/app_router.dart';
|
||||||
import 'package:eatvio_app/core/firebase_api.dart';
|
|
||||||
import 'package:eatvio_app/core/locator_service.dart';
|
import 'package:eatvio_app/core/locator_service.dart';
|
||||||
|
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||||
import 'package:eatvio_app/core/token_storage.dart';
|
import 'package:eatvio_app/core/token_storage.dart';
|
||||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
|
||||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
|
|
||||||
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:go_router/go_router.dart';
|
import 'package:go_router/go_router.dart';
|
||||||
import 'package:qr_code_scanner_plus/qr_code_scanner_plus.dart';
|
import 'package:qr_code_scanner_plus/qr_code_scanner_plus.dart';
|
||||||
@@ -39,7 +36,10 @@ class _ScanQRCodeScreenState extends State<ScanQRCodeScreen> {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Сканирование QR-кода'), centerTitle: true),
|
appBar: AppBar(
|
||||||
|
title: const Text('Сканирование QR-кода'),
|
||||||
|
centerTitle: true,
|
||||||
|
),
|
||||||
body: Column(
|
body: Column(
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Expanded(
|
Expanded(
|
||||||
@@ -60,30 +60,33 @@ class _ScanQRCodeScreenState extends State<ScanQRCodeScreen> {
|
|||||||
try {
|
try {
|
||||||
final scannedUrl = scanData.code;
|
final scannedUrl = scanData.code;
|
||||||
final uri = Uri.parse(scannedUrl ?? '');
|
final uri = Uri.parse(scannedUrl ?? '');
|
||||||
final scannedBaseUrl = (uri.hasAuthority) ? '${uri.scheme}://${uri.host}' : '';
|
final scannedBaseUrl = (uri.hasAuthority)
|
||||||
|
? '${uri.scheme}://${uri.host}'
|
||||||
|
: '';
|
||||||
sl<AppConfig>().setBaseUrl(scannedBaseUrl);
|
sl<AppConfig>().setBaseUrl(scannedBaseUrl);
|
||||||
sl<Dio>().options.baseUrl = scannedBaseUrl;
|
sl<Dio>().options.baseUrl = scannedBaseUrl;
|
||||||
final response = await Dio().getUri(uri, options: Options(headers: {'accept': 'application/json', 'content-type': 'application/json'}));
|
final response = await Dio().getUri(
|
||||||
|
uri,
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'accept': 'application/json',
|
||||||
|
'content-type': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
final token = response.data['token'];
|
final token = response.data['token'];
|
||||||
await TokenStorage.saveTokenInStorage(token);
|
await TokenStorage.saveTokenInStorage(token);
|
||||||
try {
|
await sl<SessionLifecycleService>().onAuthenticated();
|
||||||
await sl<WsManager>().clear();
|
AppRouter.navigatorKey.currentContext?.go(
|
||||||
await sl<WsManager>().initialize();
|
'/feed-screen',
|
||||||
} catch (e) {
|
extra: {'needToInitializeWebSocket': false},
|
||||||
rethrow;
|
);
|
||||||
}
|
|
||||||
try {
|
|
||||||
await sl<ProfileAvatarCubit>().getMyProfile();
|
|
||||||
await sl<ChatsCubit>().getChatRoomsWithLoading();
|
|
||||||
await sl<FirebaseApi>().registerPushToken();
|
|
||||||
} catch (e) {
|
|
||||||
rethrow;
|
|
||||||
}
|
|
||||||
AppRouter.navigatorKey.currentContext?.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
|
|
||||||
showSuccessToast('Добро пожаловать!');
|
showSuccessToast('Добро пожаловать!');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
await controller.resumeCamera();
|
await controller.resumeCamera();
|
||||||
showErrorToast('Что-то пошло не так. Попробуйте обновить страницу с QR-кодом или войдите с помощью логина и пароля.');
|
showErrorToast(
|
||||||
|
'Что-то пошло не так. Попробуйте обновить страницу с QR-кодом или войдите с помощью логина и пароля.',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,13 @@ class NewMessagesCubit extends Cubit<NewMessagesState> {
|
|||||||
|
|
||||||
NewMessagesCubit() : super(const NewMessagesState.empty());
|
NewMessagesCubit() : super(const NewMessagesState.empty());
|
||||||
|
|
||||||
|
void reset() {
|
||||||
|
_messagesCount = 0;
|
||||||
|
if (!isClosed) {
|
||||||
|
emit(const NewMessagesState.empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void incrementCounter() {
|
void incrementCounter() {
|
||||||
_messagesCount++;
|
_messagesCount++;
|
||||||
emit(NewMessagesState.loaded(messagesCount: _messagesCount));
|
emit(NewMessagesState.loaded(messagesCount: _messagesCount));
|
||||||
|
|||||||
@@ -1,18 +1,22 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:appmetrica_plugin/appmetrica_plugin.dart';
|
import 'package:appmetrica_plugin/appmetrica_plugin.dart';
|
||||||
import 'package:eatvio_app/core/app_router.dart';
|
import 'package:eatvio_app/core/token_storage.dart';
|
||||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_state.dart';
|
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_state.dart';
|
||||||
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
|
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
|
||||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
import 'package:eatvio_app/core/error_reporting/report_from.dart';
|
import 'package:eatvio_app/core/error_reporting/report_from.dart';
|
||||||
import 'package:go_router/go_router.dart';
|
|
||||||
import 'package:permission_handler/permission_handler.dart';
|
import 'package:permission_handler/permission_handler.dart';
|
||||||
|
|
||||||
class ProfileAvatarCubit extends Cubit<ProfileAvatarState> {
|
class ProfileAvatarCubit extends Cubit<ProfileAvatarState> {
|
||||||
final ProfileRepository profileRepository;
|
final ProfileRepository profileRepository;
|
||||||
|
|
||||||
ProfileAvatarCubit({required this.profileRepository}) : super(const ProfileAvatarState.loading());
|
ProfileAvatarCubit({required this.profileRepository})
|
||||||
|
: super(const ProfileAvatarState.loading());
|
||||||
|
|
||||||
|
int _requestId = 0;
|
||||||
|
int? _sessionFingerprint;
|
||||||
|
bool _ensuring = false;
|
||||||
|
|
||||||
int _calculateAge(String birthdate) {
|
int _calculateAge(String birthdate) {
|
||||||
try {
|
try {
|
||||||
@@ -25,7 +29,8 @@ class ProfileAvatarCubit extends Cubit<ProfileAvatarState> {
|
|||||||
final now = DateTime.now();
|
final now = DateTime.now();
|
||||||
int age = now.year - birthYear;
|
int age = now.year - birthYear;
|
||||||
|
|
||||||
if (now.month < birthMonth || (now.month == birthMonth && now.day < birthDay)) {
|
if (now.month < birthMonth ||
|
||||||
|
(now.month == birthMonth && now.day < birthDay)) {
|
||||||
age--;
|
age--;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,30 +43,82 @@ class ProfileAvatarCubit extends Cubit<ProfileAvatarState> {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void reset() {
|
||||||
|
_requestId++;
|
||||||
|
_sessionFingerprint = null;
|
||||||
|
unawaited(AppMetrica.setUserProfileID(null).catchError((Object _) {}));
|
||||||
|
if (!isClosed) emit(const ProfileAvatarState.loading());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> ensureFreshForCurrentSession() async {
|
||||||
|
final token = await TokenStorage.getTokenFromStorage();
|
||||||
|
if (token == null || token.isEmpty) {
|
||||||
|
reset();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final fingerprint = token.hashCode;
|
||||||
|
if (_sessionFingerprint == fingerprint &&
|
||||||
|
state is ProfileAvatarStateLoaded) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_ensuring) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_ensuring = true;
|
||||||
|
try {
|
||||||
|
await getMyProfile();
|
||||||
|
} finally {
|
||||||
|
_ensuring = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> getMyProfile() async {
|
Future<void> getMyProfile() async {
|
||||||
|
final requestId = ++_requestId;
|
||||||
|
final token = await TokenStorage.getTokenFromStorage();
|
||||||
|
final fingerprint = token?.hashCode;
|
||||||
|
if (isClosed || requestId != _requestId) return;
|
||||||
|
|
||||||
emit(const ProfileAvatarState.loading());
|
emit(const ProfileAvatarState.loading());
|
||||||
try {
|
try {
|
||||||
final profile = await profileRepository.getMyProfile();
|
final profile = await profileRepository.getMyProfile();
|
||||||
|
if (isClosed || requestId != _requestId) return;
|
||||||
|
|
||||||
final profileDetails = await profileRepository.getMyProfileDetails();
|
final profileDetails = await profileRepository.getMyProfileDetails();
|
||||||
|
if (isClosed || requestId != _requestId) return;
|
||||||
|
|
||||||
|
_sessionFingerprint = fingerprint;
|
||||||
emit(ProfileAvatarState.loaded(profile: profile));
|
emit(ProfileAvatarState.loaded(profile: profile));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
final notificationStatus = await Permission.notification.status;
|
final notificationStatus = await Permission.notification.status;
|
||||||
|
if (isClosed || requestId != _requestId) return;
|
||||||
final isNotificationEnabled = notificationStatus.isGranted;
|
final isNotificationEnabled = notificationStatus.isGranted;
|
||||||
AppMetricaUserProfile userProfile = AppMetricaUserProfile([
|
AppMetricaUserProfile userProfile = AppMetricaUserProfile([
|
||||||
AppMetricaNameAttribute.withValue(profile.name),
|
AppMetricaNameAttribute.withValue(profile.name),
|
||||||
AppMetricaGenderAttribute.withValue(profileDetails.gender == 'male' ? AppMetricaGender.male : AppMetricaGender.female),
|
AppMetricaGenderAttribute.withValue(
|
||||||
AppMetricaBirthDateAttribute.withAge(_calculateAge(profileDetails.birthdate)),
|
profileDetails.gender == 'male'
|
||||||
AppMetricaNotificationEnabledAttribute.withValue(isNotificationEnabled),
|
? AppMetricaGender.male
|
||||||
|
: AppMetricaGender.female,
|
||||||
|
),
|
||||||
|
AppMetricaBirthDateAttribute.withAge(
|
||||||
|
_calculateAge(profileDetails.birthdate),
|
||||||
|
),
|
||||||
|
AppMetricaNotificationEnabledAttribute.withValue(
|
||||||
|
isNotificationEnabled,
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
AppMetrica.setUserProfileID(profile.slug);
|
AppMetrica.setUserProfileID(profile.slug);
|
||||||
AppMetrica.reportUserProfile(userProfile);
|
AppMetrica.reportUserProfile(userProfile);
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
await reportFrom(e, st, this);
|
await reportFrom(e, st, this);
|
||||||
// Игнорируем ошибки плагинов, профиль уже загружен
|
|
||||||
}
|
}
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
|
if (isClosed || requestId != _requestId) return;
|
||||||
await reportFrom(e, st, this);
|
await reportFrom(e, st, this);
|
||||||
AppRouter.navigatorKey.currentContext?.go('/auth-screen');
|
if (isClosed || requestId != _requestId) return;
|
||||||
emit(ProfileAvatarState.error(errorMessage: e.toString()));
|
emit(ProfileAvatarState.error(errorMessage: e.toString()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ class BottomNavigationBarWidget extends StatefulWidget {
|
|||||||
class _BottomNavigationBarWidgetState extends State<BottomNavigationBarWidget> {
|
class _BottomNavigationBarWidgetState extends State<BottomNavigationBarWidget> {
|
||||||
int currentBottomNavBarIndex = 1;
|
int currentBottomNavBarIndex = 1;
|
||||||
List<String>? pages;
|
List<String>? pages;
|
||||||
|
int? _pagesProfileId;
|
||||||
|
bool? _pagesIsConsultant;
|
||||||
int tapsCount = 0;
|
int tapsCount = 0;
|
||||||
|
|
||||||
List<String> _getPages(bool isConsultant) {
|
List<String> _getPages(bool isConsultant) {
|
||||||
@@ -179,7 +181,16 @@ class _BottomNavigationBarWidgetState extends State<BottomNavigationBarWidget> {
|
|||||||
final isConsultant = profileModel.roles.contains('consultant');
|
final isConsultant = profileModel.roles.contains('consultant');
|
||||||
|
|
||||||
// Инициализируем pages на основе profileModel
|
// Инициализируем pages на основе profileModel
|
||||||
pages ??= _getPages(isConsultant);
|
if (pages == null ||
|
||||||
|
_pagesProfileId != profileModel.id ||
|
||||||
|
_pagesIsConsultant != isConsultant) {
|
||||||
|
_pagesProfileId = profileModel.id;
|
||||||
|
_pagesIsConsultant = isConsultant;
|
||||||
|
pages = _getPages(isConsultant);
|
||||||
|
if (currentBottomNavBarIndex >= pages!.length) {
|
||||||
|
currentBottomNavBarIndex = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Expose tab switching to descendants (e.g. notification widget)
|
// Expose tab switching to descendants (e.g. notification widget)
|
||||||
final controller = BottomNavScope.maybeOf(context);
|
final controller = BottomNavScope.maybeOf(context);
|
||||||
|
|||||||
@@ -31,7 +31,9 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
|||||||
|
|
||||||
StreamSubscription<ChannelReadEvent>? typingSubscription;
|
StreamSubscription<ChannelReadEvent>? typingSubscription;
|
||||||
StreamSubscription<ChannelReadEvent>? messagesSubscription;
|
StreamSubscription<ChannelReadEvent>? messagesSubscription;
|
||||||
|
StreamSubscription<ChannelReadEvent>? _chosenPlanStateSubscription;
|
||||||
StreamSubscription<void>? _reconnectSubscription;
|
StreamSubscription<void>? _reconnectSubscription;
|
||||||
|
bool _isUpdatingChosenPlan = false;
|
||||||
int currentPage = 1;
|
int currentPage = 1;
|
||||||
late int lastPage;
|
late int lastPage;
|
||||||
bool isLoading = false;
|
bool isLoading = false;
|
||||||
@@ -171,6 +173,7 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
|||||||
log(e.toString());
|
log(e.toString());
|
||||||
typingSubscription?.cancel();
|
typingSubscription?.cancel();
|
||||||
messagesSubscription?.cancel();
|
messagesSubscription?.cancel();
|
||||||
|
_chosenPlanStateSubscription?.cancel();
|
||||||
_reconnectSubscription?.cancel();
|
_reconnectSubscription?.cancel();
|
||||||
_reconnectSubscription = null;
|
_reconnectSubscription = null;
|
||||||
wsManager.unsubscribeDirectChatChannel();
|
wsManager.unsubscribeDirectChatChannel();
|
||||||
@@ -260,19 +263,30 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> updateChosenPlanState() async {
|
Future<void> updateChosenPlanState() async {
|
||||||
|
if (_isUpdatingChosenPlan) return;
|
||||||
try {
|
try {
|
||||||
|
_isUpdatingChosenPlan = true;
|
||||||
final currentState = state;
|
final currentState = state;
|
||||||
if (currentState is! ChatRoomStateLoaded) {
|
if (currentState is! ChatRoomStateLoaded) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final chosenPlanId = currentState.chatRoom.chosenPlanId;
|
final chosenPlanId =
|
||||||
|
currentState.chatRoom.chosenPlanId ??
|
||||||
|
currentState.chatRoom.chosenPlan?.id;
|
||||||
if (chosenPlanId == null) {
|
if (chosenPlanId == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final chosenPlan = await chatRepository.getChosenPlan(id: chosenPlanId);
|
final chosenPlan = await chatRepository.getChosenPlan(id: chosenPlanId);
|
||||||
_emitLoaded((latest) => latest.copyWith.chatRoom(chosenPlan: chosenPlan));
|
if (isClosed) return;
|
||||||
|
_emitLoaded(
|
||||||
|
(latest) => latest.copyWith(
|
||||||
|
chatRoom: latest.chatRoom.copyWith(chosenPlan: chosenPlan),
|
||||||
|
),
|
||||||
|
);
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
await reportFrom(e, st, this);
|
await reportFrom(e, st, this);
|
||||||
|
} finally {
|
||||||
|
_isUpdatingChosenPlan = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -338,8 +352,10 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
|||||||
if (client == null) return;
|
if (client == null) return;
|
||||||
await messagesSubscription?.cancel();
|
await messagesSubscription?.cancel();
|
||||||
await typingSubscription?.cancel();
|
await typingSubscription?.cancel();
|
||||||
|
await _chosenPlanStateSubscription?.cancel();
|
||||||
messagesSubscription = null;
|
messagesSubscription = null;
|
||||||
typingSubscription = null;
|
typingSubscription = null;
|
||||||
|
_chosenPlanStateSubscription = null;
|
||||||
await wsManager.initPrivateDirectChatChannel(chatId);
|
await wsManager.initPrivateDirectChatChannel(chatId);
|
||||||
wsManager.subscribeDirectChatChannel();
|
wsManager.subscribeDirectChatChannel();
|
||||||
messagesSubscription = wsManager.directChatStream?.listen(
|
messagesSubscription = wsManager.directChatStream?.listen(
|
||||||
@@ -361,6 +377,20 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
_chosenPlanStateSubscription = wsManager
|
||||||
|
.chosenPlanStateChangedStream
|
||||||
|
?.listen(
|
||||||
|
(_) {
|
||||||
|
EasyDebounce.debounce(
|
||||||
|
'chosen-plan-state-changed',
|
||||||
|
const Duration(milliseconds: 250),
|
||||||
|
() => unawaited(updateChosenPlanState()),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
onError: (Object e, StackTrace st) {
|
||||||
|
unawaited(reportFrom(e, st, this));
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
void _onDirectChatEvent(ChannelReadEvent event) {
|
void _onDirectChatEvent(ChannelReadEvent event) {
|
||||||
@@ -731,6 +761,7 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
|||||||
Future<void> close() async {
|
Future<void> close() async {
|
||||||
EasyDebounce.cancel('client-typing');
|
EasyDebounce.cancel('client-typing');
|
||||||
EasyDebounce.cancel('searchChatRoom');
|
EasyDebounce.cancel('searchChatRoom');
|
||||||
|
EasyDebounce.cancel('chosen-plan-state-changed');
|
||||||
if (_presenceOnlineListener != null) {
|
if (_presenceOnlineListener != null) {
|
||||||
wsManager.removePresenceDirectChatListener(_presenceOnlineListener!);
|
wsManager.removePresenceDirectChatListener(_presenceOnlineListener!);
|
||||||
_presenceOnlineListener = null;
|
_presenceOnlineListener = null;
|
||||||
@@ -739,6 +770,7 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
|||||||
_timer?.cancel();
|
_timer?.cancel();
|
||||||
await messagesSubscription?.cancel();
|
await messagesSubscription?.cancel();
|
||||||
await typingSubscription?.cancel();
|
await typingSubscription?.cancel();
|
||||||
|
await _chosenPlanStateSubscription?.cancel();
|
||||||
await _reconnectSubscription?.cancel();
|
await _reconnectSubscription?.cancel();
|
||||||
super.close();
|
super.close();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import 'dart:async';
|
|||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'dart:developer';
|
import 'dart:developer';
|
||||||
|
|
||||||
|
import 'package:eatvio_app/core/device/device_hw_id_provider.dart';
|
||||||
import 'package:eatvio_app/core/enums/base_state.dart';
|
import 'package:eatvio_app/core/enums/base_state.dart';
|
||||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
||||||
import 'package:eatvio_app/features/chat/models/chat_message_model.dart';
|
import 'package:eatvio_app/features/chat/models/chat_message_model.dart';
|
||||||
@@ -10,7 +11,9 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_sta
|
|||||||
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
|
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
|
||||||
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
|
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
|
||||||
import 'package:eatvio_app/features/video_calls/services/video_call_chat_signal.dart';
|
import 'package:eatvio_app/features/video_calls/services/video_call_chat_signal.dart';
|
||||||
|
import 'package:eatvio_app/features/video_calls/services/video_call_end_reason.dart';
|
||||||
import 'package:eatvio_app/features/video_calls/services/video_call_ended_push_handler.dart';
|
import 'package:eatvio_app/features/video_calls/services/video_call_ended_push_handler.dart';
|
||||||
|
import 'package:eatvio_app/features/video_calls/services/video_call_socket_signal.dart';
|
||||||
import 'package:eatvio_app/features/video_calls/services/video_call_incoming_push_presenter.dart';
|
import 'package:eatvio_app/features/video_calls/services/video_call_incoming_push_presenter.dart';
|
||||||
import 'package:eatvio_app/features/video_calls/services/video_call_push_payload.dart';
|
import 'package:eatvio_app/features/video_calls/services/video_call_push_payload.dart';
|
||||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
@@ -23,11 +26,19 @@ class ChatsCubit extends Cubit<ChatsState> {
|
|||||||
StreamSubscription? newIncomingMessagesSubscription;
|
StreamSubscription? newIncomingMessagesSubscription;
|
||||||
StreamSubscription? newLastMessageSubscription;
|
StreamSubscription? newLastMessageSubscription;
|
||||||
StreamSubscription<void>? reconnectedSubscription;
|
StreamSubscription<void>? reconnectedSubscription;
|
||||||
|
StreamSubscription? videoCallDeclinedSubscription;
|
||||||
|
StreamSubscription? videoCallEndedSubscription;
|
||||||
|
StreamSubscription? videoCallAcceptedSubscription;
|
||||||
final Set<int> _presentedVideoCallMessageIds = {};
|
final Set<int> _presentedVideoCallMessageIds = {};
|
||||||
|
|
||||||
/// Test seam. Production uses CallKit.
|
/// Test seam. Production uses CallKit.
|
||||||
Future<void> Function(VideoCallPushPayload payload)? presentIncomingVideoCall;
|
Future<void> Function(VideoCallPushPayload payload)? presentIncomingVideoCall;
|
||||||
Future<void> Function()? dismissIncomingVideoCall;
|
|
||||||
|
/// Test seam. Production reads [DeviceHwIdProvider.current].
|
||||||
|
Future<String?> Function()? currentDeviceHwId;
|
||||||
|
Future<void> Function(String? conversationUuid)? dismissIncomingVideoCall;
|
||||||
|
Future<void> Function({String? conversationUuid, String? callId})?
|
||||||
|
endActiveVideoCall;
|
||||||
|
|
||||||
ChatsCubit({
|
ChatsCubit({
|
||||||
required this.chatRepository,
|
required this.chatRepository,
|
||||||
@@ -46,6 +57,17 @@ class ChatsCubit extends Cubit<ChatsState> {
|
|||||||
int page = 1;
|
int page = 1;
|
||||||
late int lastPage;
|
late int lastPage;
|
||||||
|
|
||||||
|
/// Clears all user-scoped state. WS subscriptions stay intact so that
|
||||||
|
/// `getChatRoomsWithLoading` can re-load the new user's chats.
|
||||||
|
void reset() {
|
||||||
|
_query = null;
|
||||||
|
page = 1;
|
||||||
|
lastPage = 1;
|
||||||
|
if (!isClosed) {
|
||||||
|
emit(ChatsState());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> connectToWebSocket() async {
|
Future<void> connectToWebSocket() async {
|
||||||
try {
|
try {
|
||||||
await newIncomingMessagesSubscription?.cancel();
|
await newIncomingMessagesSubscription?.cancel();
|
||||||
@@ -55,6 +77,37 @@ class ChatsCubit extends Cubit<ChatsState> {
|
|||||||
_handleNewMessageViaSocket(event.data);
|
_handleNewMessageViaSocket(event.data);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
await videoCallDeclinedSubscription?.cancel();
|
||||||
|
videoCallDeclinedSubscription = wsManager.videoCallDeclinedStream?.listen(
|
||||||
|
(event) {
|
||||||
|
unawaited(
|
||||||
|
_closeCallFromSocket(
|
||||||
|
VideoCallSocketSignal.tryParseDeclined(event.data),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
await videoCallEndedSubscription?.cancel();
|
||||||
|
videoCallEndedSubscription = wsManager.videoCallEndedStream?.listen((
|
||||||
|
event,
|
||||||
|
) {
|
||||||
|
unawaited(
|
||||||
|
_closeCallFromSocket(VideoCallSocketSignal.tryParseEnded(event.data)),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
await videoCallAcceptedSubscription?.cancel();
|
||||||
|
videoCallAcceptedSubscription = wsManager.videoCallAcceptedStream?.listen(
|
||||||
|
(event) {
|
||||||
|
unawaited(
|
||||||
|
_closeCallFromSocket(
|
||||||
|
VideoCallSocketSignal.tryParseEnded(event.data),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
await reconnectedSubscription?.cancel();
|
await reconnectedSubscription?.cancel();
|
||||||
reconnectedSubscription = wsManager.reconnected.listen((_) {
|
reconnectedSubscription = wsManager.reconnected.listen((_) {
|
||||||
unawaited(getChatRooms());
|
unawaited(getChatRooms());
|
||||||
@@ -170,6 +223,7 @@ class ChatsCubit extends Cubit<ChatsState> {
|
|||||||
try {
|
try {
|
||||||
final json = jsonDecode(data) as Map<String, dynamic>;
|
final json = jsonDecode(data) as Map<String, dynamic>;
|
||||||
final message = ChatMessageModel.fromJson(json);
|
final message = ChatMessageModel.fromJson(json);
|
||||||
|
final callId = _stringField(json, const ['call_id', 'callId']);
|
||||||
|
|
||||||
final currentUserId = wsManager.userId;
|
final currentUserId = wsManager.userId;
|
||||||
final isOwn = currentUserId != null && message.authorId == currentUserId;
|
final isOwn = currentUserId != null && message.authorId == currentUserId;
|
||||||
@@ -217,6 +271,7 @@ class ChatsCubit extends Cubit<ChatsState> {
|
|||||||
message,
|
message,
|
||||||
isOwn: isOwn,
|
isOwn: isOwn,
|
||||||
chatRooms: currentChatRooms,
|
chatRooms: currentChatRooms,
|
||||||
|
callId: callId,
|
||||||
);
|
);
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
await reportFrom(e, st, this);
|
await reportFrom(e, st, this);
|
||||||
@@ -227,10 +282,16 @@ class ChatsCubit extends Cubit<ChatsState> {
|
|||||||
ChatMessageModel message, {
|
ChatMessageModel message, {
|
||||||
required bool isOwn,
|
required bool isOwn,
|
||||||
required List<ChatRoom> chatRooms,
|
required List<ChatRoom> chatRooms,
|
||||||
|
String? callId,
|
||||||
}) {
|
}) {
|
||||||
final kind = VideoCallChatSignal.kindOf(message);
|
final kind = VideoCallChatSignal.kindOf(message);
|
||||||
if (kind == VideoCallChatSignalKind.ended) {
|
if (kind == VideoCallChatSignalKind.ended) {
|
||||||
unawaited(_dismissIncomingVideoCallUi());
|
unawaited(_dismissIncomingVideoCallUi(message.roomId));
|
||||||
|
unawaited(
|
||||||
|
VideoCallEndedPushHandler.endActiveCallIfMatches(
|
||||||
|
conversationUuid: message.roomId,
|
||||||
|
),
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (isOwn || kind != VideoCallChatSignalKind.started) return;
|
if (isOwn || kind != VideoCallChatSignalKind.started) return;
|
||||||
@@ -243,6 +304,7 @@ class ChatsCubit extends Cubit<ChatsState> {
|
|||||||
message: message,
|
message: message,
|
||||||
callerName: caller?.name,
|
callerName: caller?.name,
|
||||||
callerAvatarUrl: caller?.profilePhotoUrl,
|
callerAvatarUrl: caller?.profilePhotoUrl,
|
||||||
|
callId: callId,
|
||||||
);
|
);
|
||||||
if (payload == null) return;
|
if (payload == null) return;
|
||||||
unawaited(_showIncomingVideoCall(payload));
|
unawaited(_showIncomingVideoCall(payload));
|
||||||
@@ -257,10 +319,45 @@ class ChatsCubit extends Cubit<ChatsState> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _dismissIncomingVideoCallUi() async {
|
Future<void> _closeCallFromSocket(VideoCallSocketSignal? signal) async {
|
||||||
|
if (signal == null) return;
|
||||||
|
if (await _acceptedOnThisDevice(signal)) return;
|
||||||
|
if (signal.endsActiveCall) {
|
||||||
|
final endActive = endActiveVideoCall;
|
||||||
|
if (endActive != null) {
|
||||||
|
await endActive(
|
||||||
|
conversationUuid: signal.conversationUuid,
|
||||||
|
callId: signal.callId,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await VideoCallEndedPushHandler.endActiveCallIfMatches(
|
||||||
|
conversationUuid: signal.conversationUuid,
|
||||||
|
callId: signal.callId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final dismiss = dismissIncomingVideoCall;
|
||||||
|
if (dismiss != null) {
|
||||||
|
await dismiss(signal.conversationUuid);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await VideoCallEndedPushHandler.dismissIncomingCallUi(
|
||||||
|
conversationUuid: signal.conversationUuid,
|
||||||
|
callId: signal.callId,
|
||||||
|
reason: signal.reason,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _dismissIncomingVideoCallUi(String? conversationUuid) async {
|
||||||
try {
|
try {
|
||||||
await (dismissIncomingVideoCall ??
|
final dismiss = dismissIncomingVideoCall;
|
||||||
VideoCallEndedPushHandler.dismissIncomingCallUi)();
|
if (dismiss != null) {
|
||||||
|
await dismiss(conversationUuid);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await VideoCallEndedPushHandler.dismissIncomingCallUi(
|
||||||
|
conversationUuid: conversationUuid,
|
||||||
|
);
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
log(
|
log(
|
||||||
'ChatsCubit: failed to dismiss incoming video call: $e',
|
'ChatsCubit: failed to dismiss incoming video call: $e',
|
||||||
@@ -269,6 +366,34 @@ class ChatsCubit extends Cubit<ChatsState> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `video-call-accepted` also reaches the device that just answered.
|
||||||
|
/// Closing CallKit there hangs up the call that is starting.
|
||||||
|
Future<bool> _acceptedOnThisDevice(VideoCallSocketSignal signal) async {
|
||||||
|
if (signal.reason != VideoCallEndReason.accepted) return false;
|
||||||
|
final acceptedId = signal.acceptedDeviceId?.trim();
|
||||||
|
if (acceptedId == null || acceptedId.isEmpty) return false;
|
||||||
|
try {
|
||||||
|
final current =
|
||||||
|
(await (currentDeviceHwId ?? DeviceHwIdProvider.current)())?.trim();
|
||||||
|
if (current == null || current.isEmpty) return false;
|
||||||
|
return current.toLowerCase() == acceptedId.toLowerCase();
|
||||||
|
} catch (e, st) {
|
||||||
|
log(
|
||||||
|
'ChatsCubit: failed to read hw id for accepted call: $e',
|
||||||
|
stackTrace: st,
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _stringField(Map<String, dynamic> json, List<String> keys) {
|
||||||
|
for (final key in keys) {
|
||||||
|
final value = json[key];
|
||||||
|
if (value is String && value.trim().isNotEmpty) return value.trim();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
ChatUser? _callerFromRooms(
|
ChatUser? _callerFromRooms(
|
||||||
ChatMessageModel message,
|
ChatMessageModel message,
|
||||||
List<ChatRoom> chatRooms,
|
List<ChatRoom> chatRooms,
|
||||||
@@ -297,6 +422,9 @@ class ChatsCubit extends Cubit<ChatsState> {
|
|||||||
@override
|
@override
|
||||||
Future<void> close() {
|
Future<void> close() {
|
||||||
newIncomingMessagesSubscription?.cancel();
|
newIncomingMessagesSubscription?.cancel();
|
||||||
|
videoCallDeclinedSubscription?.cancel();
|
||||||
|
videoCallEndedSubscription?.cancel();
|
||||||
|
videoCallAcceptedSubscription?.cancel();
|
||||||
reconnectedSubscription?.cancel();
|
reconnectedSubscription?.cancel();
|
||||||
return super.close();
|
return super.close();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_
|
|||||||
import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart';
|
import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart';
|
||||||
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
|
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
|
||||||
import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart';
|
import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart';
|
||||||
import 'package:eatvio_app/features/chat/presentation/widgets/about_order_button.dart';
|
|
||||||
import 'package:eatvio_app/features/chat/presentation/widgets/chat_bubble_widget.dart';
|
import 'package:eatvio_app/features/chat/presentation/widgets/chat_bubble_widget.dart';
|
||||||
import 'package:eatvio_app/features/chat/models/chat_message_model.dart';
|
import 'package:eatvio_app/features/chat/models/chat_message_model.dart';
|
||||||
import 'package:eatvio_app/features/chat/models/chat_user_model.dart';
|
import 'package:eatvio_app/features/chat/models/chat_user_model.dart';
|
||||||
@@ -24,12 +23,15 @@ import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked
|
|||||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||||
import 'package:eatvio_app/features/chat/presentation/widgets/chat_user_online_status_line.dart';
|
import 'package:eatvio_app/features/chat/presentation/widgets/chat_user_online_status_line.dart';
|
||||||
|
import 'package:eatvio_app/features/chat/presentation/utils/chat_banner_resolver.dart';
|
||||||
|
import 'package:eatvio_app/features/chat/presentation/widgets/chat_consultation_header.dart';
|
||||||
import 'package:eatvio_app/features/chat/presentation/widgets/notification_banner.dart';
|
import 'package:eatvio_app/features/chat/presentation/widgets/notification_banner.dart';
|
||||||
import 'package:eatvio_app/features/chat/utils/chat_counterpart_utils.dart';
|
import 'package:eatvio_app/features/chat/utils/chat_counterpart_utils.dart';
|
||||||
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
|
import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart';
|
||||||
import 'package:eatvio_app/features/order_info/presentation/info_by_order_screen.dart';
|
import 'package:eatvio_app/features/order_info/presentation/info_by_order_screen.dart';
|
||||||
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||||
import 'package:eatvio_app/features/user_details/presentation/user_details_screen.dart';
|
import 'package:eatvio_app/features/user_details/presentation/user_details_screen.dart';
|
||||||
|
import 'package:eatvio_app/features/video_calls/managers/video_call_manager.dart';
|
||||||
import 'package:eatvio_app/features/video_calls/presentation/pages/video_call_screen.dart';
|
import 'package:eatvio_app/features/video_calls/presentation/pages/video_call_screen.dart';
|
||||||
import 'package:eatvio_app/generated/l10n.dart';
|
import 'package:eatvio_app/generated/l10n.dart';
|
||||||
import 'package:file_picker/file_picker.dart';
|
import 'package:file_picker/file_picker.dart';
|
||||||
@@ -62,8 +64,6 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
final TextEditingController textEditingController = TextEditingController();
|
final TextEditingController textEditingController = TextEditingController();
|
||||||
final ChatRoomCubit chatRoomCubit = sl<ChatRoomCubit>();
|
final ChatRoomCubit chatRoomCubit = sl<ChatRoomCubit>();
|
||||||
final List<int> unreadMessageIds = [];
|
final List<int> unreadMessageIds = [];
|
||||||
final showableChatBadgeStates =
|
|
||||||
ChosenPlanStateEnum.getShowableChatBadgeStates();
|
|
||||||
late AppLifecycleListener _listener;
|
late AppLifecycleListener _listener;
|
||||||
List<File> pickedFiles = [];
|
List<File> pickedFiles = [];
|
||||||
|
|
||||||
@@ -187,49 +187,24 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
ChosenPlanStateEnum.statePendingPayment,
|
ChosenPlanStateEnum.statePendingPayment,
|
||||||
ChosenPlanStateEnum.stateInCoordination,
|
ChosenPlanStateEnum.stateInCoordination,
|
||||||
].contains(chosenPlan?.chosenPlanState);
|
].contains(chosenPlan?.chosenPlanState);
|
||||||
PacketOptions? chosenOption;
|
final chosenOption = chosenPlan?.chosenOption;
|
||||||
if (chosenPlan?.optionType == 'options1') {
|
final progress = chosenPlan == null
|
||||||
chosenOption = chosenPlan?.plan.packet1Options;
|
? null
|
||||||
} else if (chosenPlan?.optionType == 'options2') {
|
: mapConsultationProgress(
|
||||||
chosenOption = chosenPlan?.plan.packet2Options;
|
state: chosenPlan.chosenPlanState,
|
||||||
} else if (chosenPlan?.optionType == 'options3') {
|
hasPersonalDiet: chosenOption?.hasPersonalDiet ?? false,
|
||||||
chosenOption = chosenPlan?.plan.packet3Options;
|
personalDietName: chosenPlan.personalDietName,
|
||||||
}
|
);
|
||||||
|
final bannerType = resolveChatBanner(
|
||||||
final showAboutOrderButton =
|
progress: progress,
|
||||||
state.chatRoom.chosenPlan != null &&
|
amIConsultant: amIConsultant,
|
||||||
state.chatRoom.chosenPlan!.chosenPlanState !=
|
hasCard: state.hasCard,
|
||||||
|
state: chosenPlan?.chosenPlanState,
|
||||||
|
);
|
||||||
|
final showInfoButton =
|
||||||
|
chosenPlan != null &&
|
||||||
|
chosenPlan.chosenPlanState !=
|
||||||
ChosenPlanStateEnum.stateCanceledByTheInitiator;
|
ChosenPlanStateEnum.stateCanceledByTheInitiator;
|
||||||
BannerType? bannerType;
|
|
||||||
if (chosenPlan == null ||
|
|
||||||
chosenPlan.chosenPlanState ==
|
|
||||||
ChosenPlanStateEnum.stateCanceledByTheInitiator) {
|
|
||||||
bannerType = null;
|
|
||||||
} else if (amIConsultant &&
|
|
||||||
!state.hasCard &&
|
|
||||||
chosenPlan.chosenPlanState == ChosenPlanStateEnum.stateInCoordination) {
|
|
||||||
bannerType = BannerType.card;
|
|
||||||
} else if (amIConsultant &&
|
|
||||||
chosenPlan.chosenPlanState == ChosenPlanStateEnum.stateInCoordination) {
|
|
||||||
bannerType = BannerType.date;
|
|
||||||
} else if (!amIConsultant &&
|
|
||||||
(chosenPlan.chosenPlanState ==
|
|
||||||
ChosenPlanStateEnum.stateStartDateHasBeenSet ||
|
|
||||||
chosenPlan.chosenPlanState ==
|
|
||||||
ChosenPlanStateEnum.statePendingPayment)) {
|
|
||||||
bannerType = BannerType.payment;
|
|
||||||
} else if (chosenPlan.chosenPlanState == ChosenPlanStateEnum.stateDone &&
|
|
||||||
amIConsultant) {
|
|
||||||
bannerType = BannerType.collectCharge;
|
|
||||||
} else if (chosenPlan.chosenPlanState ==
|
|
||||||
ChosenPlanStateEnum.stateLastDayFinished &&
|
|
||||||
!amIConsultant) {
|
|
||||||
bannerType = BannerType.finishPlan;
|
|
||||||
} else if (chosenOption?.hasPersonalDiet == true &&
|
|
||||||
amIConsultant &&
|
|
||||||
chosenPlan.chosenPlanState != ChosenPlanStateEnum.stateDone) {
|
|
||||||
bannerType = BannerType.setPersonalDiet;
|
|
||||||
}
|
|
||||||
|
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
resizeToAvoidBottomInset: true,
|
resizeToAvoidBottomInset: true,
|
||||||
@@ -339,6 +314,28 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
Column(
|
Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
|
if (progress != null)
|
||||||
|
ChatConsultationHeader(
|
||||||
|
progress: progress,
|
||||||
|
showInfoButton: showInfoButton,
|
||||||
|
onInfoTap: () {
|
||||||
|
if (amIConsultant) {
|
||||||
|
GoRouter.of(context).push(
|
||||||
|
InfoByOrderScreen.path,
|
||||||
|
extra: {
|
||||||
|
'planId': chosenPlan?.id,
|
||||||
|
'customerSlug':
|
||||||
|
state.chatRoom.users.receiver.slug,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
GoRouter.of(context).push(
|
||||||
|
InfoByOrderScreen.path,
|
||||||
|
extra: {'planId': chosenPlan?.id},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Container(
|
child: Container(
|
||||||
color: appTheme.whiteA700,
|
color: appTheme.whiteA700,
|
||||||
@@ -383,22 +380,9 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
final isPlanOrderMessage =
|
final isPlanOrderMessage =
|
||||||
message.type == ChatMessageType.planOrder;
|
message.type == ChatMessageType.planOrder;
|
||||||
|
|
||||||
PacketOptions? messageOption;
|
final messageOption = isPlanOrderMessage
|
||||||
if (isPlanOrderMessage &&
|
? chosenPlan?.chosenOption
|
||||||
chosenPlan != null) {
|
: null;
|
||||||
if (chosenPlan.optionType == 'options1') {
|
|
||||||
messageOption =
|
|
||||||
chosenPlan.plan.packet1Options;
|
|
||||||
} else if (chosenPlan.optionType ==
|
|
||||||
'options2') {
|
|
||||||
messageOption =
|
|
||||||
chosenPlan.plan.packet2Options;
|
|
||||||
} else if (chosenPlan.optionType ==
|
|
||||||
'options3') {
|
|
||||||
messageOption =
|
|
||||||
chosenPlan.plan.packet3Options;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return Column(
|
return Column(
|
||||||
children: [
|
children: [
|
||||||
@@ -449,21 +433,9 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
final isPlanOrderMessage =
|
final isPlanOrderMessage =
|
||||||
message.type == ChatMessageType.planOrder;
|
message.type == ChatMessageType.planOrder;
|
||||||
|
|
||||||
PacketOptions? messageOption;
|
final messageOption = isPlanOrderMessage
|
||||||
if (isPlanOrderMessage && chosenPlan != null) {
|
? chosenPlan?.chosenOption
|
||||||
if (chosenPlan.optionType == 'options1') {
|
: null;
|
||||||
messageOption =
|
|
||||||
chosenPlan.plan.packet1Options;
|
|
||||||
} else if (chosenPlan.optionType ==
|
|
||||||
'options2') {
|
|
||||||
messageOption =
|
|
||||||
chosenPlan.plan.packet2Options;
|
|
||||||
} else if (chosenPlan.optionType ==
|
|
||||||
'options3') {
|
|
||||||
messageOption =
|
|
||||||
chosenPlan.plan.packet3Options;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return Column(
|
return Column(
|
||||||
children: [
|
children: [
|
||||||
@@ -803,30 +775,6 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
if (showAboutOrderButton)
|
|
||||||
Positioned(
|
|
||||||
top: 8,
|
|
||||||
right: 15,
|
|
||||||
left: 16,
|
|
||||||
child: AboutOrderButton(
|
|
||||||
onTap: () async {
|
|
||||||
if (amIConsultant) {
|
|
||||||
GoRouter.of(context).push(
|
|
||||||
InfoByOrderScreen.path,
|
|
||||||
extra: {
|
|
||||||
'planId': state.chatRoom.chosenPlan?.id,
|
|
||||||
'customerSlug': state.chatRoom.users.receiver.slug,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
GoRouter.of(context).push(
|
|
||||||
InfoByOrderScreen.path,
|
|
||||||
extra: {'planId': state.chatRoom.chosenPlan?.id},
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -1009,6 +957,7 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
ChatRoomStateLoaded state,
|
ChatRoomStateLoaded state,
|
||||||
ChatUserModel chatCounterpart,
|
ChatUserModel chatCounterpart,
|
||||||
) {
|
) {
|
||||||
|
sl<VideoCallManager>().permitParticipantTokenRequest();
|
||||||
GoRouter.of(context).pushNamed(
|
GoRouter.of(context).pushNamed(
|
||||||
VideoCallScreen.name,
|
VideoCallScreen.name,
|
||||||
extra: <String, dynamic>{
|
extra: <String, dynamic>{
|
||||||
|
|||||||
@@ -135,9 +135,9 @@ class _EmptyChatScreenState extends State<EmptyChatScreen> {
|
|||||||
textEditingController.clear();
|
textEditingController.clear();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
final chatId = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
||||||
if (context.mounted) {
|
if (chatId != null && chatId.isNotEmpty && context.mounted) {
|
||||||
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError});
|
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatId});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -189,9 +189,9 @@ class _EmptyChatScreenState extends State<EmptyChatScreen> {
|
|||||||
if (images.isNotEmpty) {
|
if (images.isNotEmpty) {
|
||||||
List<File> files = images.map((image) => File(image.path)).toList();
|
List<File> files = images.map((image) => File(image.path)).toList();
|
||||||
await sl<ChatRepository>().sendMessage(files: files, slug: widget.user.slug);
|
await sl<ChatRepository>().sendMessage(files: files, slug: widget.user.slug);
|
||||||
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
final chatId = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
||||||
if (mounted) {
|
if (chatId != null && chatId.isNotEmpty && mounted) {
|
||||||
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError});
|
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatId});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -205,9 +205,9 @@ class _EmptyChatScreenState extends State<EmptyChatScreen> {
|
|||||||
if (images.isNotEmpty) {
|
if (images.isNotEmpty) {
|
||||||
List<File> files = images.map((image) => File(image.path)).toList();
|
List<File> files = images.map((image) => File(image.path)).toList();
|
||||||
await sl<ChatRepository>().sendMessage(files: files, slug: widget.user.slug);
|
await sl<ChatRepository>().sendMessage(files: files, slug: widget.user.slug);
|
||||||
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
final chatId = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
||||||
if (mounted) {
|
if (chatId != null && chatId.isNotEmpty && mounted) {
|
||||||
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError});
|
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatId});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -243,9 +243,9 @@ class _EmptyChatScreenState extends State<EmptyChatScreen> {
|
|||||||
if (result != null) {
|
if (result != null) {
|
||||||
List<File> files = result.paths.map((path) => File(path!)).toList();
|
List<File> files = result.paths.map((path) => File(path!)).toList();
|
||||||
await sl<ChatRepository>().sendMessage(files: files, slug: widget.user.slug);
|
await sl<ChatRepository>().sendMessage(files: files, slug: widget.user.slug);
|
||||||
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
final chatId = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
||||||
if (mounted) {
|
if (chatId != null && chatId.isNotEmpty && mounted) {
|
||||||
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError});
|
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatId});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import 'package:eatvio_app/features/chat/presentation/widgets/notification_banner.dart';
|
||||||
|
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
|
||||||
|
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||||
|
|
||||||
|
BannerType? resolveChatBanner({
|
||||||
|
required ConsultationProgress? progress,
|
||||||
|
required bool amIConsultant,
|
||||||
|
required bool hasCard,
|
||||||
|
required ChosenPlanStateEnum? state,
|
||||||
|
}) {
|
||||||
|
if (progress == null ||
|
||||||
|
state == null ||
|
||||||
|
progress.phase != ConsultationPhase.active) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (amIConsultant &&
|
||||||
|
!hasCard &&
|
||||||
|
state == ChosenPlanStateEnum.stateInCoordination) {
|
||||||
|
return BannerType.card;
|
||||||
|
}
|
||||||
|
if (amIConsultant && state == ChosenPlanStateEnum.stateInCoordination) {
|
||||||
|
return BannerType.date;
|
||||||
|
}
|
||||||
|
if (!amIConsultant &&
|
||||||
|
(state == ChosenPlanStateEnum.stateStartDateHasBeenSet ||
|
||||||
|
state == ChosenPlanStateEnum.statePendingPayment)) {
|
||||||
|
return BannerType.payment;
|
||||||
|
}
|
||||||
|
if (state == ChosenPlanStateEnum.stateDone && amIConsultant) {
|
||||||
|
return BannerType.collectCharge;
|
||||||
|
}
|
||||||
|
if (state == ChosenPlanStateEnum.stateLastDayFinished && !amIConsultant) {
|
||||||
|
return BannerType.finishPlan;
|
||||||
|
}
|
||||||
|
if (!amIConsultant) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state == ChosenPlanStateEnum.statePaid &&
|
||||||
|
progress.dietStatus == PersonalDietStatus.notProposed) {
|
||||||
|
return BannerType.setPersonalDiet;
|
||||||
|
}
|
||||||
|
if ((state == ChosenPlanStateEnum.personalDietSet ||
|
||||||
|
state == ChosenPlanStateEnum.stateStarted ||
|
||||||
|
state == ChosenPlanStateEnum.stateInProgress) &&
|
||||||
|
progress.dietStatus == PersonalDietStatus.proposed) {
|
||||||
|
return BannerType.changePersonalDiet;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||||
|
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||||
|
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
|
||||||
|
import 'package:eatvio_app/features/consultations/presentation/widgets/consultation_progress_plank.dart';
|
||||||
|
import 'package:eatvio_app/features/consultations/presentation/widgets/personal_diet_status_chip.dart';
|
||||||
|
import 'package:eatvio_app/generated/l10n.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
class ChatConsultationHeader extends StatelessWidget {
|
||||||
|
const ChatConsultationHeader({
|
||||||
|
super.key,
|
||||||
|
required this.progress,
|
||||||
|
required this.showInfoButton,
|
||||||
|
required this.onInfoTap,
|
||||||
|
});
|
||||||
|
|
||||||
|
final ConsultationProgress progress;
|
||||||
|
final bool showInfoButton;
|
||||||
|
final VoidCallback onInfoTap;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final showPlank = progress.showProgressPlank;
|
||||||
|
final showChip = progress.hasChip;
|
||||||
|
if (!showPlank && !showChip && !showInfoButton) {
|
||||||
|
return const SizedBox.shrink();
|
||||||
|
}
|
||||||
|
|
||||||
|
final s = S.of(context);
|
||||||
|
|
||||||
|
return Container(
|
||||||
|
margin: const EdgeInsets.fromLTRB(16, 8, 16, 0),
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: appTheme.commentBg,
|
||||||
|
borderRadius: BorderRadius.circular(20),
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
if (progress.phase == ConsultationPhase.active || showPlank)
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
_title(s),
|
||||||
|
style: TextStyles.textMMedium.copyWith(
|
||||||
|
color: appTheme.black,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (showInfoButton)
|
||||||
|
_InfoButton(
|
||||||
|
onTap: onInfoTap,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
else if (showInfoButton)
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerRight,
|
||||||
|
child: _InfoButton(
|
||||||
|
onTap: onInfoTap,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (showPlank) ...[
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
ConsultationProgressPlank(progress: progress),
|
||||||
|
],
|
||||||
|
if (showChip) ...[
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
PersonalDietStatusChip(progress: progress),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _title(S s) {
|
||||||
|
if (progress.isCanceled) return s.orderCanceled;
|
||||||
|
if (progress.isPaymentFailed) return s.payment_failed;
|
||||||
|
if (progress.isStepCompleted(ConsultationStep.finished)) return s.done;
|
||||||
|
if (progress.showProgressPlank) return s.order_in_progress;
|
||||||
|
return s.more_about_order;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _InfoButton extends StatelessWidget {
|
||||||
|
const _InfoButton({required this.onTap});
|
||||||
|
|
||||||
|
final VoidCallback onTap;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return InkWell(
|
||||||
|
onTap: onTap,
|
||||||
|
customBorder: const CircleBorder(),
|
||||||
|
child: Container(
|
||||||
|
width: 32,
|
||||||
|
height: 32,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: appTheme.whiteA700,
|
||||||
|
shape: BoxShape.circle,
|
||||||
|
),
|
||||||
|
child: Icon(
|
||||||
|
Icons.info_outline_rounded,
|
||||||
|
size: 18,
|
||||||
|
color: appTheme.blueA400,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -106,7 +106,11 @@ class _NotificationBannerState extends State<NotificationBanner> {
|
|||||||
onTap: () {
|
onTap: () {
|
||||||
final planId = (context.read<ChatRoomCubit>().state as ChatRoomStateLoaded).chatRoom.chosenPlan?.id;
|
final planId = (context.read<ChatRoomCubit>().state as ChatRoomStateLoaded).chatRoom.chosenPlan?.id;
|
||||||
if (planId != null) {
|
if (planId != null) {
|
||||||
showConsultationPaymentFlow(context, planId: planId);
|
showConsultationPaymentFlow(
|
||||||
|
context,
|
||||||
|
planId: planId,
|
||||||
|
amount: widget.planPrice,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
child: Text(s.pay, style: TextStyles.textLSemibold.copyWith(color: appTheme.blueA400)),
|
child: Text(s.pay, style: TextStyles.textLSemibold.copyWith(color: appTheme.blueA400)),
|
||||||
@@ -142,12 +146,37 @@ class _NotificationBannerState extends State<NotificationBanner> {
|
|||||||
BannerType.setPersonalDiet => [
|
BannerType.setPersonalDiet => [
|
||||||
SizedBox(
|
SizedBox(
|
||||||
width: size.width * 0.6,
|
width: size.width * 0.6,
|
||||||
child: Text(s.createPersonalDiet, style: TextStyles.textMMedium.copyWith(color: appTheme.black)),
|
child: Text(s.suggestDiet, style: TextStyles.textMMedium.copyWith(color: appTheme.black)),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
GestureDetector(
|
GestureDetector(
|
||||||
onTap: () {
|
onTap: () {
|
||||||
GoRouter.of(context).pushNamed(MyDietsScreen.name);
|
GoRouter.of(context).pushNamed(
|
||||||
|
MyDietsScreen.name,
|
||||||
|
queryParameters: {'initialTabIndex': '2'},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
child: Text(s.goToMyDiets, style: TextStyles.textLSemibold.copyWith(color: appTheme.blueA400)),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
],
|
||||||
|
BannerType.changePersonalDiet => [
|
||||||
|
SizedBox(
|
||||||
|
width: size.width * 0.6,
|
||||||
|
child: Text(s.change_personal_diet, style: TextStyles.textMMedium.copyWith(color: appTheme.black)),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
SizedBox(
|
||||||
|
width: size.width * 0.6,
|
||||||
|
child: Text(s.personal_diet_replaces_tomorrow, style: TextStyles.textSMedium.copyWith(color: appTheme.black)),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
GestureDetector(
|
||||||
|
onTap: () {
|
||||||
|
GoRouter.of(context).pushNamed(
|
||||||
|
MyDietsScreen.name,
|
||||||
|
queryParameters: {'initialTabIndex': '2'},
|
||||||
|
);
|
||||||
},
|
},
|
||||||
child: Text(s.goToMyDiets, style: TextStyles.textLSemibold.copyWith(color: appTheme.blueA400)),
|
child: Text(s.goToMyDiets, style: TextStyles.textLSemibold.copyWith(color: appTheme.blueA400)),
|
||||||
),
|
),
|
||||||
@@ -240,4 +269,4 @@ class _StarIcon extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
enum BannerType { date, card, payment, collectCharge, finishPlan, setPersonalDiet }
|
enum BannerType { date, card, payment, collectCharge, finishPlan, setPersonalDiet, changePersonalDiet }
|
||||||
|
|||||||
@@ -137,11 +137,12 @@ class ChatRepository {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<String> getChatByUserSlug(String slug) async {
|
Future<String?> getChatByUserSlug(String slug) async {
|
||||||
final response = await chatService.getChatByUserSlug(slug: slug);
|
final response = await chatService.getChatByUserSlug(slug: slug);
|
||||||
if (response.response.statusCode == 404) {
|
final data = response.data;
|
||||||
return '404';
|
if (data is Map && data['id'] is String && (data['id'] as String).isNotEmpty) {
|
||||||
|
return data['id'] as String;
|
||||||
}
|
}
|
||||||
return response.data['id'];
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ class BecomeConsultantScreen extends StatefulWidget {
|
|||||||
class _BecomeConsultantScreenState extends State<BecomeConsultantScreen> {
|
class _BecomeConsultantScreenState extends State<BecomeConsultantScreen> {
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||||
|
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('Стать консультантом'),
|
title: const Text('Стать консультантом'),
|
||||||
@@ -24,14 +26,18 @@ class _BecomeConsultantScreenState extends State<BecomeConsultantScreen> {
|
|||||||
icon: const Icon(Icons.close),
|
icon: const Icon(Icons.close),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
body: const Padding(
|
body: SingleChildScrollView(
|
||||||
padding: EdgeInsets.all(16),
|
physics: const BouncingScrollPhysics(),
|
||||||
child: Text(
|
padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + 52 + 8 + bottomInset),
|
||||||
|
child: const Text(
|
||||||
'Чтобы стать консультантом необходимо пройти короткую регистрацию. Подготовьте свои дипломы и/или сертификаты в формате jpg, они Вам пригодятся для проверки и подтверждения. Также необходимо будет указать ссылки на Ваши соц. сети и указать тип лица (физ. лицо или юр. лицо). На данный момент доступна регистрация в качестве физ. лица.\n\nВнутри Итвио разница между обычным пользователем и консультантом заключается в дополнительных возможностях последнего создавать публичные диеты, рецепты и планы питания; участвовать в ежемесячных рейтингах.',
|
'Чтобы стать консультантом необходимо пройти короткую регистрацию. Подготовьте свои дипломы и/или сертификаты в формате jpg, они Вам пригодятся для проверки и подтверждения. Также необходимо будет указать ссылки на Ваши соц. сети и указать тип лица (физ. лицо или юр. лицо). На данный момент доступна регистрация в качестве физ. лица.\n\nВнутри Итвио разница между обычным пользователем и консультантом заключается в дополнительных возможностях последнего создавать публичные диеты, рецепты и планы питания; участвовать в ежемесячных рейтингах.',
|
||||||
style: TextStyle(fontSize: 16),
|
style: TextStyle(fontSize: 16),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
bottomSheet: _startRegistrationButton(),
|
bottomSheet: Padding(
|
||||||
|
padding: EdgeInsets.fromLTRB(16, 0, 16, 8 + bottomInset),
|
||||||
|
child: _startRegistrationButton(),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,7 +50,7 @@ class _BecomeConsultantScreenState extends State<BecomeConsultantScreen> {
|
|||||||
borderRadius: BorderRadius.circular(20),
|
borderRadius: BorderRadius.circular(20),
|
||||||
child: Ink(
|
child: Ink(
|
||||||
height: 52,
|
height: 52,
|
||||||
width: MediaQuery.of(context).size.width - 32,
|
width: double.infinity,
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
borderRadius: BorderRadius.circular(20),
|
borderRadius: BorderRadius.circular(20),
|
||||||
color: appTheme.blueA400,
|
color: appTheme.blueA400,
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ part 'consultation_model.g.dart';
|
|||||||
abstract class ConsultationModel with _$ConsultationModel {
|
abstract class ConsultationModel with _$ConsultationModel {
|
||||||
factory ConsultationModel({
|
factory ConsultationModel({
|
||||||
required int id,
|
required int id,
|
||||||
|
@JsonKey(name: 'chat_id') String? chatId,
|
||||||
@JsonKey(name: 'last_state') required ChosenPlanStateEnum chosenPlanState,
|
@JsonKey(name: 'last_state') required ChosenPlanStateEnum chosenPlanState,
|
||||||
@JsonKey(name: 'plan_title') required String planTitle,
|
@JsonKey(name: 'plan_title') required String planTitle,
|
||||||
@JsonKey(name: 'user_name') required String userName,
|
@JsonKey(name: 'user_name') required String userName,
|
||||||
@@ -19,10 +20,11 @@ abstract class ConsultationModel with _$ConsultationModel {
|
|||||||
@JsonKey(name: 'user_profile_photo_url') required String userProfilePhotoUrl,
|
@JsonKey(name: 'user_profile_photo_url') required String userProfilePhotoUrl,
|
||||||
@JsonKey(name: 'consultation_option_price') required int consultationOptionPrice,
|
@JsonKey(name: 'consultation_option_price') required int consultationOptionPrice,
|
||||||
@JsonKey(name: 'start_date', fromJson: parseDate) required DateTime startDate,
|
@JsonKey(name: 'start_date', fromJson: parseDate) required DateTime startDate,
|
||||||
@JsonKey(name: 'end_date', fromJson: parseDate) required DateTime endDate,
|
@JsonKey(name: 'end_date', fromJson: parseDateOrNull) DateTime? endDate,
|
||||||
@JsonKey(name: 'consultant_id') required int consultantId,
|
@JsonKey(name: 'consultant_id') required int consultantId,
|
||||||
required List<DiaryModel> diaries,
|
required List<DiaryModel> diaries,
|
||||||
@JsonKey(name: 'personal_diet_id') required int? personalDietId,
|
@JsonKey(name: 'personal_diet_id') required int? personalDietId,
|
||||||
|
@JsonKey(name: 'personal_diet_name') String? personalDietName,
|
||||||
}) = _ConsultationModel;
|
}) = _ConsultationModel;
|
||||||
|
|
||||||
factory ConsultationModel.fromJson(Map<String, dynamic> json) => _$ConsultationModelFromJson(json);
|
factory ConsultationModel.fromJson(Map<String, dynamic> json) => _$ConsultationModelFromJson(json);
|
||||||
@@ -39,6 +41,11 @@ abstract class DiaryModel with _$DiaryModel {
|
|||||||
factory DiaryModel.fromJson(Map<String, dynamic> json) => _$DiaryModelFromJson(json);
|
factory DiaryModel.fromJson(Map<String, dynamic> json) => _$DiaryModelFromJson(json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
DateTime? parseDateOrNull(dynamic date) {
|
||||||
|
if (date == null) return null;
|
||||||
|
return parseDate(date as String);
|
||||||
|
}
|
||||||
|
|
||||||
DateTime parseUnformattedDate(String date) {
|
DateTime parseUnformattedDate(String date) {
|
||||||
final dateChunks = date.split('-').map(int.parse).toList();
|
final dateChunks = date.split('-').map(int.parse).toList();
|
||||||
|
|
||||||
|
|||||||
33
lib/features/consultations/models/consultation_progress.dart
Normal file
33
lib/features/consultations/models/consultation_progress.dart
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
enum ConsultationStep { startDate, paid, inProgress, finished }
|
||||||
|
|
||||||
|
enum PersonalDietStatus { notRequired, notProposed, proposed }
|
||||||
|
|
||||||
|
enum ConsultationPhase { active, canceled, paymentFailed }
|
||||||
|
|
||||||
|
class ConsultationProgress {
|
||||||
|
const ConsultationProgress({
|
||||||
|
required this.completedSteps,
|
||||||
|
required this.showProgressPlank,
|
||||||
|
required this.dietStatus,
|
||||||
|
required this.phase,
|
||||||
|
this.personalDietName,
|
||||||
|
});
|
||||||
|
|
||||||
|
final Set<ConsultationStep> completedSteps;
|
||||||
|
final bool showProgressPlank;
|
||||||
|
final PersonalDietStatus dietStatus;
|
||||||
|
final ConsultationPhase phase;
|
||||||
|
final String? personalDietName;
|
||||||
|
|
||||||
|
bool isStepCompleted(ConsultationStep step) => completedSteps.contains(step);
|
||||||
|
|
||||||
|
bool get hasDietChip => dietStatus != PersonalDietStatus.notRequired;
|
||||||
|
|
||||||
|
bool get hasStatusChip => phase != ConsultationPhase.active;
|
||||||
|
|
||||||
|
bool get hasChip => hasDietChip || hasStatusChip;
|
||||||
|
|
||||||
|
bool get isCanceled => phase == ConsultationPhase.canceled;
|
||||||
|
|
||||||
|
bool get isPaymentFailed => phase == ConsultationPhase.paymentFailed;
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import 'dart:developer';
|
import 'dart:developer';
|
||||||
|
|
||||||
import 'package:eatvio_app/core/enums/base_state.dart';
|
import 'package:eatvio_app/core/enums/base_state.dart';
|
||||||
|
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
|
||||||
import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_state.dart';
|
import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_state.dart';
|
||||||
import 'package:eatvio_app/features/consultations/repositories/consultations_repository.dart';
|
import 'package:eatvio_app/features/consultations/repositories/consultations_repository.dart';
|
||||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
@@ -8,7 +9,8 @@ import 'package:eatvio_app/core/error_reporting/report_from.dart';
|
|||||||
|
|
||||||
class ConsultationsCubit extends Cubit<ConsultationsState> {
|
class ConsultationsCubit extends Cubit<ConsultationsState> {
|
||||||
final ConsultationsRepository consultationsRepository;
|
final ConsultationsRepository consultationsRepository;
|
||||||
ConsultationsCubit({required this.consultationsRepository}) : super(ConsultationsState());
|
final ChatRepository chatRepository;
|
||||||
|
ConsultationsCubit({required this.consultationsRepository, required this.chatRepository}) : super(ConsultationsState());
|
||||||
|
|
||||||
Future<void> loadConsultations() async {
|
Future<void> loadConsultations() async {
|
||||||
try {
|
try {
|
||||||
@@ -20,4 +22,14 @@ class ConsultationsCubit extends Cubit<ConsultationsState> {
|
|||||||
emit(state.copyWith(state: BaseState.error));
|
emit(state.copyWith(state: BaseState.error));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<String?> getChatIdByUserSlug(String slug) async {
|
||||||
|
try {
|
||||||
|
return await chatRepository.getChatByUserSlug(slug);
|
||||||
|
} catch (e, st) {
|
||||||
|
await reportFrom(e, st, this);
|
||||||
|
log(e.toString(), stackTrace: st);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,14 +3,17 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
|||||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||||
import 'package:eatvio_app/core/widgets/custom_divider.dart';
|
import 'package:eatvio_app/core/widgets/custom_divider.dart';
|
||||||
import 'package:eatvio_app/core/widgets/custom_outlined_button.dart';
|
import 'package:eatvio_app/core/widgets/custom_outlined_button.dart';
|
||||||
|
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||||
import 'package:eatvio_app/core/widgets/show_error_dialog.dart';
|
import 'package:eatvio_app/core/widgets/show_error_dialog.dart';
|
||||||
import 'package:eatvio_app/features/consultations/models/consultation_model.dart';
|
import 'package:eatvio_app/features/consultations/models/consultation_model.dart';
|
||||||
|
import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_cubit.dart';
|
||||||
import 'package:eatvio_app/features/diary/presentation/pages/diary_screen.dart';
|
import 'package:eatvio_app/features/diary/presentation/pages/diary_screen.dart';
|
||||||
import 'package:eatvio_app/features/my_finance/presentation/pages/card_settings.dart';
|
import 'package:eatvio_app/features/my_finance/presentation/pages/card_settings.dart';
|
||||||
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||||
import 'package:eatvio_app/features/user_details/presentation/user_details_screen.dart';
|
import 'package:eatvio_app/features/user_details/presentation/user_details_screen.dart';
|
||||||
import 'package:eatvio_app/generated/l10n.dart';
|
import 'package:eatvio_app/generated/l10n.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
import 'package:go_router/go_router.dart';
|
import 'package:go_router/go_router.dart';
|
||||||
|
|
||||||
class ConsultationCardWidget extends StatefulWidget {
|
class ConsultationCardWidget extends StatefulWidget {
|
||||||
@@ -34,6 +37,7 @@ class _ConsultationCardWidgetState extends State<ConsultationCardWidget> {
|
|||||||
final List<Color> legendColors = const [Colors.white, Color(0xFFF0C497), Color(0xFFFF9500), Color(0xFF2F80ED), Color(0xFF4CD964)];
|
final List<Color> legendColors = const [Colors.white, Color(0xFFF0C497), Color(0xFFFF9500), Color(0xFF2F80ED), Color(0xFF4CD964)];
|
||||||
|
|
||||||
late final List<(int, DiaryModel)> givenDaysWithDayNumber;
|
late final List<(int, DiaryModel)> givenDaysWithDayNumber;
|
||||||
|
bool _isOpeningChat = false;
|
||||||
final List<List<DiaryStateEnum>> legendStates = [
|
final List<List<DiaryStateEnum>> legendStates = [
|
||||||
[DiaryStateEnum.init],
|
[DiaryStateEnum.init],
|
||||||
[DiaryStateEnum.started, DiaryStateEnum.lastDayStarted],
|
[DiaryStateEnum.started, DiaryStateEnum.lastDayStarted],
|
||||||
@@ -81,6 +85,30 @@ class _ConsultationCardWidgetState extends State<ConsultationCardWidget> {
|
|||||||
widget.consultationsModel.planTitle,
|
widget.consultationsModel.planTitle,
|
||||||
style: const TextStyle(height: 1, color: Color(0xFF88949F), fontSize: 14, fontWeight: FontWeight.w500),
|
style: const TextStyle(height: 1, color: Color(0xFF88949F), fontSize: 14, fontWeight: FontWeight.w500),
|
||||||
),
|
),
|
||||||
|
if (widget.consultationsModel.personalDietId != null) ...[
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: 8,
|
||||||
|
vertical: 4,
|
||||||
|
),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: appTheme.transparentGreen,
|
||||||
|
borderRadius: BorderRadius.circular(100),
|
||||||
|
),
|
||||||
|
child: Text(
|
||||||
|
widget.consultationsModel.personalDietName == null ||
|
||||||
|
widget.consultationsModel.personalDietName!.isEmpty
|
||||||
|
? s.personal_diet_proposed
|
||||||
|
: s.personal_diet_proposed_named(
|
||||||
|
widget.consultationsModel.personalDietName!,
|
||||||
|
),
|
||||||
|
style: TextStyles.textXSSemibold.copyWith(
|
||||||
|
color: appTheme.greenA700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -279,7 +307,7 @@ class _ConsultationCardWidgetState extends State<ConsultationCardWidget> {
|
|||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
InkWell(
|
InkWell(
|
||||||
borderRadius: BorderRadius.circular(20),
|
borderRadius: BorderRadius.circular(20),
|
||||||
onTap: () {},
|
onTap: _isOpeningChat ? null : _openChat,
|
||||||
child: Ink(
|
child: Ink(
|
||||||
height: 52,
|
height: 52,
|
||||||
width: 52,
|
width: 52,
|
||||||
@@ -308,6 +336,22 @@ class _ConsultationCardWidgetState extends State<ConsultationCardWidget> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _openChat() async {
|
||||||
|
if (_isOpeningChat) return;
|
||||||
|
setState(() => _isOpeningChat = true);
|
||||||
|
var chatId = widget.consultationsModel.chatId;
|
||||||
|
if (chatId == null || chatId.isEmpty) {
|
||||||
|
chatId = await context.read<ConsultationsCubit>().getChatIdByUserSlug(widget.consultationsModel.userSlug);
|
||||||
|
}
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _isOpeningChat = false);
|
||||||
|
if (chatId == null || chatId.isEmpty) {
|
||||||
|
showErrorToast(S.of(context).msg_something_went_wrong);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
GoRouter.of(context).pushNamed('chatScreen', extra: {'uuid': chatId});
|
||||||
|
}
|
||||||
|
|
||||||
Row _legendTitle(String text, Color color) {
|
Row _legendTitle(String text, Color color) {
|
||||||
return Row(
|
return Row(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||||
|
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||||
|
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
|
||||||
|
import 'package:eatvio_app/generated/l10n.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
class ConsultationProgressPlank extends StatelessWidget {
|
||||||
|
const ConsultationProgressPlank({super.key, required this.progress});
|
||||||
|
|
||||||
|
final ConsultationProgress progress;
|
||||||
|
|
||||||
|
static const _steps = [
|
||||||
|
ConsultationStep.startDate,
|
||||||
|
ConsultationStep.paid,
|
||||||
|
ConsultationStep.inProgress,
|
||||||
|
ConsultationStep.finished,
|
||||||
|
];
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
if (!progress.showProgressPlank) {
|
||||||
|
return const SizedBox.shrink();
|
||||||
|
}
|
||||||
|
|
||||||
|
return Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
for (var index = 0; index < _steps.length; index++)
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Container(
|
||||||
|
height: 2,
|
||||||
|
color: index == 0
|
||||||
|
? Colors.transparent
|
||||||
|
: progress.isStepCompleted(_steps[index - 1])
|
||||||
|
? appTheme.greenA700
|
||||||
|
: appTheme.lightGray00,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
_ProgressStepCircle(
|
||||||
|
key: ValueKey('consultation_step_circle_$index'),
|
||||||
|
index: index,
|
||||||
|
isCompleted: progress.isStepCompleted(_steps[index]),
|
||||||
|
),
|
||||||
|
Expanded(
|
||||||
|
child: Container(
|
||||||
|
height: 2,
|
||||||
|
color: index == _steps.length - 1
|
||||||
|
? Colors.transparent
|
||||||
|
: progress.isStepCompleted(_steps[index])
|
||||||
|
? appTheme.greenA700
|
||||||
|
: appTheme.lightGray00,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 6),
|
||||||
|
Text(
|
||||||
|
_stepLabel(S.of(context), _steps[index]),
|
||||||
|
key: ValueKey('consultation_step_label_$index'),
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyles.textFS10FW500.copyWith(
|
||||||
|
color: progress.isStepCompleted(_steps[index])
|
||||||
|
? appTheme.black
|
||||||
|
: appTheme.gray,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _stepLabel(S s, ConsultationStep step) {
|
||||||
|
switch (step) {
|
||||||
|
case ConsultationStep.startDate:
|
||||||
|
return s.startDateHasBeenSet;
|
||||||
|
case ConsultationStep.paid:
|
||||||
|
return s.order_paid;
|
||||||
|
case ConsultationStep.inProgress:
|
||||||
|
return s.order_in_progress;
|
||||||
|
case ConsultationStep.finished:
|
||||||
|
return s.done;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ProgressStepCircle extends StatelessWidget {
|
||||||
|
const _ProgressStepCircle({
|
||||||
|
super.key,
|
||||||
|
required this.index,
|
||||||
|
required this.isCompleted,
|
||||||
|
});
|
||||||
|
|
||||||
|
final int index;
|
||||||
|
final bool isCompleted;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Container(
|
||||||
|
width: 24,
|
||||||
|
height: 24,
|
||||||
|
alignment: Alignment.center,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
shape: BoxShape.circle,
|
||||||
|
color: isCompleted ? appTheme.greenA700 : appTheme.lightGray00,
|
||||||
|
),
|
||||||
|
child: isCompleted
|
||||||
|
? Icon(Icons.check, size: 14, color: appTheme.whiteA700)
|
||||||
|
: Text(
|
||||||
|
'${index + 1}',
|
||||||
|
style: TextStyles.textFS10FW500.copyWith(color: appTheme.gray),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||||
|
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||||
|
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
|
||||||
|
import 'package:eatvio_app/generated/l10n.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
class PersonalDietStatusChip extends StatelessWidget {
|
||||||
|
const PersonalDietStatusChip({super.key, required this.progress});
|
||||||
|
|
||||||
|
final ConsultationProgress progress;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
if (!progress.hasChip) {
|
||||||
|
return const SizedBox.shrink();
|
||||||
|
}
|
||||||
|
|
||||||
|
final s = S.of(context);
|
||||||
|
final (label, background, foreground) = _chipStyle(s);
|
||||||
|
|
||||||
|
return Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: Container(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: background,
|
||||||
|
borderRadius: BorderRadius.circular(100),
|
||||||
|
),
|
||||||
|
child: Text(
|
||||||
|
label,
|
||||||
|
style: TextStyles.textXSSemibold.copyWith(color: foreground),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
(String, Color, Color) _chipStyle(S s) {
|
||||||
|
if (progress.isCanceled) {
|
||||||
|
return (s.orderCanceled, appTheme.lightRed, appTheme.red);
|
||||||
|
}
|
||||||
|
if (progress.isPaymentFailed) {
|
||||||
|
return (s.payment_failed, appTheme.lightRed, appTheme.red);
|
||||||
|
}
|
||||||
|
if (progress.dietStatus == PersonalDietStatus.proposed) {
|
||||||
|
final dietName = progress.personalDietName;
|
||||||
|
final label = dietName == null || dietName.isEmpty
|
||||||
|
? s.personal_diet_proposed
|
||||||
|
: s.personal_diet_proposed_named(dietName);
|
||||||
|
return (
|
||||||
|
label,
|
||||||
|
appTheme.transparentGreen,
|
||||||
|
appTheme.greenA700,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
s.personal_diet_not_proposed,
|
||||||
|
appTheme.gray100,
|
||||||
|
appTheme.gray,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
|
||||||
|
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||||
|
|
||||||
|
ConsultationProgress mapConsultationProgress({
|
||||||
|
required ChosenPlanStateEnum state,
|
||||||
|
required bool hasPersonalDiet,
|
||||||
|
String? personalDietName,
|
||||||
|
}) {
|
||||||
|
return ConsultationProgress(
|
||||||
|
completedSteps: _completedSteps(state),
|
||||||
|
showProgressPlank: _showProgressPlank(state),
|
||||||
|
dietStatus: _dietStatus(state, hasPersonalDiet),
|
||||||
|
phase: _phase(state),
|
||||||
|
personalDietName: personalDietName,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Set<ConsultationStep> _completedSteps(ChosenPlanStateEnum state) {
|
||||||
|
switch (state) {
|
||||||
|
case ChosenPlanStateEnum.stateInited:
|
||||||
|
case ChosenPlanStateEnum.stateConfirmedByConsultant:
|
||||||
|
case ChosenPlanStateEnum.stateInCoordination:
|
||||||
|
case ChosenPlanStateEnum.stateCanceledByTheInitiator:
|
||||||
|
return const {};
|
||||||
|
case ChosenPlanStateEnum.stateStartDateHasBeenSet:
|
||||||
|
case ChosenPlanStateEnum.statePendingPayment:
|
||||||
|
case ChosenPlanStateEnum.statePaymentFailed:
|
||||||
|
return const {ConsultationStep.startDate};
|
||||||
|
case ChosenPlanStateEnum.statePaid:
|
||||||
|
case ChosenPlanStateEnum.personalDietSet:
|
||||||
|
return const {ConsultationStep.startDate, ConsultationStep.paid};
|
||||||
|
case ChosenPlanStateEnum.stateStarted:
|
||||||
|
case ChosenPlanStateEnum.stateInProgress:
|
||||||
|
case ChosenPlanStateEnum.stateLastDayStarted:
|
||||||
|
case ChosenPlanStateEnum.stateLastDayFinished:
|
||||||
|
case ChosenPlanStateEnum.stateComplained:
|
||||||
|
return const {
|
||||||
|
ConsultationStep.startDate,
|
||||||
|
ConsultationStep.paid,
|
||||||
|
ConsultationStep.inProgress,
|
||||||
|
};
|
||||||
|
case ChosenPlanStateEnum.stateDone:
|
||||||
|
case ChosenPlanStateEnum.stateChargeWasCollected:
|
||||||
|
return const {
|
||||||
|
ConsultationStep.startDate,
|
||||||
|
ConsultationStep.paid,
|
||||||
|
ConsultationStep.inProgress,
|
||||||
|
ConsultationStep.finished,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _showProgressPlank(ChosenPlanStateEnum state) {
|
||||||
|
switch (state) {
|
||||||
|
case ChosenPlanStateEnum.stateInited:
|
||||||
|
case ChosenPlanStateEnum.stateConfirmedByConsultant:
|
||||||
|
case ChosenPlanStateEnum.stateChargeWasCollected:
|
||||||
|
case ChosenPlanStateEnum.stateCanceledByTheInitiator:
|
||||||
|
case ChosenPlanStateEnum.statePaymentFailed:
|
||||||
|
return false;
|
||||||
|
case ChosenPlanStateEnum.stateInCoordination:
|
||||||
|
case ChosenPlanStateEnum.stateStartDateHasBeenSet:
|
||||||
|
case ChosenPlanStateEnum.statePendingPayment:
|
||||||
|
case ChosenPlanStateEnum.statePaid:
|
||||||
|
case ChosenPlanStateEnum.personalDietSet:
|
||||||
|
case ChosenPlanStateEnum.stateStarted:
|
||||||
|
case ChosenPlanStateEnum.stateInProgress:
|
||||||
|
case ChosenPlanStateEnum.stateLastDayStarted:
|
||||||
|
case ChosenPlanStateEnum.stateLastDayFinished:
|
||||||
|
case ChosenPlanStateEnum.stateComplained:
|
||||||
|
case ChosenPlanStateEnum.stateDone:
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
PersonalDietStatus _dietStatus(
|
||||||
|
ChosenPlanStateEnum state,
|
||||||
|
bool hasPersonalDiet,
|
||||||
|
) {
|
||||||
|
if (!hasPersonalDiet) {
|
||||||
|
return PersonalDietStatus.notRequired;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (state) {
|
||||||
|
case ChosenPlanStateEnum.personalDietSet:
|
||||||
|
case ChosenPlanStateEnum.stateStarted:
|
||||||
|
case ChosenPlanStateEnum.stateInProgress:
|
||||||
|
case ChosenPlanStateEnum.stateLastDayStarted:
|
||||||
|
case ChosenPlanStateEnum.stateLastDayFinished:
|
||||||
|
case ChosenPlanStateEnum.stateComplained:
|
||||||
|
case ChosenPlanStateEnum.stateDone:
|
||||||
|
case ChosenPlanStateEnum.stateChargeWasCollected:
|
||||||
|
return PersonalDietStatus.proposed;
|
||||||
|
case ChosenPlanStateEnum.stateInited:
|
||||||
|
case ChosenPlanStateEnum.stateInCoordination:
|
||||||
|
case ChosenPlanStateEnum.stateConfirmedByConsultant:
|
||||||
|
case ChosenPlanStateEnum.stateStartDateHasBeenSet:
|
||||||
|
case ChosenPlanStateEnum.statePendingPayment:
|
||||||
|
case ChosenPlanStateEnum.statePaid:
|
||||||
|
return PersonalDietStatus.notProposed;
|
||||||
|
case ChosenPlanStateEnum.stateCanceledByTheInitiator:
|
||||||
|
case ChosenPlanStateEnum.statePaymentFailed:
|
||||||
|
return PersonalDietStatus.notRequired;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ConsultationPhase _phase(ChosenPlanStateEnum state) {
|
||||||
|
switch (state) {
|
||||||
|
case ChosenPlanStateEnum.stateCanceledByTheInitiator:
|
||||||
|
return ConsultationPhase.canceled;
|
||||||
|
case ChosenPlanStateEnum.statePaymentFailed:
|
||||||
|
return ConsultationPhase.paymentFailed;
|
||||||
|
default:
|
||||||
|
return ConsultationPhase.active;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,8 +18,13 @@ enum PortionState {
|
|||||||
@JsonValue('eaten_edited')
|
@JsonValue('eaten_edited')
|
||||||
eatenEdited,
|
eatenEdited,
|
||||||
commented,
|
commented,
|
||||||
|
@JsonValue('commented_from_diet')
|
||||||
|
commentedFromDiet,
|
||||||
@JsonValue('reviewed_by_user')
|
@JsonValue('reviewed_by_user')
|
||||||
reviewedByUser,
|
reviewedByUser,
|
||||||
|
@JsonValue('reviewed_from_diet')
|
||||||
|
reviewedFromDiet,
|
||||||
|
unknown,
|
||||||
}
|
}
|
||||||
|
|
||||||
@freezed
|
@freezed
|
||||||
@@ -138,7 +143,7 @@ abstract class PortionModel with _$PortionModel {
|
|||||||
@JsonKey(name: "quantity") required int quantity,
|
@JsonKey(name: "quantity") required int quantity,
|
||||||
@JsonKey(name: "portion") required String portion,
|
@JsonKey(name: "portion") required String portion,
|
||||||
@JsonKey(name: "from_diet") required bool fromDiet,
|
@JsonKey(name: "from_diet") required bool fromDiet,
|
||||||
@JsonKey(name: "state") required PortionState portionState,
|
@JsonKey(name: "state", unknownEnumValue: PortionState.unknown) required PortionState portionState,
|
||||||
}) = _PortionModel;
|
}) = _PortionModel;
|
||||||
|
|
||||||
factory PortionModel.fromJson(Map<String, dynamic> json) => _$PortionModelFromJson(json);
|
factory PortionModel.fromJson(Map<String, dynamic> json) => _$PortionModelFromJson(json);
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart';
|
|||||||
import 'package:eatvio_app/core/widgets/custom_divider.dart';
|
import 'package:eatvio_app/core/widgets/custom_divider.dart';
|
||||||
import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart';
|
import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart';
|
||||||
import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart';
|
import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart';
|
||||||
import 'package:eatvio_app/generated/l10n.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
import 'package:go_router/go_router.dart';
|
import 'package:go_router/go_router.dart';
|
||||||
@@ -19,9 +18,7 @@ class ChosenDietWidget extends StatelessWidget {
|
|||||||
if (state is DiaryStateLoaded) {
|
if (state is DiaryStateLoaded) {
|
||||||
if (state.diary.typeOfDiary.hasChosenDiet) {
|
if (state.diary.typeOfDiary.hasChosenDiet) {
|
||||||
return ChosenDietWidgetContent(
|
return ChosenDietWidgetContent(
|
||||||
currentDietDay: state.diary.dayOfChosenDiet ?? 0,
|
|
||||||
dietName: state.diary.diet?.name ?? '',
|
dietName: state.diary.diet?.name ?? '',
|
||||||
dietDuration: state.diary.diet?.duration ?? 0,
|
|
||||||
dietId: state.diary.diet?.id ?? 0,
|
dietId: state.diary.diet?.id ?? 0,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -33,9 +30,7 @@ class ChosenDietWidget extends StatelessWidget {
|
|||||||
const CustomDivider(),
|
const CustomDivider(),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
ChosenDietWidgetContent(
|
ChosenDietWidgetContent(
|
||||||
currentDietDay: state.diary.dayOfChosenDiet ?? 0,
|
|
||||||
dietName: state.diary.diet?.name ?? '',
|
dietName: state.diary.diet?.name ?? '',
|
||||||
dietDuration: state.diary.diet?.duration ?? 0,
|
|
||||||
dietId: state.diary.diet?.id ?? 0,
|
dietId: state.diary.diet?.id ?? 0,
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -50,15 +45,11 @@ class ChosenDietWidget extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class ChosenDietWidgetContent extends StatelessWidget {
|
class ChosenDietWidgetContent extends StatelessWidget {
|
||||||
const ChosenDietWidgetContent({super.key, required this.currentDietDay, required this.dietName, required this.dietDuration, required this.dietId});
|
const ChosenDietWidgetContent({super.key, required this.dietName, required this.dietId});
|
||||||
final int currentDietDay;
|
|
||||||
final String dietName;
|
final String dietName;
|
||||||
final int dietDuration;
|
|
||||||
final int dietId;
|
final int dietId;
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final size = MediaQuery.sizeOf(context);
|
|
||||||
final s = S.of(context);
|
|
||||||
return GestureDetector(
|
return GestureDetector(
|
||||||
onTap: () {
|
onTap: () {
|
||||||
GoRouter.of(context).push(RouteConstants.aboutDietScreen, extra: {'id': dietId, 'navigateToComments': false});
|
GoRouter.of(context).push(RouteConstants.aboutDietScreen, extra: {'id': dietId, 'navigateToComments': false});
|
||||||
@@ -67,19 +58,12 @@ class ChosenDietWidgetContent extends StatelessWidget {
|
|||||||
children: [
|
children: [
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
SizedBox(
|
Expanded(
|
||||||
width: size.width * 0.4,
|
|
||||||
child: Text(
|
child: Text(
|
||||||
dietName,
|
dietName,
|
||||||
style: TextStyles.textLMedium.copyWith(color: appTheme.black, decoration: TextDecoration.underline),
|
style: TextStyles.textLMedium.copyWith(color: appTheme.black, decoration: TextDecoration.underline),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const Spacer(),
|
|
||||||
Container(
|
|
||||||
decoration: BoxDecoration(color: appTheme.dividerColor, borderRadius: BorderRadius.circular(12)),
|
|
||||||
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 12),
|
|
||||||
child: Text('${s.day} $currentDietDay из $dietDuration', style: TextStyles.textMSemibold.copyWith(color: appTheme.gray)),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
|
|||||||
@@ -12,9 +12,19 @@ class FeedCubit extends Cubit<FeedState> {
|
|||||||
bool _hasMore = true;
|
bool _hasMore = true;
|
||||||
bool isLoading = false;
|
bool isLoading = false;
|
||||||
String? _query;
|
String? _query;
|
||||||
|
int _requestId = 0;
|
||||||
|
|
||||||
FeedCubit({required this.feedRepository}) : super(const FeedState.loading());
|
FeedCubit({required this.feedRepository}) : super(const FeedState.loading());
|
||||||
|
|
||||||
|
void reset() {
|
||||||
|
_requestId++;
|
||||||
|
_nextCursor = null;
|
||||||
|
_hasMore = true;
|
||||||
|
isLoading = false;
|
||||||
|
_query = null;
|
||||||
|
if (!isClosed) emit(const FeedState.loading());
|
||||||
|
}
|
||||||
|
|
||||||
void updateFeedBlogPostList(FeedBlogPostModel? feedBlogPostModel, bool wasLikedByMe) {
|
void updateFeedBlogPostList(FeedBlogPostModel? feedBlogPostModel, bool wasLikedByMe) {
|
||||||
if (feedBlogPostModel == null || isClosed || state is! FeedStateLoaded) return;
|
if (feedBlogPostModel == null || isClosed || state is! FeedStateLoaded) return;
|
||||||
final List<FeedBlogPostModel> feedBlogPostList = [...(state as FeedStateLoaded).feedBlogPostList];
|
final List<FeedBlogPostModel> feedBlogPostList = [...(state as FeedStateLoaded).feedBlogPostList];
|
||||||
@@ -39,17 +49,18 @@ class FeedCubit extends Cubit<FeedState> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> loadFeedBlogPostList({String? query, int? currentUserId}) async {
|
Future<void> loadFeedBlogPostList({String? query, int? currentUserId}) async {
|
||||||
|
final requestId = ++_requestId;
|
||||||
try {
|
try {
|
||||||
_query = query;
|
_query = query;
|
||||||
_nextCursor = null;
|
_nextCursor = null;
|
||||||
_hasMore = true;
|
_hasMore = true;
|
||||||
final feed = await feedRepository.getFeed(search: query, currentUserId: currentUserId);
|
final feed = await feedRepository.getFeed(search: query, currentUserId: currentUserId);
|
||||||
|
if (isClosed || requestId != _requestId) return;
|
||||||
_nextCursor = feed.nextCursor;
|
_nextCursor = feed.nextCursor;
|
||||||
_hasMore = _nextCursor != null;
|
_hasMore = _nextCursor != null;
|
||||||
if (!isClosed) {
|
emit(FeedState.loaded(feedBlogPostList: feed.posts, isLoading: false));
|
||||||
emit(FeedState.loaded(feedBlogPostList: feed.posts, isLoading: false));
|
|
||||||
}
|
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
|
if (isClosed || requestId != _requestId) return;
|
||||||
await reportFrom(e, st, this);
|
await reportFrom(e, st, this);
|
||||||
if (!isClosed) {
|
if (!isClosed) {
|
||||||
emit(FeedState.error(errorMessage: e.toString()));
|
emit(FeedState.error(errorMessage: e.toString()));
|
||||||
@@ -62,14 +73,16 @@ class FeedCubit extends Cubit<FeedState> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
final requestId = _requestId;
|
||||||
isLoading = true;
|
isLoading = true;
|
||||||
emit((state as FeedStateLoaded).copyWith(isLoading: true));
|
emit((state as FeedStateLoaded).copyWith(isLoading: true));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
final feed = await feedRepository.getFeed(search: _query, cursor: _nextCursor, currentUserId: currentUserId);
|
final feed = await feedRepository.getFeed(search: _query, cursor: _nextCursor, currentUserId: currentUserId);
|
||||||
|
if (isClosed || requestId != _requestId) return;
|
||||||
_nextCursor = feed.nextCursor;
|
_nextCursor = feed.nextCursor;
|
||||||
_hasMore = _nextCursor != null;
|
_hasMore = _nextCursor != null;
|
||||||
if (!isClosed && state is FeedStateLoaded) {
|
if (state is FeedStateLoaded) {
|
||||||
emit(
|
emit(
|
||||||
FeedState.loaded(
|
FeedState.loaded(
|
||||||
feedBlogPostList: [...(state as FeedStateLoaded).feedBlogPostList, ...feed.posts],
|
feedBlogPostList: [...(state as FeedStateLoaded).feedBlogPostList, ...feed.posts],
|
||||||
@@ -78,14 +91,15 @@ class FeedCubit extends Cubit<FeedState> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
|
if (isClosed || requestId != _requestId) return;
|
||||||
await reportFrom(e, st, this);
|
await reportFrom(e, st, this);
|
||||||
if (!isClosed && state is FeedStateLoaded) {
|
if (state is FeedStateLoaded) {
|
||||||
emit((state as FeedStateLoaded).copyWith(isLoading: false));
|
emit((state as FeedStateLoaded).copyWith(isLoading: false));
|
||||||
} else if (!isClosed) {
|
} else {
|
||||||
emit(FeedState.error(errorMessage: e.toString()));
|
emit(FeedState.error(errorMessage: e.toString()));
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
isLoading = false;
|
if (requestId == _requestId) isLoading = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import 'dart:developer';
|
import 'dart:developer';
|
||||||
|
|
||||||
|
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||||
import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_state.dart';
|
import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_state.dart';
|
||||||
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
|
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
|
||||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
@@ -7,7 +8,11 @@ import 'package:eatvio_app/core/error_reporting/report_from.dart';
|
|||||||
|
|
||||||
class MenuCubit extends Cubit<MenuState> {
|
class MenuCubit extends Cubit<MenuState> {
|
||||||
final ProfileRepository profileRepository;
|
final ProfileRepository profileRepository;
|
||||||
MenuCubit(this.profileRepository) : super(const MenuState.initial());
|
final SessionLifecycleService sessionLifecycleService;
|
||||||
|
MenuCubit(this.profileRepository, this.sessionLifecycleService)
|
||||||
|
: super(const MenuState.initial());
|
||||||
|
|
||||||
|
Future<void> logout() => sessionLifecycleService.logout();
|
||||||
|
|
||||||
Future<void> getMyProfile() async {
|
Future<void> getMyProfile() async {
|
||||||
emit(const MenuState.loading());
|
emit(const MenuState.loading());
|
||||||
@@ -23,7 +28,10 @@ class MenuCubit extends Cubit<MenuState> {
|
|||||||
|
|
||||||
Future<String?> makePassKey() async {
|
Future<String?> makePassKey() async {
|
||||||
try {
|
try {
|
||||||
final passKey = await profileRepository.getPassKey(routeName: 'product_nutritional_value.index', routeParams: {});
|
final passKey = await profileRepository.getPassKey(
|
||||||
|
routeName: 'product_nutritional_value.index',
|
||||||
|
routeParams: {},
|
||||||
|
);
|
||||||
return passKey;
|
return passKey;
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
await reportFrom(e, st, this);
|
await reportFrom(e, st, this);
|
||||||
|
|||||||
@@ -1,26 +1,20 @@
|
|||||||
import 'package:dio/dio.dart';
|
|
||||||
import 'package:eatvio_app/core/app_config.dart';
|
|
||||||
import 'package:eatvio_app/core/error_reporting/error_reporter.dart';
|
|
||||||
import 'package:eatvio_app/core/const.dart';
|
import 'package:eatvio_app/core/const.dart';
|
||||||
import 'package:eatvio_app/core/firebase_api.dart';
|
|
||||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||||
import 'package:eatvio_app/core/token_storage.dart';
|
|
||||||
import 'package:eatvio_app/core/utils/image_constant.dart';
|
import 'package:eatvio_app/core/utils/image_constant.dart';
|
||||||
import 'package:eatvio_app/core/utils/date_time_utils.dart';
|
import 'package:eatvio_app/core/utils/date_time_utils.dart';
|
||||||
import 'package:eatvio_app/core/widgets/data_error_widget.dart';
|
import 'package:eatvio_app/core/widgets/data_error_widget.dart';
|
||||||
import 'package:eatvio_app/core/widgets/loader.dart';
|
import 'package:eatvio_app/core/widgets/loader.dart';
|
||||||
import 'package:eatvio_app/core/locator_service.dart';
|
import 'package:eatvio_app/core/locator_service.dart';
|
||||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
|
||||||
import 'package:eatvio_app/features/consultant_rating/presentation/consultant_rating_screen.dart';
|
import 'package:eatvio_app/features/consultant_rating/presentation/consultant_rating_screen.dart';
|
||||||
import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/consultant_finances_screen.dart';
|
import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/consultant_finances_screen.dart';
|
||||||
import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/user_purchases_screen.dart';
|
import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/user_purchases_screen.dart';
|
||||||
import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_cubit.dart';
|
import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_cubit.dart';
|
||||||
import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart';
|
|
||||||
import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_state.dart';
|
import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_state.dart';
|
||||||
import 'package:eatvio_app/features/my_diets/presentation/my_diets_screen.dart';
|
import 'package:eatvio_app/features/my_diets/presentation/my_diets_screen.dart';
|
||||||
import 'package:eatvio_app/features/my_plans/presentation/my_plans_screen.dart';
|
import 'package:eatvio_app/features/my_plans/presentation/my_plans_screen.dart';
|
||||||
import 'package:eatvio_app/features/recipe/presentation/pages/my_recipes_screen.dart';
|
import 'package:eatvio_app/features/recipe/presentation/pages/my_recipes_screen.dart';
|
||||||
|
import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart';
|
||||||
import 'package:flutter/cupertino.dart';
|
import 'package:flutter/cupertino.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
@@ -56,6 +50,12 @@ class MenuScreen extends StatelessWidget {
|
|||||||
if (profileModel.roles.contains('consultant')) _divider(context),
|
if (profileModel.roles.contains('consultant')) _divider(context),
|
||||||
if (profileModel.roles.contains('consultant'))
|
if (profileModel.roles.contains('consultant'))
|
||||||
_tile(leading: ImageConstant.icnPlans, title: 'Мои планы', onTap: () => GoRouter.of(context).push(MyPlansScreen.path)),
|
_tile(leading: ImageConstant.icnPlans, title: 'Мои планы', onTap: () => GoRouter.of(context).push(MyPlansScreen.path)),
|
||||||
|
_divider(context),
|
||||||
|
_tile(
|
||||||
|
leading: ImageConstant.icnConsultation,
|
||||||
|
title: 'Мои консультации',
|
||||||
|
onTap: () => GoRouter.of(context).push(VideoCallRecordingsScreen.path),
|
||||||
|
),
|
||||||
if (!hidePlans) ...[
|
if (!hidePlans) ...[
|
||||||
_divider(context),
|
_divider(context),
|
||||||
_tile(
|
_tile(
|
||||||
@@ -155,6 +155,7 @@ class MenuScreen extends StatelessWidget {
|
|||||||
|
|
||||||
Future<Null> Function() _onTapLogout(BuildContext context) {
|
Future<Null> Function() _onTapLogout(BuildContext context) {
|
||||||
return () async {
|
return () async {
|
||||||
|
final menuCubit = context.read<MenuCubit>();
|
||||||
showDialog(
|
showDialog(
|
||||||
context: context,
|
context: context,
|
||||||
builder: (context) => CupertinoAlertDialog(
|
builder: (context) => CupertinoAlertDialog(
|
||||||
@@ -162,24 +163,8 @@ class MenuScreen extends StatelessWidget {
|
|||||||
actions: [
|
actions: [
|
||||||
CupertinoDialogAction(
|
CupertinoDialogAction(
|
||||||
onPressed: () async {
|
onPressed: () async {
|
||||||
try {
|
Navigator.of(context).pop();
|
||||||
await sl<Dio>().post('${sl<AppConfig>().baseUrl}/api/profile/logout');
|
await menuCubit.logout();
|
||||||
} catch (e, s) {
|
|
||||||
await sl<ErrorReporter>().report(e, s, origin: 'MenuScreen');
|
|
||||||
} finally {
|
|
||||||
try {
|
|
||||||
// Needs Authorization header → must run before removing token.
|
|
||||||
await sl<FirebaseApi>().unregisterPushTokens();
|
|
||||||
} catch (e, s) {
|
|
||||||
await sl<ErrorReporter>().report(e, s, origin: 'MenuScreen');
|
|
||||||
}
|
|
||||||
await sl<VideoCallSessionCubit>().endCall();
|
|
||||||
await sl<WsManager>().clear();
|
|
||||||
await TokenStorage.removeTokenInStorage();
|
|
||||||
if (context.mounted) {
|
|
||||||
GoRouter.of(context).go('/auth-screen', extra: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
isDestructiveAction: true,
|
isDestructiveAction: true,
|
||||||
child: const Text("Выйти"),
|
child: const Text("Выйти"),
|
||||||
|
|||||||
@@ -136,6 +136,11 @@ class MyDietsCubit extends Cubit<MyDietsState> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void selectInitialTab(int index) {
|
||||||
|
if (index < 0 || index > 2) return;
|
||||||
|
emit(state.copyWith(selectedStateIndex: index));
|
||||||
|
}
|
||||||
|
|
||||||
void changeSelectedStateIndex(int index) {
|
void changeSelectedStateIndex(int index) {
|
||||||
emit(state.copyWith(selectedStateIndex: index));
|
emit(state.copyWith(selectedStateIndex: index));
|
||||||
if (state.activeDiets.isEmpty) {
|
if (state.activeDiets.isEmpty) {
|
||||||
|
|||||||
@@ -19,12 +19,19 @@ import 'package:flutter_bloc/flutter_bloc.dart';
|
|||||||
import 'package:go_router/go_router.dart';
|
import 'package:go_router/go_router.dart';
|
||||||
|
|
||||||
class MyDietsScreen extends StatelessWidget {
|
class MyDietsScreen extends StatelessWidget {
|
||||||
const MyDietsScreen({super.key});
|
const MyDietsScreen({super.key, this.initialTabIndex = 0});
|
||||||
static const name = 'myDietsScreen';
|
static const name = 'myDietsScreen';
|
||||||
static const path = '/my-diets-screen';
|
static const path = '/my-diets-screen';
|
||||||
|
final int initialTabIndex;
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return BlocProvider(create: (context) => sl<MyDietsCubit>()..loadAllDiets(), child: MyDietsScreenContent());
|
return BlocProvider(
|
||||||
|
create: (context) =>
|
||||||
|
sl<MyDietsCubit>()
|
||||||
|
..selectInitialTab(initialTabIndex)
|
||||||
|
..loadAllDiets(),
|
||||||
|
child: MyDietsScreenContent(),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2174,6 +2174,56 @@ class PersonalDietIsDefinedToCustomerNotification implements BaseNotificationMod
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class PersonalDietIsDefinedToAuthorNotification implements BaseNotificationModel {
|
||||||
|
@override
|
||||||
|
final NotificationType type;
|
||||||
|
@override
|
||||||
|
final bool isRead;
|
||||||
|
@override
|
||||||
|
final DateTime createdAt;
|
||||||
|
final int chosenPlanId;
|
||||||
|
final int dietId;
|
||||||
|
final String planName;
|
||||||
|
final String userName;
|
||||||
|
final String consultantName;
|
||||||
|
final String dietName;
|
||||||
|
final String role;
|
||||||
|
final String peerSlug;
|
||||||
|
final String peerImagePath;
|
||||||
|
|
||||||
|
PersonalDietIsDefinedToAuthorNotification({
|
||||||
|
required this.type,
|
||||||
|
required this.isRead,
|
||||||
|
required this.createdAt,
|
||||||
|
required this.chosenPlanId,
|
||||||
|
required this.dietId,
|
||||||
|
required this.planName,
|
||||||
|
required this.userName,
|
||||||
|
required this.consultantName,
|
||||||
|
required this.dietName,
|
||||||
|
required this.role,
|
||||||
|
required this.peerSlug,
|
||||||
|
required this.peerImagePath,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory PersonalDietIsDefinedToAuthorNotification.fromJson(Map<String, dynamic> json, NotificationType type, {bool? isRead, String? createdAt}) {
|
||||||
|
return PersonalDietIsDefinedToAuthorNotification(
|
||||||
|
type: type,
|
||||||
|
isRead: isRead ?? false,
|
||||||
|
createdAt: parseDate(createdAt ?? json['created_at'] ?? DateTime.now().toIso8601String()),
|
||||||
|
chosenPlanId: json['chosen_plan_id'] ?? 0,
|
||||||
|
dietId: json['diet_id'] ?? 0,
|
||||||
|
planName: json['plan_name'] ?? '',
|
||||||
|
userName: json['user_name'] ?? '',
|
||||||
|
consultantName: json['consultant_name'] ?? '',
|
||||||
|
dietName: json['diet_name'] ?? '',
|
||||||
|
role: json['role']?.toString() ?? '',
|
||||||
|
peerSlug: json['peer_slug'] ?? '',
|
||||||
|
peerImagePath: json['peer_image_path'] ?? '',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// New Model Classes for Comprehensive Support
|
// New Model Classes for Comprehensive Support
|
||||||
|
|
||||||
class ConsultantEducationUpdatedNotification implements BaseNotificationModel {
|
class ConsultantEducationUpdatedNotification implements BaseNotificationModel {
|
||||||
@@ -2480,6 +2530,7 @@ enum NotificationType {
|
|||||||
chosenPlanFinishedToConsultant,
|
chosenPlanFinishedToConsultant,
|
||||||
stayOnTrackToCustomer,
|
stayOnTrackToCustomer,
|
||||||
personalDietIsDefinedToCustomer,
|
personalDietIsDefinedToCustomer,
|
||||||
|
personalDietIsDefinedToAuthor,
|
||||||
|
|
||||||
// Comments
|
// Comments
|
||||||
entityCommented,
|
entityCommented,
|
||||||
@@ -2602,6 +2653,7 @@ enum NotificationType {
|
|||||||
'stay-on-track-to-customer' => NotificationType.stayOnTrackToCustomer,
|
'stay-on-track-to-customer' => NotificationType.stayOnTrackToCustomer,
|
||||||
'diary-reminder-for-users' => NotificationType.diaryReminderForUsers,
|
'diary-reminder-for-users' => NotificationType.diaryReminderForUsers,
|
||||||
'personal-diet-is-defined-to-customer' => NotificationType.personalDietIsDefinedToCustomer,
|
'personal-diet-is-defined-to-customer' => NotificationType.personalDietIsDefinedToCustomer,
|
||||||
|
'personal-diet-is-defined-to-author' => NotificationType.personalDietIsDefinedToAuthor,
|
||||||
|
|
||||||
// New additions
|
// New additions
|
||||||
'consultant-education-updated' => NotificationType.consultantEducationUpdated,
|
'consultant-education-updated' => NotificationType.consultantEducationUpdated,
|
||||||
|
|||||||
@@ -16,6 +16,11 @@ class NotificationsCubit extends Cubit<NotificationsState> {
|
|||||||
StreamSubscription? _newNotificationsSubscription;
|
StreamSubscription? _newNotificationsSubscription;
|
||||||
NotificationsCubit({required this.wsManager, required this.notificationsRepository}) : super(const NotificationsState.empty());
|
NotificationsCubit({required this.wsManager, required this.notificationsRepository}) : super(const NotificationsState.empty());
|
||||||
|
|
||||||
|
void reset() {
|
||||||
|
_notifications.clear();
|
||||||
|
if (!isClosed) emit(const NotificationsState.empty());
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> connectToWebSocket() async {
|
Future<void> connectToWebSocket() async {
|
||||||
try {
|
try {
|
||||||
await _newNotificationsSubscription?.cancel();
|
await _newNotificationsSubscription?.cancel();
|
||||||
@@ -272,6 +277,12 @@ class NotificationsCubit extends Cubit<NotificationsState> {
|
|||||||
isRead: isRead,
|
isRead: isRead,
|
||||||
createdAt: createdAt,
|
createdAt: createdAt,
|
||||||
),
|
),
|
||||||
|
NotificationType.personalDietIsDefinedToAuthor => PersonalDietIsDefinedToAuthorNotification.fromJson(
|
||||||
|
notificationJson,
|
||||||
|
type,
|
||||||
|
isRead: isRead,
|
||||||
|
createdAt: createdAt,
|
||||||
|
),
|
||||||
NotificationType.consultantEducationUpdated => ConsultantEducationUpdatedNotification.fromJson(
|
NotificationType.consultantEducationUpdated => ConsultantEducationUpdatedNotification.fromJson(
|
||||||
notificationJson,
|
notificationJson,
|
||||||
type,
|
type,
|
||||||
|
|||||||
@@ -122,6 +122,9 @@ class NotificationWidget extends StatelessWidget {
|
|||||||
PersonalDietIsDefinedToCustomerNotification() => _PersonalDietIsDefinedToCustomerWidget(
|
PersonalDietIsDefinedToCustomerNotification() => _PersonalDietIsDefinedToCustomerWidget(
|
||||||
notification: notification as PersonalDietIsDefinedToCustomerNotification,
|
notification: notification as PersonalDietIsDefinedToCustomerNotification,
|
||||||
),
|
),
|
||||||
|
PersonalDietIsDefinedToAuthorNotification() => _PersonalDietIsDefinedToAuthorWidget(
|
||||||
|
notification: notification as PersonalDietIsDefinedToAuthorNotification,
|
||||||
|
),
|
||||||
// New Widgets
|
// New Widgets
|
||||||
ConsultantEducationUpdatedNotification() => _ConsultantEducationUpdatedWidget(notification: notification as ConsultantEducationUpdatedNotification),
|
ConsultantEducationUpdatedNotification() => _ConsultantEducationUpdatedWidget(notification: notification as ConsultantEducationUpdatedNotification),
|
||||||
ComplaintRegisteredNotification() => _ComplaintRegisteredWidget(notification: notification as ComplaintRegisteredNotification),
|
ComplaintRegisteredNotification() => _ComplaintRegisteredWidget(notification: notification as ComplaintRegisteredNotification),
|
||||||
@@ -1273,6 +1276,30 @@ class _PersonalDietIsDefinedToCustomerWidget extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class _PersonalDietIsDefinedToAuthorWidget extends StatelessWidget {
|
||||||
|
const _PersonalDietIsDefinedToAuthorWidget({required this.notification});
|
||||||
|
final PersonalDietIsDefinedToAuthorNotification notification;
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final s = S.of(context);
|
||||||
|
final userName = notification.userName.isNotEmpty ? notification.userName : s.default_user_name;
|
||||||
|
final notificationsText = notification.dietName.isEmpty
|
||||||
|
? s.personal_diet_defined_to_author(userName)
|
||||||
|
: s.personal_diet_defined_to_author_named(userName, notification.dietName);
|
||||||
|
|
||||||
|
return _BaseNotificationWidget(
|
||||||
|
isRead: notification.isRead,
|
||||||
|
notificationsText: notificationsText,
|
||||||
|
createdAt: notification.createdAt,
|
||||||
|
onTap: notification.peerSlug.isEmpty
|
||||||
|
? null
|
||||||
|
: () {
|
||||||
|
context.push(RouteConstants.profileScreen, extra: notification.peerSlug);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
class _ConsultantEducationUpdatedWidget extends StatelessWidget {
|
class _ConsultantEducationUpdatedWidget extends StatelessWidget {
|
||||||
const _ConsultantEducationUpdatedWidget({required this.notification});
|
const _ConsultantEducationUpdatedWidget({required this.notification});
|
||||||
final ConsultantEducationUpdatedNotification notification;
|
final ConsultantEducationUpdatedNotification notification;
|
||||||
|
|||||||
@@ -413,6 +413,12 @@ class NotificationsService {
|
|||||||
isRead: readDate != null,
|
isRead: readDate != null,
|
||||||
createdAt: createdAt,
|
createdAt: createdAt,
|
||||||
),
|
),
|
||||||
|
NotificationType.personalDietIsDefinedToAuthor => PersonalDietIsDefinedToAuthorNotification.fromJson(
|
||||||
|
notificationJson['data'],
|
||||||
|
type,
|
||||||
|
isRead: readDate != null,
|
||||||
|
createdAt: createdAt,
|
||||||
|
),
|
||||||
NotificationType.consultantEducationUpdated => ConsultantEducationUpdatedNotification.fromJson(
|
NotificationType.consultantEducationUpdated => ConsultantEducationUpdatedNotification.fromJson(
|
||||||
notificationJson['data'],
|
notificationJson['data'],
|
||||||
type,
|
type,
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import 'package:eatvio_app/features/cancel_plan_bottom_sheet/cancel_plan_bottom_
|
|||||||
import 'package:eatvio_app/core/widgets/custom_outlined_button.dart';
|
import 'package:eatvio_app/core/widgets/custom_outlined_button.dart';
|
||||||
import 'package:eatvio_app/core/widgets/loader.dart';
|
import 'package:eatvio_app/core/widgets/loader.dart';
|
||||||
import 'package:eatvio_app/features/diets/presentation/widgets/author_card.dart';
|
import 'package:eatvio_app/features/diets/presentation/widgets/author_card.dart';
|
||||||
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
|
|
||||||
import 'package:eatvio_app/features/order_info/cubit/order_info_cubit.dart';
|
import 'package:eatvio_app/features/order_info/cubit/order_info_cubit.dart';
|
||||||
import 'package:eatvio_app/features/order_info/cubit/order_info_state.dart';
|
import 'package:eatvio_app/features/order_info/cubit/order_info_state.dart';
|
||||||
import 'package:eatvio_app/features/order_info/presentation/widgets/collect_charge_banner.dart';
|
import 'package:eatvio_app/features/order_info/presentation/widgets/collect_charge_banner.dart';
|
||||||
@@ -106,14 +105,7 @@ class _InfoByOrderScreenContentState extends State<InfoByOrderScreenContent> {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
PacketOptions? chosenOption;
|
final chosenOption = plan.chosenOption;
|
||||||
if (plan.optionType == 'options1') {
|
|
||||||
chosenOption = plan.plan.packet1Options;
|
|
||||||
} else if (plan.optionType == 'options2') {
|
|
||||||
chosenOption = plan.plan.packet2Options;
|
|
||||||
} else {
|
|
||||||
chosenOption = plan.plan.packet3Options;
|
|
||||||
}
|
|
||||||
|
|
||||||
PlanStatusValues planStatus;
|
PlanStatusValues planStatus;
|
||||||
if (widget.successfulPayment == true) {
|
if (widget.successfulPayment == true) {
|
||||||
@@ -164,7 +156,7 @@ class _InfoByOrderScreenContentState extends State<InfoByOrderScreenContent> {
|
|||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
PlanState(state: plan.chosenPlanState, hasPersonalDiet: chosenOption?.hasPersonalDiet ?? false),
|
PlanState(state: plan.chosenPlanState, hasPersonalDiet: chosenOption?.hasPersonalDiet ?? false),
|
||||||
const SizedBox(height: 20),
|
const SizedBox(height: 20),
|
||||||
if (widget.successfulPayment == null)
|
if (widget.successfulPayment == null && plan.chosenPlanState.canShowCancelAction)
|
||||||
CustomOutlinedButton(
|
CustomOutlinedButton(
|
||||||
text: s.cancelConsultation,
|
text: s.cancelConsultation,
|
||||||
height: 52,
|
height: 52,
|
||||||
@@ -173,7 +165,7 @@ class _InfoByOrderScreenContentState extends State<InfoByOrderScreenContent> {
|
|||||||
onPressed: () async {
|
onPressed: () async {
|
||||||
showModalBottomSheet(
|
showModalBottomSheet(
|
||||||
context: context,
|
context: context,
|
||||||
builder: (context) => CancelPlanBottomSheet(enableForm: plan.chosenPlanState.isStateAfterPaidState(), planId: plan.id),
|
builder: (context) => CancelPlanBottomSheet(enableForm: plan.chosenPlanState.isCancelAfterPaidState, planId: plan.id),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import 'package:flutter/material.dart';
|
|||||||
Future<void> showConsultationPaymentFlow(
|
Future<void> showConsultationPaymentFlow(
|
||||||
BuildContext context, {
|
BuildContext context, {
|
||||||
required int planId,
|
required int planId,
|
||||||
|
double? amount,
|
||||||
Future<bool?> Function(BuildContext)? showGate,
|
Future<bool?> Function(BuildContext)? showGate,
|
||||||
Future<PromoCodeResult?> Function(
|
Future<PromoCodeResult?> Function(
|
||||||
BuildContext, {
|
BuildContext, {
|
||||||
@@ -21,7 +22,7 @@ Future<void> showConsultationPaymentFlow(
|
|||||||
Future<bool> Function()? onRemove,
|
Future<bool> Function()? onRemove,
|
||||||
PromoCodeModel? initialPromo,
|
PromoCodeModel? initialPromo,
|
||||||
})? showForm,
|
})? showForm,
|
||||||
Future<void> Function(BuildContext, {required int planId})? showSbp,
|
Future<void> Function(BuildContext, {required int planId, double? amount})? showSbp,
|
||||||
Future<PromoValidateResponse> Function({
|
Future<PromoValidateResponse> Function({
|
||||||
required int planId,
|
required int planId,
|
||||||
required String promoCode,
|
required String promoCode,
|
||||||
@@ -65,7 +66,7 @@ Future<void> showConsultationPaymentFlow(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!context.mounted) return;
|
if (!context.mounted) return;
|
||||||
await sbp(context, planId: planId);
|
await sbp(context, planId: planId, amount: amount);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,7 +93,7 @@ Future<void> showConsultationPaymentFlow(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!context.mounted) return;
|
if (!context.mounted) return;
|
||||||
await sbp(context, planId: planId);
|
await sbp(context, planId: planId, amount: amount);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<bool?> _showGate(BuildContext context) {
|
Future<bool?> _showGate(BuildContext context) {
|
||||||
@@ -113,8 +114,8 @@ Future<PromoCodeResult?> _showForm(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _showSbp(BuildContext context, {required int planId}) {
|
Future<void> _showSbp(BuildContext context, {required int planId, double? amount}) {
|
||||||
return showSbpBanksBottomSheet(context, planId: planId);
|
return showSbpBanksBottomSheet(context, planId: planId, amount: amount);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<PromoValidateResponse> _defaultValidatePromo({
|
Future<PromoValidateResponse> _defaultValidatePromo({
|
||||||
|
|||||||
@@ -8,18 +8,23 @@ import 'package:eatvio_app/core/widgets/custom_outlined_button.dart';
|
|||||||
import 'package:eatvio_app/core/widgets/loader.dart';
|
import 'package:eatvio_app/core/widgets/loader.dart';
|
||||||
import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_cubit.dart';
|
import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_cubit.dart';
|
||||||
import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_state.dart';
|
import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_state.dart';
|
||||||
|
import 'package:eatvio_app/features/payment/presentation/widgets/sbp_qr_bottom_sheet.dart';
|
||||||
import 'package:eatvio_app/generated/l10n.dart';
|
import 'package:eatvio_app/generated/l10n.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
import 'package:sbp/models/c2bmembers_model.dart';
|
import 'package:sbp/models/c2bmembers_model.dart';
|
||||||
|
|
||||||
/// Показывает bottom sheet выбора банка СБП для оплаты консультации.
|
/// Показывает bottom sheet выбора банка СБП для оплаты консультации.
|
||||||
Future<void> showSbpBanksBottomSheet(BuildContext context, {required int planId}) {
|
Future<void> showSbpBanksBottomSheet(
|
||||||
|
BuildContext context, {
|
||||||
|
required int planId,
|
||||||
|
double? amount,
|
||||||
|
}) {
|
||||||
final height = MediaQuery.sizeOf(context).height * 0.55;
|
final height = MediaQuery.sizeOf(context).height * 0.55;
|
||||||
return showBottomSheetWithBlur(
|
return showBottomSheetWithBlur(
|
||||||
context: context,
|
context: context,
|
||||||
height: height,
|
height: height,
|
||||||
child: SbpBanksBottomSheet(planId: planId),
|
child: SbpBanksBottomSheet(planId: planId, amount: amount),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,9 +33,13 @@ Future<void> showSbpBanksBottomSheet(BuildContext context, {required int planId}
|
|||||||
/// При открытии вызывает [ConsultationPaymentCubit.startPayment] с [planId]
|
/// При открытии вызывает [ConsultationPaymentCubit.startPayment] с [planId]
|
||||||
/// и показывает [Loader], пока загружаются checkout_url и список банков.
|
/// и показывает [Loader], пока загружаются checkout_url и список банков.
|
||||||
class SbpBanksBottomSheet extends StatefulWidget {
|
class SbpBanksBottomSheet extends StatefulWidget {
|
||||||
const SbpBanksBottomSheet({super.key, required this.planId, this.cubit});
|
const SbpBanksBottomSheet({super.key, required this.planId, this.amount, this.cubit});
|
||||||
|
|
||||||
final int planId;
|
final int planId;
|
||||||
|
|
||||||
|
/// Сумма к оплате в рублях — передаётся в QR-шит для отображения.
|
||||||
|
final double? amount;
|
||||||
|
|
||||||
final ConsultationPaymentCubit? cubit;
|
final ConsultationPaymentCubit? cubit;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -77,6 +86,32 @@ class _SbpBanksBottomSheetState extends State<SbpBanksBottomSheet> {
|
|||||||
style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black),
|
style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black),
|
||||||
textAlign: TextAlign.center,
|
textAlign: TextAlign.center,
|
||||||
),
|
),
|
||||||
|
// QR-кнопка доступна сразу после получения checkout_url,
|
||||||
|
// не дожидаясь списка банков: на устройствах без банковских
|
||||||
|
// приложений (iOS в РФ) это единственный путь оплаты.
|
||||||
|
BlocBuilder<ConsultationPaymentCubit, ConsultationPaymentState>(
|
||||||
|
buildWhen: (previous, current) =>
|
||||||
|
previous.checkoutUrl != current.checkoutUrl,
|
||||||
|
builder: (context, state) {
|
||||||
|
final checkoutUrl = state.checkoutUrl;
|
||||||
|
if (checkoutUrl == null || checkoutUrl.isEmpty) {
|
||||||
|
return const SizedBox.shrink();
|
||||||
|
}
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 16),
|
||||||
|
child: CustomOutlinedButton(
|
||||||
|
text: s.pay_by_qr_code,
|
||||||
|
height: 52,
|
||||||
|
buttonTextStyle: TextStyles.textMSemibold.copyWith(color: appTheme.whiteA700),
|
||||||
|
buttonStyle: ButtonStyle(
|
||||||
|
side: const WidgetStatePropertyAll(BorderSide.none),
|
||||||
|
backgroundColor: WidgetStatePropertyAll(appTheme.blueA400),
|
||||||
|
),
|
||||||
|
onPressed: _onShowQrTap,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: BlocBuilder<ConsultationPaymentCubit, ConsultationPaymentState>(
|
child: BlocBuilder<ConsultationPaymentCubit, ConsultationPaymentState>(
|
||||||
@@ -122,6 +157,23 @@ class _SbpBanksBottomSheetState extends State<SbpBanksBottomSheet> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Открывает QR-шит поверх шита банков; при подтверждённой оплате
|
||||||
|
/// закрывает и родительский шит.
|
||||||
|
Future<void> _onShowQrTap() async {
|
||||||
|
final paid = await showSbpQrBottomSheet(
|
||||||
|
context,
|
||||||
|
planId: widget.planId,
|
||||||
|
cubit: _cubit,
|
||||||
|
amount: widget.amount,
|
||||||
|
);
|
||||||
|
if (paid == true && mounted) {
|
||||||
|
final navigator = Navigator.of(context);
|
||||||
|
if (navigator.canPop()) {
|
||||||
|
navigator.pop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _onBankTap(C2bmemberModel bank) async {
|
Future<void> _onBankTap(C2bmemberModel bank) async {
|
||||||
final opened = await _cubit.openBank(bank: bank);
|
final opened = await _cubit.openBank(bank: bank);
|
||||||
if (opened && mounted) {
|
if (opened && mounted) {
|
||||||
|
|||||||
@@ -0,0 +1,316 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:eatvio_app/core/app_config.dart';
|
||||||
|
import 'package:eatvio_app/core/locator_service.dart';
|
||||||
|
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||||
|
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||||
|
import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart';
|
||||||
|
import 'package:eatvio_app/core/widgets/bottom_sheet_with_blur.dart';
|
||||||
|
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
|
||||||
|
import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_cubit.dart';
|
||||||
|
import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_state.dart';
|
||||||
|
import 'package:eatvio_app/generated/l10n.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
|
import 'package:qr_flutter/qr_flutter.dart';
|
||||||
|
import 'package:url_launcher/url_launcher.dart';
|
||||||
|
|
||||||
|
/// Тестовый симулятор оплаты СБП (только для стендов разработки/stage).
|
||||||
|
const String _testPayUrlBase = 'https://testpay.alfabank.ru/sbp-page?qrcId=';
|
||||||
|
const String _nspkUrlPrefix = 'https://qr.nspk.ru/';
|
||||||
|
const Duration _pollInterval = Duration(seconds: 3);
|
||||||
|
const Duration _autoCloseDelay = Duration(seconds: 2);
|
||||||
|
|
||||||
|
/// Показывает bottom sheet с QR-кодом СБП для оплаты консультации
|
||||||
|
/// с другого устройства.
|
||||||
|
///
|
||||||
|
/// Возвращает `true`, если оплата подтверждена polling-ом статуса плана.
|
||||||
|
Future<bool?> showSbpQrBottomSheet(
|
||||||
|
BuildContext context, {
|
||||||
|
required int planId,
|
||||||
|
required ConsultationPaymentCubit cubit,
|
||||||
|
double? amount,
|
||||||
|
}) {
|
||||||
|
return showBottomSheetWithBlur<bool>(
|
||||||
|
context: context,
|
||||||
|
height: null,
|
||||||
|
child: SbpQrBottomSheet(
|
||||||
|
planId: planId,
|
||||||
|
cubit: cubit,
|
||||||
|
amount: amount,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// QR-код оплаты СБП: рендерит [ConsultationPaymentState.checkoutUrl]
|
||||||
|
/// (payload вида `https://qr.nspk.ru/{qrcId}`), ожидает оплату через
|
||||||
|
/// polling статуса chosen_plan и показывает успех.
|
||||||
|
class SbpQrBottomSheet extends StatefulWidget {
|
||||||
|
const SbpQrBottomSheet({
|
||||||
|
super.key,
|
||||||
|
required this.planId,
|
||||||
|
required this.cubit,
|
||||||
|
this.amount,
|
||||||
|
this.chatRepository,
|
||||||
|
this.pollInterval = _pollInterval,
|
||||||
|
});
|
||||||
|
|
||||||
|
final int planId;
|
||||||
|
final ConsultationPaymentCubit cubit;
|
||||||
|
|
||||||
|
/// Сумма к оплате в рублях (показывается над QR, если передана).
|
||||||
|
final double? amount;
|
||||||
|
|
||||||
|
/// Переопределяется в тестах; по умолчанию берётся из DI.
|
||||||
|
final ChatRepository? chatRepository;
|
||||||
|
|
||||||
|
final Duration pollInterval;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<SbpQrBottomSheet> createState() => _SbpQrBottomSheetState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _SbpQrBottomSheetState extends State<SbpQrBottomSheet> {
|
||||||
|
late final ChatRepository _chatRepository;
|
||||||
|
late final Timer _pollTimer;
|
||||||
|
bool _paid = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_chatRepository = widget.chatRepository ?? sl<ChatRepository>();
|
||||||
|
_pollTimer = Timer.periodic(widget.pollInterval, (_) => _pollStatus());
|
||||||
|
_pollStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_pollTimer.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pollStatus() async {
|
||||||
|
if (_paid || !mounted) return;
|
||||||
|
try {
|
||||||
|
final plan = await _chatRepository.getChosenPlan(id: widget.planId);
|
||||||
|
if (plan.chosenPlanState.isStateAfterPaidState()) {
|
||||||
|
_onPaid();
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
// Сетевые сбои polling-а игнорируем — следующий тик повторит проверку.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onPaid() {
|
||||||
|
if (_paid || !mounted) return;
|
||||||
|
setState(() => _paid = true);
|
||||||
|
Future.delayed(_autoCloseDelay, () {
|
||||||
|
if (!mounted) return;
|
||||||
|
Navigator.of(context).pop(true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final s = S.of(context);
|
||||||
|
return BlocProvider<ConsultationPaymentCubit>.value(
|
||||||
|
value: widget.cubit,
|
||||||
|
child: BlocBuilder<ConsultationPaymentCubit, ConsultationPaymentState>(
|
||||||
|
builder: (context, state) {
|
||||||
|
final checkoutUrl = state.checkoutUrl;
|
||||||
|
if (checkoutUrl == null || checkoutUrl.isEmpty) {
|
||||||
|
return const SizedBox.shrink();
|
||||||
|
}
|
||||||
|
return SingleChildScrollView(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
const BottomSheetHandlerBar(),
|
||||||
|
const SizedBox(height: 20),
|
||||||
|
Text(
|
||||||
|
_paid ? s.sbp_qr_paid_title : s.sbp_qr_title,
|
||||||
|
style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black),
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
if (_paid)
|
||||||
|
_PaidContent(description: s.sbp_qr_paid_description)
|
||||||
|
else ...[
|
||||||
|
if (widget.amount != null) ...[
|
||||||
|
Text(
|
||||||
|
s.sbp_qr_amount_label,
|
||||||
|
style: TextStyles.textMMedium.copyWith(color: appTheme.gray600),
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(
|
||||||
|
'${widget.amount!.toStringAsFixed(0)} ₽',
|
||||||
|
style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black),
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
],
|
||||||
|
_QrCodeCard(checkoutUrl: checkoutUrl),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
_HowToPay(
|
||||||
|
step1: s.sbp_qr_step1,
|
||||||
|
step2: s.sbp_qr_step2,
|
||||||
|
step3: s.sbp_qr_step3,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
_TestPayButton(checkoutUrl: checkoutUrl),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
Text(
|
||||||
|
s.sbp_qr_waiting_payment,
|
||||||
|
style: TextStyles.textMMedium.copyWith(color: appTheme.gray600),
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _QrCodeCard extends StatelessWidget {
|
||||||
|
const _QrCodeCard({required this.checkoutUrl});
|
||||||
|
|
||||||
|
final String checkoutUrl;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Center(
|
||||||
|
child: Container(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Colors.white,
|
||||||
|
borderRadius: BorderRadius.circular(16),
|
||||||
|
border: Border.all(color: appTheme.blueGray300),
|
||||||
|
),
|
||||||
|
child: QrImageView(
|
||||||
|
key: const ValueKey('sbp_qr_code'),
|
||||||
|
data: checkoutUrl,
|
||||||
|
size: 200,
|
||||||
|
backgroundColor: Colors.white,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _HowToPay extends StatelessWidget {
|
||||||
|
const _HowToPay({required this.step1, required this.step2, required this.step3});
|
||||||
|
|
||||||
|
final String step1;
|
||||||
|
final String step2;
|
||||||
|
final String step3;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Container(
|
||||||
|
padding: const EdgeInsets.all(16),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: appTheme.blueA400.withValues(alpha: 0.08),
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(step1, style: TextStyles.textSMedium.copyWith(color: appTheme.black)),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(step2, style: TextStyles.textSMedium.copyWith(color: appTheme.black)),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(step3, style: TextStyles.textSMedium.copyWith(color: appTheme.black)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Кнопка открытия тестового симулятора оплаты Альфа-Банка.
|
||||||
|
///
|
||||||
|
/// Видна только когда QR выдан непродовым бэкендом: тестовый qrcId от
|
||||||
|
/// продового в приложении не отличить (формат одинаковый), различает их
|
||||||
|
/// именно то, какой бэкенд выдал checkout_url — на стендах разработки/stage
|
||||||
|
/// Альфа подключена в sandbox и выдаёт QR тестового терминала. Поэтому
|
||||||
|
/// критерий — текущий base URL API не продуктовый (см. [AppConfig.isProdApi]).
|
||||||
|
class _TestPayButton extends StatelessWidget {
|
||||||
|
const _TestPayButton({required this.checkoutUrl});
|
||||||
|
|
||||||
|
final String checkoutUrl;
|
||||||
|
|
||||||
|
bool get _visible {
|
||||||
|
if (sl<AppConfig>().isProdApi) return false;
|
||||||
|
return checkoutUrl.startsWith(_nspkUrlPrefix);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
if (!_visible) return const SizedBox.shrink();
|
||||||
|
final s = S.of(context);
|
||||||
|
return Container(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: const Color(0xFFFFF3E0),
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
s.sbp_qr_test_hint,
|
||||||
|
style: TextStyles.textXSSemibold.copyWith(color: appTheme.gray600),
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
OutlinedButton(
|
||||||
|
onPressed: () => _openTestPayment(),
|
||||||
|
child: Text(s.sbp_qr_open_test_payment),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _openTestPayment() async {
|
||||||
|
final qrcId = checkoutUrl.replaceFirst(_nspkUrlPrefix, '');
|
||||||
|
final uri = Uri.parse('$_testPayUrlBase$qrcId');
|
||||||
|
try {
|
||||||
|
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||||
|
} catch (_) {
|
||||||
|
// Не смогли открыть браузер — пользователь оплатит по QR.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _PaidContent extends StatelessWidget {
|
||||||
|
const _PaidContent({required this.description});
|
||||||
|
|
||||||
|
final String description;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Column(
|
||||||
|
children: [
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Container(
|
||||||
|
width: 64,
|
||||||
|
height: 64,
|
||||||
|
decoration: const BoxDecoration(color: Color(0xFFE8F5E9), shape: BoxShape.circle),
|
||||||
|
child: const Icon(Icons.check_rounded, color: Color(0xFF4CAF50), size: 40),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Text(
|
||||||
|
description,
|
||||||
|
style: TextStyles.textMMedium.copyWith(color: appTheme.gray600),
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,38 +9,54 @@ import 'package:eatvio_app/core/error_reporting/report_from.dart';
|
|||||||
class PersonalDietSuggestionCubit extends Cubit<PersonalDietSuggestionState> {
|
class PersonalDietSuggestionCubit extends Cubit<PersonalDietSuggestionState> {
|
||||||
final DietRepository dietRepository;
|
final DietRepository dietRepository;
|
||||||
final PersonalDietSuggestionRepository personalDietSuggestionService;
|
final PersonalDietSuggestionRepository personalDietSuggestionService;
|
||||||
late final int dietId;
|
late int dietId;
|
||||||
PersonalDietSuggestionCubit({required this.dietRepository, required this.personalDietSuggestionService}) : super(PersonalDietSuggestionState());
|
PersonalDietSuggestionCubit({required this.dietRepository, required this.personalDietSuggestionService}) : super(PersonalDietSuggestionState());
|
||||||
|
|
||||||
Future<void> setDietName(int dietId) async {
|
Future<void> setDietName(int dietId) async {
|
||||||
try {
|
try {
|
||||||
emit(state.copyWith(isLoading: true, error: null));
|
if (!isClosed) {
|
||||||
|
emit(state.copyWith(isLoading: true, error: null));
|
||||||
|
}
|
||||||
final diet = await dietRepository.getDiet(dietId);
|
final diet = await dietRepository.getDiet(dietId);
|
||||||
emit(state.copyWith(isLoading: false, dietName: diet.name));
|
if (!isClosed) {
|
||||||
|
emit(state.copyWith(
|
||||||
|
isLoading: false,
|
||||||
|
dietName: diet.name,
|
||||||
|
dietDuration: diet.duration,
|
||||||
|
));
|
||||||
|
}
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
await reportFrom(e, st, this);
|
await reportFrom(e, st, this);
|
||||||
log(e.toString(), stackTrace: st);
|
log(e.toString(), stackTrace: st);
|
||||||
emit(state.copyWith(isLoading: false, error: e.toString()));
|
if (!isClosed) {
|
||||||
|
emit(state.copyWith(isLoading: false, error: e.toString()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> getConsultationWithPersonalDiets(int dietId) async {
|
Future<void> getConsultationWithPersonalDiets(int dietId) async {
|
||||||
try {
|
try {
|
||||||
this.dietId = dietId;
|
this.dietId = dietId;
|
||||||
emit(state.copyWith(isLoading: true, error: null));
|
if (!isClosed) {
|
||||||
setDietName(dietId);
|
emit(state.copyWith(isLoading: true, error: null));
|
||||||
|
}
|
||||||
|
await setDietName(dietId);
|
||||||
final consultations = await personalDietSuggestionService.getConsultationWithPersonalDiets();
|
final consultations = await personalDietSuggestionService.getConsultationWithPersonalDiets();
|
||||||
final consultationWithDiet = consultations.where((consultation) => consultation.personalDietId != null).toList();
|
final consultationWithDiet = consultations.where((consultation) => consultation.personalDietId != null).toList();
|
||||||
final consultationWithoutDiet = consultations.where((consultation) => consultation.personalDietId == null).toList();
|
final consultationWithoutDiet = consultations.where((consultation) => consultation.personalDietId == null).toList();
|
||||||
emit(state.copyWith(
|
if (!isClosed) {
|
||||||
isLoading: false,
|
emit(state.copyWith(
|
||||||
consultationsWithDiet: consultationWithDiet,
|
isLoading: false,
|
||||||
consultationsWithoutDiet: consultationWithoutDiet,
|
consultationsWithDiet: consultationWithDiet,
|
||||||
));
|
consultationsWithoutDiet: consultationWithoutDiet,
|
||||||
|
));
|
||||||
|
}
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
await reportFrom(e, st, this);
|
await reportFrom(e, st, this);
|
||||||
log(e.toString(), stackTrace: st);
|
log(e.toString(), stackTrace: st);
|
||||||
emit(state.copyWith(isLoading: false, error: e.toString()));
|
if (!isClosed) {
|
||||||
|
emit(state.copyWith(isLoading: false, error: e.toString()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,6 +65,7 @@ class PersonalDietSuggestionCubit extends Cubit<PersonalDietSuggestionState> {
|
|||||||
}) async {
|
}) async {
|
||||||
try {
|
try {
|
||||||
await personalDietSuggestionService.attachPersonalDiet(consultationId: consultationId, dietId: dietId);
|
await personalDietSuggestionService.attachPersonalDiet(consultationId: consultationId, dietId: dietId);
|
||||||
|
await getConsultationWithPersonalDiets(dietId);
|
||||||
return true;
|
return true;
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
await reportFrom(e, st, this);
|
await reportFrom(e, st, this);
|
||||||
@@ -62,6 +79,7 @@ class PersonalDietSuggestionCubit extends Cubit<PersonalDietSuggestionState> {
|
|||||||
}) async {
|
}) async {
|
||||||
try {
|
try {
|
||||||
await personalDietSuggestionService.reattachPersonalDiet(consultationId: consultationId, dietId: dietId);
|
await personalDietSuggestionService.reattachPersonalDiet(consultationId: consultationId, dietId: dietId);
|
||||||
|
await getConsultationWithPersonalDiets(dietId);
|
||||||
return true;
|
return true;
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
await reportFrom(e, st, this);
|
await reportFrom(e, st, this);
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ abstract class PersonalDietSuggestionState with _$PersonalDietSuggestionState {
|
|||||||
@Default([]) List<ConsultationModel> consultationsWithDiet,
|
@Default([]) List<ConsultationModel> consultationsWithDiet,
|
||||||
@Default([]) List<ConsultationModel> consultationsWithoutDiet,
|
@Default([]) List<ConsultationModel> consultationsWithoutDiet,
|
||||||
@Default('') String dietName,
|
@Default('') String dietName,
|
||||||
|
@Default(0) int dietDuration,
|
||||||
@Default(false) bool isLoading,
|
@Default(false) bool isLoading,
|
||||||
@Default(null) String? error,
|
@Default(null) String? error,
|
||||||
}) = _PersonalDietSuggestionState;
|
}) = _PersonalDietSuggestionState;
|
||||||
|
}
|
||||||
}
|
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import 'package:eatvio_app/core/app_router.dart';
|
|||||||
import 'package:eatvio_app/core/locator_service.dart';
|
import 'package:eatvio_app/core/locator_service.dart';
|
||||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||||
|
import 'package:eatvio_app/core/utils/localization_utils.dart';
|
||||||
|
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||||
import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart';
|
import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart';
|
||||||
import 'package:eatvio_app/core/widgets/bottom_sheet_with_blur.dart';
|
import 'package:eatvio_app/core/widgets/bottom_sheet_with_blur.dart';
|
||||||
import 'package:eatvio_app/core/widgets/custom_outlined_button.dart';
|
import 'package:eatvio_app/core/widgets/custom_outlined_button.dart';
|
||||||
@@ -11,6 +13,7 @@ import 'package:eatvio_app/features/consultations/models/consultation_model.dart
|
|||||||
import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart';
|
import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart';
|
||||||
import 'package:eatvio_app/generated/l10n.dart';
|
import 'package:eatvio_app/generated/l10n.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:intl/intl.dart';
|
||||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
import 'package:go_router/go_router.dart';
|
import 'package:go_router/go_router.dart';
|
||||||
|
|
||||||
@@ -19,9 +22,15 @@ class ConsultationWidget extends StatelessWidget {
|
|||||||
super.key,
|
super.key,
|
||||||
required this.consultationModel,
|
required this.consultationModel,
|
||||||
required this.dietName,
|
required this.dietName,
|
||||||
|
this.dietDuration = 0,
|
||||||
});
|
});
|
||||||
final ConsultationModel consultationModel;
|
final ConsultationModel consultationModel;
|
||||||
final String dietName;
|
final String dietName;
|
||||||
|
final int dietDuration;
|
||||||
|
|
||||||
|
bool get _isDurationMismatch =>
|
||||||
|
dietDuration > 0 && consultationModel.duration != dietDuration;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final s = S.of(context);
|
final s = S.of(context);
|
||||||
@@ -64,7 +73,20 @@ class ConsultationWidget extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
Text(
|
Text(
|
||||||
'Старт: ${consultationModel.userName}',
|
s.plan_duration_label(
|
||||||
|
consultationModel.duration,
|
||||||
|
getDayForm(consultationModel.duration, s),
|
||||||
|
),
|
||||||
|
style: TextStyles.textMMedium.copyWith(
|
||||||
|
color: const Color(0xFF88949F),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Text(
|
||||||
|
s.start_date_label(
|
||||||
|
DateFormat('dd.MM.yyyy').format(
|
||||||
|
consultationModel.startDate,
|
||||||
|
),
|
||||||
|
),
|
||||||
style: TextStyles.textMMedium.copyWith(
|
style: TextStyles.textMMedium.copyWith(
|
||||||
color: const Color(0xFF88949F),
|
color: const Color(0xFF88949F),
|
||||||
),
|
),
|
||||||
@@ -103,15 +125,47 @@ class ConsultationWidget extends StatelessWidget {
|
|||||||
color: const Color(0xFF88949F),
|
color: const Color(0xFF88949F),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
Text(
|
||||||
|
s.plan_duration_label(
|
||||||
|
consultationModel.duration,
|
||||||
|
getDayForm(consultationModel.duration, s),
|
||||||
|
),
|
||||||
|
style: TextStyles.textMMedium.copyWith(
|
||||||
|
color: const Color(0xFF88949F),
|
||||||
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
|
if (_isDurationMismatch)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 8),
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Icon(Icons.error_outline, size: 18, color: appTheme.red),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
s.personal_diet_duration_mismatch(
|
||||||
|
dietDuration,
|
||||||
|
getDayForm(dietDuration, s),
|
||||||
|
consultationModel.duration,
|
||||||
|
getDayForm(consultationModel.duration, s),
|
||||||
|
),
|
||||||
|
style: TextStyles.textSMedium.copyWith(color: appTheme.red),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
if (consultationModel.personalDietId != null)
|
if (consultationModel.personalDietId != null)
|
||||||
CustomOutlinedButton(
|
CustomOutlinedButton(
|
||||||
text: s.changeDiet,
|
text: s.changeDiet,
|
||||||
height: 52,
|
height: 52,
|
||||||
|
isDisabled: _isDurationMismatch,
|
||||||
buttonTextStyle: TextStyles.textMSemibold.copyWith(
|
buttonTextStyle: TextStyles.textMSemibold.copyWith(
|
||||||
color: appTheme.gray,
|
color: appTheme.gray,
|
||||||
),
|
),
|
||||||
@@ -128,35 +182,8 @@ class ConsultationWidget extends StatelessWidget {
|
|||||||
userName: consultationModel.userName,
|
userName: consultationModel.userName,
|
||||||
dietName: dietName,
|
dietName: dietName,
|
||||||
onTap: () async {
|
onTap: () async {
|
||||||
final result = await context
|
|
||||||
.read<PersonalDietSuggestionCubit>()
|
|
||||||
.attachDietToConsultation(
|
|
||||||
consultationId: consultationModel.id,
|
|
||||||
);
|
|
||||||
AppRouter.navigatorKey.currentContext?.pop();
|
AppRouter.navigatorKey.currentContext?.pop();
|
||||||
if (result) {
|
await _attachDiet(context, reattach: true);
|
||||||
if (!context.mounted) return;
|
|
||||||
showBottomSheetWithBlur(
|
|
||||||
userRootNavigator: true,
|
|
||||||
context: context,
|
|
||||||
height: null,
|
|
||||||
child: SuggestionSuccessBottomSheet(
|
|
||||||
userName: consultationModel.userName,
|
|
||||||
dietName: dietName,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!context.mounted) return;
|
|
||||||
showBottomSheetWithBlur(
|
|
||||||
userRootNavigator: true,
|
|
||||||
context: context,
|
|
||||||
height: null,
|
|
||||||
child: SuggestionFailureBottomSheet(
|
|
||||||
userName: consultationModel.userName,
|
|
||||||
dietName: dietName,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -166,12 +193,17 @@ class ConsultationWidget extends StatelessWidget {
|
|||||||
CustomOutlinedButton(
|
CustomOutlinedButton(
|
||||||
text: s.suggestDiet,
|
text: s.suggestDiet,
|
||||||
height: 52,
|
height: 52,
|
||||||
|
isDisabled: _isDurationMismatch,
|
||||||
buttonTextStyle: TextStyles.textMSemibold.copyWith(
|
buttonTextStyle: TextStyles.textMSemibold.copyWith(
|
||||||
color: appTheme.whiteA700,
|
color: _isDurationMismatch ? appTheme.gray : appTheme.whiteA700,
|
||||||
),
|
),
|
||||||
buttonStyle: ButtonStyle(
|
buttonStyle: ButtonStyle(
|
||||||
side: const WidgetStatePropertyAll(BorderSide.none),
|
side: const WidgetStatePropertyAll(BorderSide.none),
|
||||||
backgroundColor: WidgetStatePropertyAll(appTheme.blueA400),
|
backgroundColor: WidgetStatePropertyAll(
|
||||||
|
_isDurationMismatch
|
||||||
|
? appTheme.dividerColor
|
||||||
|
: appTheme.blueA400,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
onPressed: () async {
|
onPressed: () async {
|
||||||
showBottomSheetWithBlur(
|
showBottomSheetWithBlur(
|
||||||
@@ -183,34 +215,7 @@ class ConsultationWidget extends StatelessWidget {
|
|||||||
dietName: dietName,
|
dietName: dietName,
|
||||||
onTap: () async {
|
onTap: () async {
|
||||||
AppRouter.navigatorKey.currentContext?.pop();
|
AppRouter.navigatorKey.currentContext?.pop();
|
||||||
final result = await context
|
await _attachDiet(context, reattach: false);
|
||||||
.read<PersonalDietSuggestionCubit>()
|
|
||||||
.attachDietToConsultation(
|
|
||||||
consultationId: consultationModel.id,
|
|
||||||
);
|
|
||||||
if (result) {
|
|
||||||
if (!context.mounted) return;
|
|
||||||
showBottomSheetWithBlur(
|
|
||||||
userRootNavigator: true,
|
|
||||||
context: context,
|
|
||||||
height: null,
|
|
||||||
child: SuggestionSuccessBottomSheet(
|
|
||||||
userName: consultationModel.userName,
|
|
||||||
dietName: dietName,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!context.mounted) return;
|
|
||||||
showBottomSheetWithBlur(
|
|
||||||
userRootNavigator: true,
|
|
||||||
context: context,
|
|
||||||
height: null,
|
|
||||||
child: SuggestionFailureBottomSheet(
|
|
||||||
userName: consultationModel.userName,
|
|
||||||
dietName: dietName,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -220,6 +225,41 @@ class ConsultationWidget extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _attachDiet(
|
||||||
|
BuildContext context, {
|
||||||
|
required bool reattach,
|
||||||
|
}) async {
|
||||||
|
final router = GoRouter.of(context);
|
||||||
|
final chatId = consultationModel.chatId;
|
||||||
|
final noChatMessage = S.of(context).msg_something_went_wrong;
|
||||||
|
final cubit = context.read<PersonalDietSuggestionCubit>();
|
||||||
|
final result = reattach
|
||||||
|
? await cubit.reattachDietToConsultation(
|
||||||
|
consultationId: consultationModel.id,
|
||||||
|
)
|
||||||
|
: await cubit.attachDietToConsultation(
|
||||||
|
consultationId: consultationModel.id,
|
||||||
|
);
|
||||||
|
if (!result) {
|
||||||
|
if (!context.mounted) return;
|
||||||
|
showBottomSheetWithBlur(
|
||||||
|
userRootNavigator: true,
|
||||||
|
context: context,
|
||||||
|
height: null,
|
||||||
|
child: SuggestionFailureBottomSheet(
|
||||||
|
userName: consultationModel.userName,
|
||||||
|
dietName: dietName,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (chatId == null || chatId.isEmpty) {
|
||||||
|
showErrorToast(noChatMessage);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
router.goNamed('chatScreen', queryParameters: {'uuid': chatId});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class SuggestDietBottomSheet extends StatefulWidget {
|
class SuggestDietBottomSheet extends StatefulWidget {
|
||||||
@@ -278,65 +318,6 @@ class _SuggestDietBottomSheet extends State<SuggestDietBottomSheet> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class SuggestionSuccessBottomSheet extends StatefulWidget {
|
|
||||||
const SuggestionSuccessBottomSheet({
|
|
||||||
super.key,
|
|
||||||
required this.userName,
|
|
||||||
required this.dietName,
|
|
||||||
});
|
|
||||||
final String userName;
|
|
||||||
final String dietName;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<SuggestionSuccessBottomSheet> createState() =>
|
|
||||||
_SuggestionSuccessBottomSheet();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _SuggestionSuccessBottomSheet
|
|
||||||
extends State<SuggestionSuccessBottomSheet> {
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final s = S.of(context);
|
|
||||||
return Padding(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 12.0),
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
const BottomSheetHandlerBar(),
|
|
||||||
const SizedBox(height: 20),
|
|
||||||
Text(
|
|
||||||
'Предложение диеты',
|
|
||||||
style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
Text(
|
|
||||||
'«${widget.dietName}» предложена пользователю ${widget.userName}',
|
|
||||||
style: TextStyles.textSMedium.copyWith(color: appTheme.black),
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
CustomOutlinedButton(
|
|
||||||
text: s.ok,
|
|
||||||
height: 52,
|
|
||||||
buttonTextStyle: TextStyles.textMSemibold.copyWith(
|
|
||||||
color: appTheme.whiteA700,
|
|
||||||
),
|
|
||||||
buttonStyle: ButtonStyle(
|
|
||||||
side: const WidgetStatePropertyAll(BorderSide.none),
|
|
||||||
backgroundColor: WidgetStatePropertyAll(appTheme.blueA400),
|
|
||||||
),
|
|
||||||
onPressed: () async {
|
|
||||||
AppRouter.navigatorKey.currentContext?.pop();
|
|
||||||
},
|
|
||||||
),
|
|
||||||
const SizedBox(height: 40),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class SuggestionFailureBottomSheet extends StatefulWidget {
|
class SuggestionFailureBottomSheet extends StatefulWidget {
|
||||||
const SuggestionFailureBottomSheet({
|
const SuggestionFailureBottomSheet({
|
||||||
super.key,
|
super.key,
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import 'package:eatvio_app/core/locator_service.dart';
|
import 'package:eatvio_app/core/locator_service.dart';
|
||||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||||
|
import 'package:eatvio_app/core/utils/localization_utils.dart';
|
||||||
import 'package:eatvio_app/core/widgets/loader.dart';
|
import 'package:eatvio_app/core/widgets/loader.dart';
|
||||||
import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart';
|
import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart';
|
||||||
import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_state.dart';
|
import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_state.dart';
|
||||||
@@ -17,7 +18,9 @@ class PersonalDietSuggestionScreen extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return BlocProvider(
|
return BlocProvider(
|
||||||
create: (context) => sl<PersonalDietSuggestionCubit>()..getConsultationWithPersonalDiets(dietId),
|
create: (context) =>
|
||||||
|
sl<PersonalDietSuggestionCubit>()
|
||||||
|
..getConsultationWithPersonalDiets(dietId),
|
||||||
child: const PersonalDietSuggestionScreenContent(),
|
child: const PersonalDietSuggestionScreenContent(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -28,7 +31,10 @@ class PersonalDietSuggestionScreenContent extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final s = S.of(context);
|
final s = S.of(context);
|
||||||
return BlocBuilder<PersonalDietSuggestionCubit, PersonalDietSuggestionState>(
|
return BlocBuilder<
|
||||||
|
PersonalDietSuggestionCubit,
|
||||||
|
PersonalDietSuggestionState
|
||||||
|
>(
|
||||||
builder: (context, state) {
|
builder: (context, state) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
backgroundColor: appTheme.gray100,
|
backgroundColor: appTheme.gray100,
|
||||||
@@ -36,45 +42,97 @@ class PersonalDietSuggestionScreenContent extends StatelessWidget {
|
|||||||
centerTitle: true,
|
centerTitle: true,
|
||||||
title: Text(
|
title: Text(
|
||||||
'${s.dietSuggestion}\n«${state.dietName}»',
|
'${s.dietSuggestion}\n«${state.dietName}»',
|
||||||
style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black),
|
style: TextStyles.headingXLSemibold.copyWith(
|
||||||
|
color: appTheme.black,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
body: state.isLoading
|
body: state.isLoading
|
||||||
? const Center(child: Loader())
|
? const Center(child: Loader())
|
||||||
: (state.consultationsWithDiet.isEmpty && state.consultationsWithoutDiet.isEmpty)
|
: SingleChildScrollView(
|
||||||
? Center(
|
child: Column(
|
||||||
child: Padding(
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
padding: const EdgeInsets.all(32.0),
|
children: [
|
||||||
child: Text(
|
if (state.dietDuration > 0)
|
||||||
'Нет активных консультаций с персональной диетой',
|
Padding(
|
||||||
style: TextStyles.textMSemibold.copyWith(color: appTheme.gray),
|
padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
|
||||||
textAlign: TextAlign.center,
|
child: _PersonalDietDurationHint(
|
||||||
),
|
duration: state.dietDuration,
|
||||||
),
|
|
||||||
)
|
|
||||||
: SingleChildScrollView(
|
|
||||||
child: Column(
|
|
||||||
children: [
|
|
||||||
...List.generate(state.consultationsWithDiet.length, (index) {
|
|
||||||
return ConsultationWidget(
|
|
||||||
consultationModel: state.consultationsWithDiet[index],
|
|
||||||
dietName: state.dietName,
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
const SizedBox(
|
|
||||||
height: 12,
|
|
||||||
),
|
),
|
||||||
...List.generate(state.consultationsWithoutDiet.length, (index) {
|
),
|
||||||
|
if (state.consultationsWithDiet.isEmpty &&
|
||||||
|
state.consultationsWithoutDiet.isEmpty)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.all(32),
|
||||||
|
child: Text(
|
||||||
|
s.no_active_personal_diet_consultations,
|
||||||
|
style: TextStyles.textMSemibold.copyWith(
|
||||||
|
color: appTheme.gray,
|
||||||
|
),
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else ...[
|
||||||
|
...List.generate(state.consultationsWithDiet.length, (
|
||||||
|
index,
|
||||||
|
) {
|
||||||
|
return ConsultationWidget(
|
||||||
|
consultationModel:
|
||||||
|
state.consultationsWithDiet[index],
|
||||||
|
dietName: state.dietName,
|
||||||
|
dietDuration: state.dietDuration,
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
...List.generate(
|
||||||
|
state.consultationsWithoutDiet.length,
|
||||||
|
(index) {
|
||||||
return ConsultationWidget(
|
return ConsultationWidget(
|
||||||
consultationModel: state.consultationsWithoutDiet[index],
|
consultationModel:
|
||||||
|
state.consultationsWithoutDiet[index],
|
||||||
dietName: state.dietName,
|
dietName: state.dietName,
|
||||||
|
dietDuration: state.dietDuration,
|
||||||
);
|
);
|
||||||
})
|
},
|
||||||
],
|
),
|
||||||
),
|
],
|
||||||
),
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class _PersonalDietDurationHint extends StatelessWidget {
|
||||||
|
const _PersonalDietDurationHint({required this.duration});
|
||||||
|
|
||||||
|
final int duration;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final s = S.of(context);
|
||||||
|
return Container(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: appTheme.gray50,
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
border: Border.all(color: appTheme.dividerColor),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Icon(Icons.info_outline, size: 20, color: appTheme.blueA400),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
s.personal_diet_duration_hint(duration, getDayForm(duration, s)),
|
||||||
|
style: TextStyles.textSMedium.copyWith(color: appTheme.gray),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -11,13 +11,23 @@ class PersonalDietSuggestionRepository {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> attachPersonalDiet({required int consultationId, required int dietId}) async {
|
Future<void> attachPersonalDiet({
|
||||||
return personalDietSuggestionService.attachPersonalDiet(consultationId: consultationId, dietId: dietId);
|
required int consultationId,
|
||||||
|
required int dietId,
|
||||||
|
}) async {
|
||||||
|
await personalDietSuggestionService.attachPersonalDiet(
|
||||||
|
consultationId,
|
||||||
|
{'diet_id': dietId},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> reattachPersonalDiet({required int consultationId, required int dietId}) async {
|
Future<void> reattachPersonalDiet({
|
||||||
return await personalDietSuggestionService.reattachPersonalDiet(consultationId: consultationId, dietId: dietId);
|
required int consultationId,
|
||||||
|
required int dietId,
|
||||||
|
}) async {
|
||||||
|
await personalDietSuggestionService.reattachPersonalDiet(
|
||||||
|
consultationId,
|
||||||
|
{'diet_id': dietId},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,36 +1,40 @@
|
|||||||
import 'package:dio/dio.dart';
|
import 'package:dio/dio.dart';
|
||||||
import 'package:eatvio_app/features/consultations/models/consultation_model.dart';
|
import 'package:eatvio_app/features/consultations/models/consultation_model.dart';
|
||||||
|
import 'package:retrofit/retrofit.dart';
|
||||||
|
|
||||||
class PersonalDietSuggestionService {
|
part 'personal_diet_suggestion_service.g.dart';
|
||||||
final Dio dio;
|
|
||||||
PersonalDietSuggestionService(this.dio);
|
|
||||||
|
|
||||||
Future<ConsultationPaginationModel> getConsultationWithPersonalDiets() async {
|
@RestApi()
|
||||||
try {
|
abstract class PersonalDietSuggestionService {
|
||||||
final response = await dio.get('/api/consultations', queryParameters: {
|
factory PersonalDietSuggestionService(Dio dio, {String? baseUrl}) =
|
||||||
'filters[plan][has_personal_diet][\$personal_diet]': '1',
|
_PersonalDietSuggestionService;
|
||||||
'filters[last_state][\$notIn][]': ['done', 'charge_was_collected', 'complained', 'last_day_finished', 'canceled_by_the_initiator', 'inited'],
|
|
||||||
'sort[]': 'start_date:desc',
|
|
||||||
});
|
|
||||||
return ConsultationPaginationModel.fromJson(response.data);
|
|
||||||
} catch (e) {
|
|
||||||
rethrow;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> attachPersonalDiet({required int consultationId, required int dietId}) async {
|
@GET('/api/consultations')
|
||||||
try {
|
Future<ConsultationPaginationModel> getConsultationWithPersonalDiets({
|
||||||
await dio.post('/api/chosen_plans/$consultationId/attach_diet', data: {'diet_id': dietId});
|
@Query('filters[plan][has_personal_diet][\$personal_diet]')
|
||||||
} catch (e) {
|
String hasPersonalDiet = '1',
|
||||||
rethrow;
|
@Query('filters[last_state][\$notIn][]')
|
||||||
}
|
List<String> notIn = const [
|
||||||
}
|
'done',
|
||||||
|
'charge_was_collected',
|
||||||
|
'complained',
|
||||||
|
'last_day_finished',
|
||||||
|
'last_day_started',
|
||||||
|
'canceled_by_the_initiator',
|
||||||
|
'inited',
|
||||||
|
],
|
||||||
|
@Query('sort[]') List<String> sort = const ['start_date:desc'],
|
||||||
|
});
|
||||||
|
|
||||||
Future<void> reattachPersonalDiet({required int consultationId, required int dietId}) async {
|
@POST('/api/chosen_plans/{id}/attach_diet')
|
||||||
try {
|
Future<void> attachPersonalDiet(
|
||||||
await dio.post('/api/chosen_plans/$consultationId/re_attach_diet', data: {'diet_id': dietId});
|
@Path('id') int consultationId,
|
||||||
} catch (e) {
|
@Body() Map<String, dynamic> body,
|
||||||
rethrow;
|
);
|
||||||
}
|
|
||||||
}
|
@POST('/api/chosen_plans/{id}/re_attach_diet')
|
||||||
|
Future<void> reattachPersonalDiet(
|
||||||
|
@Path('id') int consultationId,
|
||||||
|
@Body() Map<String, dynamic> body,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,6 +62,32 @@ enum ChosenPlanStateEnum {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool get canShowCancelAction {
|
||||||
|
switch (this) {
|
||||||
|
case ChosenPlanStateEnum.stateInited:
|
||||||
|
case ChosenPlanStateEnum.stateInCoordination:
|
||||||
|
case ChosenPlanStateEnum.stateStartDateHasBeenSet:
|
||||||
|
case ChosenPlanStateEnum.statePendingPayment:
|
||||||
|
case ChosenPlanStateEnum.statePaid:
|
||||||
|
case ChosenPlanStateEnum.stateStarted:
|
||||||
|
case ChosenPlanStateEnum.stateInProgress:
|
||||||
|
return true;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get isCancelAfterPaidState {
|
||||||
|
switch (this) {
|
||||||
|
case ChosenPlanStateEnum.statePaid:
|
||||||
|
case ChosenPlanStateEnum.stateStarted:
|
||||||
|
case ChosenPlanStateEnum.stateInProgress:
|
||||||
|
return true;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
static List<ChosenPlanStateEnum> getActiveStates() {
|
static List<ChosenPlanStateEnum> getActiveStates() {
|
||||||
return [
|
return [
|
||||||
ChosenPlanStateEnum.statePaid,
|
ChosenPlanStateEnum.statePaid,
|
||||||
|
|||||||
29
lib/features/plans/enums/plan_option_type_enum.dart
Normal file
29
lib/features/plans/enums/plan_option_type_enum.dart
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||||
|
|
||||||
|
enum PlanOptionType {
|
||||||
|
@JsonValue('options1')
|
||||||
|
options1('options1'),
|
||||||
|
@JsonValue('options2')
|
||||||
|
options2('options2'),
|
||||||
|
@JsonValue('options3')
|
||||||
|
options3('options3');
|
||||||
|
|
||||||
|
const PlanOptionType(this.apiValue);
|
||||||
|
|
||||||
|
final String apiValue;
|
||||||
|
|
||||||
|
static PlanOptionType? tryParse(String? raw) {
|
||||||
|
for (final option in values) {
|
||||||
|
if (option.apiValue == raw) {
|
||||||
|
return option;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static PlanOptionType fromIndex(int index) => switch (index) {
|
||||||
|
1 => PlanOptionType.options2,
|
||||||
|
2 => PlanOptionType.options3,
|
||||||
|
_ => PlanOptionType.options1,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
|
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
|
||||||
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||||
|
import 'package:eatvio_app/features/plans/enums/plan_option_type_enum.dart';
|
||||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||||
|
|
||||||
part 'chosen_plan_model.freezed.dart';
|
part 'chosen_plan_model.freezed.dart';
|
||||||
@@ -7,6 +8,7 @@ part 'chosen_plan_model.g.dart';
|
|||||||
|
|
||||||
@freezed
|
@freezed
|
||||||
abstract class ChosenPlanModel with _$ChosenPlanModel {
|
abstract class ChosenPlanModel with _$ChosenPlanModel {
|
||||||
|
const ChosenPlanModel._();
|
||||||
|
|
||||||
factory ChosenPlanModel({
|
factory ChosenPlanModel({
|
||||||
@JsonKey() required int id,
|
@JsonKey() required int id,
|
||||||
@@ -15,10 +17,24 @@ abstract class ChosenPlanModel with _$ChosenPlanModel {
|
|||||||
@JsonKey(name: 'last_state') required ChosenPlanStateEnum chosenPlanState,
|
@JsonKey(name: 'last_state') required ChosenPlanStateEnum chosenPlanState,
|
||||||
@JsonKey(name: 'chat_id') required String chatId,
|
@JsonKey(name: 'chat_id') required String chatId,
|
||||||
@JsonKey(name: 'consultant_id') required int consultantId,
|
@JsonKey(name: 'consultant_id') required int consultantId,
|
||||||
|
@JsonKey(name: 'personal_diet_name') String? personalDietName,
|
||||||
@JsonKey(name: 'plan') required PlanModel plan,
|
@JsonKey(name: 'plan') required PlanModel plan,
|
||||||
}) = _ChosenPlanModel;
|
}) = _ChosenPlanModel;
|
||||||
|
|
||||||
factory ChosenPlanModel.fromJson(Map<String, dynamic> json) => _$ChosenPlanModelFromJson(json);
|
factory ChosenPlanModel.fromJson(Map<String, dynamic> json) => _$ChosenPlanModelFromJson(json);
|
||||||
|
|
||||||
|
PacketOptions? get chosenOption {
|
||||||
|
switch (PlanOptionType.tryParse(optionType)) {
|
||||||
|
case PlanOptionType.options1:
|
||||||
|
return plan.packet1Options;
|
||||||
|
case PlanOptionType.options2:
|
||||||
|
return plan.packet2Options;
|
||||||
|
case PlanOptionType.options3:
|
||||||
|
return plan.packet3Options;
|
||||||
|
case null:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ChosenPlanModel? parseChosenPlan(dynamic json) {
|
ChosenPlanModel? parseChosenPlan(dynamic json) {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import 'package:dio/dio.dart';
|
|||||||
import 'package:easy_debounce/easy_debounce.dart';
|
import 'package:easy_debounce/easy_debounce.dart';
|
||||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||||
import 'package:eatvio_app/features/diets/repositories/diet_repository.dart';
|
import 'package:eatvio_app/features/diets/repositories/diet_repository.dart';
|
||||||
|
import 'package:eatvio_app/features/plans/enums/plan_option_type_enum.dart';
|
||||||
import 'package:eatvio_app/features/plans/models/chosen_plan_model.dart';
|
import 'package:eatvio_app/features/plans/models/chosen_plan_model.dart';
|
||||||
import 'package:eatvio_app/features/plans/presentation/cubit/about_plan_state.dart';
|
import 'package:eatvio_app/features/plans/presentation/cubit/about_plan_state.dart';
|
||||||
import 'package:eatvio_app/features/plans/repositories/plan_repository.dart';
|
import 'package:eatvio_app/features/plans/repositories/plan_repository.dart';
|
||||||
@@ -133,7 +134,7 @@ class AboutPlanCubit extends Cubit<AboutPlanState> {
|
|||||||
final slug = state.planModel?.slug;
|
final slug = state.planModel?.slug;
|
||||||
final optionIndex = state.chosenOptionIndex;
|
final optionIndex = state.chosenOptionIndex;
|
||||||
if (slug != null) {
|
if (slug != null) {
|
||||||
final optionName = _getOptionNameFromIndex(optionIndex);
|
final optionName = PlanOptionType.fromIndex(optionIndex).apiValue;
|
||||||
final body = {'options_type': optionName};
|
final body = {'options_type': optionName};
|
||||||
return (await planRepository.chosePlan(slug, body), null);
|
return (await planRepository.chosePlan(slug, body), null);
|
||||||
}
|
}
|
||||||
@@ -181,10 +182,4 @@ class AboutPlanCubit extends Cubit<AboutPlanState> {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
String _getOptionNameFromIndex(int index) => switch (index) {
|
|
||||||
1 => 'options2',
|
|
||||||
2 => 'options3',
|
|
||||||
_ => 'options1',
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,10 @@ class ProfileCubit extends Cubit<ProfileState> {
|
|||||||
/// Bottom-nav / own profile instance, used to refresh posts after create/update/delete.
|
/// Bottom-nav / own profile instance, used to refresh posts after create/update/delete.
|
||||||
static ProfileCubit? myProfileCubit;
|
static ProfileCubit? myProfileCubit;
|
||||||
|
|
||||||
|
static void clearMyProfileReference() {
|
||||||
|
myProfileCubit = null;
|
||||||
|
}
|
||||||
|
|
||||||
ProfileCubit({required this.profileRepository, required this.chatRepository, required this.consultantRepository}) : super(const ProfileState.loading());
|
ProfileCubit({required this.profileRepository, required this.chatRepository, required this.consultantRepository}) : super(const ProfileState.loading());
|
||||||
|
|
||||||
Future<void> getProfileBySlug(String slug) async {
|
Future<void> getProfileBySlug(String slug) async {
|
||||||
@@ -141,13 +145,13 @@ class ProfileCubit extends Cubit<ProfileState> {
|
|||||||
|
|
||||||
Future<String?> getChatRoomIdBySlug({required String slug}) async {
|
Future<String?> getChatRoomIdBySlug({required String slug}) async {
|
||||||
try {
|
try {
|
||||||
final chatIdOrError = await chatRepository.getChatByUserSlug(slug);
|
final chatId = await chatRepository.getChatByUserSlug(slug);
|
||||||
final userProfile = await profileRepository.getProfileBySlug(slug);
|
if (chatId == null || chatId.isEmpty) {
|
||||||
if (chatIdOrError == '404') {
|
final userProfile = await profileRepository.getProfileBySlug(slug);
|
||||||
AppRouter.navigatorKey.currentContext?.pushNamed('emptyChatScreen', extra: userProfile);
|
AppRouter.navigatorKey.currentContext?.pushNamed('emptyChatScreen', extra: userProfile);
|
||||||
} else {
|
} else {
|
||||||
AppRouter.navigatorKey.currentContext?.pushNamed('chatScreen', extra: {'uuid': chatIdOrError});
|
AppRouter.navigatorKey.currentContext?.pushNamed('chatScreen', extra: {'uuid': chatId});
|
||||||
return chatIdOrError;
|
return chatId;
|
||||||
}
|
}
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
await reportFrom(e, st, this);
|
await reportFrom(e, st, this);
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
import 'dart:developer';
|
import 'dart:developer';
|
||||||
|
|
||||||
import 'package:eatvio_app/core/app_router.dart';
|
import 'package:eatvio_app/core/app_router.dart';
|
||||||
import 'package:eatvio_app/core/firebase_api.dart';
|
|
||||||
import 'package:eatvio_app/core/locator_service.dart';
|
|
||||||
import 'package:eatvio_app/core/mixins/registration_date_cache_mixin.dart';
|
import 'package:eatvio_app/core/mixins/registration_date_cache_mixin.dart';
|
||||||
import 'package:eatvio_app/core/prefs.dart';
|
import 'package:eatvio_app/core/prefs.dart';
|
||||||
|
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||||
import 'package:eatvio_app/core/token_storage.dart';
|
import 'package:eatvio_app/core/token_storage.dart';
|
||||||
import 'package:eatvio_app/features/registration/models/user_registration_model.dart';
|
import 'package:eatvio_app/features/registration/models/user_registration_model.dart';
|
||||||
import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart';
|
import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart';
|
||||||
@@ -18,7 +16,8 @@ import 'package:go_router/go_router.dart';
|
|||||||
|
|
||||||
class RegistrationCubit extends Cubit<RegistrationState> with RegistrationDateCacheMixin {
|
class RegistrationCubit extends Cubit<RegistrationState> with RegistrationDateCacheMixin {
|
||||||
final RegistrationRepository registrationRepository;
|
final RegistrationRepository registrationRepository;
|
||||||
RegistrationCubit({required this.registrationRepository, required Prefs prefs})
|
final SessionLifecycleService sessionLifecycleService;
|
||||||
|
RegistrationCubit({required this.registrationRepository, required this.sessionLifecycleService, required Prefs prefs})
|
||||||
: super(
|
: super(
|
||||||
const RegistrationState(
|
const RegistrationState(
|
||||||
sheet: UserRegistrationSheet(
|
sheet: UserRegistrationSheet(
|
||||||
@@ -62,7 +61,7 @@ class RegistrationCubit extends Cubit<RegistrationState> with RegistrationDateCa
|
|||||||
state.sheet.copyWith(phone: state.sheet.phone.replaceAll(' ', '').replaceAll('(', '').replaceAll(')', ''), responseBody: '{}'),
|
state.sheet.copyWith(phone: state.sheet.phone.replaceAll(' ', '').replaceAll('(', '').replaceAll(')', ''), responseBody: '{}'),
|
||||||
);
|
);
|
||||||
await TokenStorage.saveTokenInStorage(token);
|
await TokenStorage.saveTokenInStorage(token);
|
||||||
await sl<FirebaseApi>().registerPushToken();
|
await sessionLifecycleService.onAuthenticated();
|
||||||
RegistrationAnalyticsService.reportRegistrationComplete();
|
RegistrationAnalyticsService.reportRegistrationComplete();
|
||||||
cacheRegistrationDate(DateTime.now());
|
cacheRegistrationDate(DateTime.now());
|
||||||
AppRouter.navigatorKey.currentContext?.replaceNamed('verifyEmailScreen');
|
AppRouter.navigatorKey.currentContext?.replaceNamed('verifyEmailScreen');
|
||||||
|
|||||||
@@ -15,7 +15,11 @@ import 'package:flutter_bloc/flutter_bloc.dart';
|
|||||||
import 'package:go_router/go_router.dart';
|
import 'package:go_router/go_router.dart';
|
||||||
|
|
||||||
class VerifyEmailScreen extends StatefulWidget {
|
class VerifyEmailScreen extends StatefulWidget {
|
||||||
const VerifyEmailScreen({super.key});
|
const VerifyEmailScreen({super.key, this.returnOnSuccess = false});
|
||||||
|
|
||||||
|
/// Вернуться на предыдущий экран вместо перехода в ленту после подтверждения.
|
||||||
|
/// Используется, когда экран открыт из публичного действия (пост, лайк, комментарий).
|
||||||
|
final bool returnOnSuccess;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<VerifyEmailScreen> createState() => _VerifyEmailScreenState();
|
State<VerifyEmailScreen> createState() => _VerifyEmailScreenState();
|
||||||
@@ -89,7 +93,12 @@ class _VerifyEmailScreenState extends State<VerifyEmailScreen> {
|
|||||||
_startTimer();
|
_startTimer();
|
||||||
} else if (state is VerifyEmailStateVerifySuccess) {
|
} else if (state is VerifyEmailStateVerifySuccess) {
|
||||||
showSuccessToast('Почта успешно подтверждена');
|
showSuccessToast('Почта успешно подтверждена');
|
||||||
goRouter.pushNamed('feedScreen');
|
if (widget.returnOnSuccess) {
|
||||||
|
// Экран открыт из публичного действия — возвращаемся назад с результатом.
|
||||||
|
goRouter.pop(true);
|
||||||
|
} else {
|
||||||
|
goRouter.pushNamed('feedScreen');
|
||||||
|
}
|
||||||
} else if (state is VerifyEmailStateVerifyError) {
|
} else if (state is VerifyEmailStateVerifyError) {
|
||||||
showErrorToast("Неверный код. Попробуйте снова.");
|
showErrorToast("Неверный код. Попробуйте снова.");
|
||||||
for (var controller in _controllers) {
|
for (var controller in _controllers) {
|
||||||
@@ -166,18 +175,20 @@ class _VerifyEmailScreenState extends State<VerifyEmailScreen> {
|
|||||||
},
|
},
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
CustomOutlinedButton(
|
// При переходе из публичного действия уйти без подтверждения нельзя.
|
||||||
text: 'Позже',
|
if (!widget.returnOnSuccess)
|
||||||
height: 52,
|
CustomOutlinedButton(
|
||||||
buttonTextStyle: TextStyles.textMSemibold.copyWith(color: appTheme.black900),
|
text: 'Позже',
|
||||||
buttonStyle: ButtonStyle(
|
height: 52,
|
||||||
side: const WidgetStatePropertyAll(BorderSide.none),
|
buttonTextStyle: TextStyles.textMSemibold.copyWith(color: appTheme.black900),
|
||||||
backgroundColor: WidgetStatePropertyAll(appTheme.gray.withValues(alpha: 0.1)),
|
buttonStyle: ButtonStyle(
|
||||||
|
side: const WidgetStatePropertyAll(BorderSide.none),
|
||||||
|
backgroundColor: WidgetStatePropertyAll(appTheme.gray.withValues(alpha: 0.1)),
|
||||||
|
),
|
||||||
|
onPressed: () {
|
||||||
|
context.read<VerifyEmailCubit>().skipVerification();
|
||||||
|
},
|
||||||
),
|
),
|
||||||
onPressed: () {
|
|
||||||
context.read<VerifyEmailCubit>().skipVerification();
|
|
||||||
},
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user