Author SHA1 Message Date
linfeng 43373bec54 更新主裁判 APP 的上传描述,添加构建时间戳 2026-07-29 18:47:23 +08:00
linfeng ac304b10f8 更新主裁判 APP 的启动页 2026-07-29 18:39:59 +08:00
linfeng df38ecee18 登录后清空输入框 2026-07-29 18:06:53 +08:00
linfeng 7faa8e5c47 更新获取赛事列表功能,增加 NAS IP 地址参数以支持动态请求 2026-07-29 18:00:45 +08:00
linfeng 7d65be0514 选手赛项列表增加 选手与该赛项的选手编号属性 2026-07-29 11:51:11 +08:00
linfeng 40799f2d15 扫码页支持返回上一页 2026-07-29 10:13:47 +08:00
linfeng f7f7413b55 优化扫码页 UI 2026-07-28 18:50:14 +08:00
linfeng 8e599f5a86 完成视频播放UI 调整 2026-07-28 18:02:40 +08:00
linfeng 9fca76f679 1.完成查看录像模块功能
2.完成录像页面播放视频功能
2026-07-28 16:36:32 +08:00
linfeng a324825e8a update 2026-07-28 15:46:52 +08:00
linfeng 6793ca53af 还原参赛队伍列表页、详情页 2026-07-28 15:46:23 +08:00
linfeng 9e72bc522e 解决查看录像页 UI 2026-07-28 14:59:34 +08:00
linfeng 1096645e79 update git 湖绿 2026-07-28 12:04:28 +08:00
linfeng 13ecb2fccc 优化赛事信息页 UI 2026-07-28 10:12:13 +08:00
linfeng e3f9c8ebc0 优化团队赛页面 UI 2026-07-28 10:00:02 +08:00
linfeng 6790ea41b2 优化人工处理弹窗 UI 2026-07-28 09:30:24 +08:00
linfeng b2dd593e93 完成团队赛、 UI 开发 2026-07-27 18:41:20 +08:00
linfeng 5ffe524e20 完成选手信息页 2026-07-27 17:57:09 +08:00
linfeng 356636c4b4 解决解析 TOKEN 类型报错问题 2026-07-27 16:57:05 +08:00
linfeng 686db244fd 1.还原授权页 UI
2.还原扫码页 UI
2026-07-27 16:52:58 +08:00
linfeng 20d501f673 修改启动页 2026-07-27 15:45:06 +08:00
linfeng ddc1c9bf98 更换 APP 图标 2026-07-27 15:43:26 +08:00
linfeng 30d317c0b9 修改名字 2026-07-27 15:30:17 +08:00
linfeng 10d9eee60e 新增人工设置晋级/淘汰功能,更新相关数据模型和API接口;重构比赛页面以支持新逻辑,优化用户交互体验。 2026-07-23 15:35:31 +08:00
linfeng 00937bf4b6 更新比赛页面以传递新的事件注册项,简化数据处理逻辑并优化构建脚本。 2026-07-23 11:55:26 +08:00
linfeng 3c3baede85 移除比赛页面中的备注文本,优化UI布局以提升用户体验。 2026-07-23 11:48:07 +08:00
linfeng 8c127dd0e7 1.重构参赛队伍详情页面,更新数据模型以支持新结构;
2.优化比赛信息展示逻辑,增强用户交互体验;
3.修复API请求以获取队伍详情并处理异常情况。
2026-07-23 11:44:47 +08:00
linfeng 1264ebdd7c 重构参赛队伍相关模型,更新API接口以支持队伍详情获取;
调整UI逻辑以使用新的数据结构,优化比赛信息展示;
更新构建脚本以支持新功能。
2026-07-22 13:35:53 +08:00
linfeng d6e80df5bf 新增网络可视化请求工具 2026-07-22 09:24:48 +08:00
linfeng 4ff93edaab 授权页增加获取设备码 2026-07-21 22:45:41 +08:00
linfeng 1f0e0407ab 修复口令过期处理并增加参赛队伍接口 2026-07-20 10:52:19 +08:00
linfeng da52dc9797 Handle zero opponent IDs and hide video button 2026-07-20 10:23:44 +08:00
linfeng e5b6246458 更新应用配置以添加主裁判计分 H5 链接;
重构事件注册模型以支持团队成员信息,并简化事件信息页面的导航逻辑。
2026-07-20 10:10:51 +08:00
linfeng 4e0a675198 1.新增参赛队伍页面交互
2.新增人工处理功能交互
2026-07-20 09:29:53 +08:00
linfeng a4333d3bd1 解决华为 webview Chrome 78 内核版本渲染白屏问题 2026-07-17 15:22:57 +08:00
linfeng e08a8ed26b 重构事件信息页面,移除不必要的加载状态和错误消息字段,简化状态管理逻辑;在扫码页面中增强选手信息查询功能,添加加载提示和错误处理。 2026-07-17 15:17:08 +08:00
linfeng 62d717c3ee 更新build-apk-split.sh脚本以添加错误处理和构建完成时间输出;在ScanQrCodePage中增强玩家ID验证,添加无效凭证提示。 2026-07-17 12:19:57 +08:00
linfeng 1f9c5af51b 重构事件注册模型并更新应用配置。更改不同环境的基本url,增强事件注册项结构,并改进ScanQrCodePage中的导航。在AuthViewModel中添加clearAuth方法,以便更好地进行状态管理。 2026-07-17 11:55:13 +08:00
linfeng 831ca1059b Merge branch 'linfeng/drone_video/dev_1.1.0/20260707' into linfeng/drone_scoring/dev_1.1.0/2026630 2026-07-16 11:59:22 +08:00
linfeng 613bd90bad update 2026-07-16 11:58:58 +08:00
linfeng 9818a56fe1 删除单例测试文件 2026-07-16 11:58:43 +08:00
linfeng 16ad7b253c 添加 jwt_decoder 依赖;更新 AuthApi 枚举以支持获取录像列表;新增录像响应模型和相关状态管理;重构 AuthViewModel 以解析和存储 JWT 数据;更新 ScanQrCodePage 以处理用户鉴权和获取录像列表。 2026-07-14 10:16:31 +08:00
linfeng 45000b4188 update 2026-07-14 09:10:27 +08:00
linfeng fab49a9750 通过在扫描仪对话框中启用自动缩放和改进错误处理来重构QR码扫描功能。更新ScanQrCodePage以利用AppQrScannerDialog获取玩家ID。 2026-07-09 17:56:17 +08:00
linfeng 1c909277ff 更新 devtools_options.yaml 以启用 riverpod 和 shared_preferences 扩展;更新 AuthApi 枚举以添加 playerRegistrationList API;重构 Auth 页面以在用户已登录时直接导航到扫码页面;重构 EventInfoPage 以使用新的状态管理和加载赛事报名信息;更新扫码页面以导航到 EventInfoPage。 2026-07-09 17:38:56 +08:00
linfeng 6138eddc16 删除未使用的相机和记录类来重构记录功能;更新pubspec中的依赖项。Yaml为本地插件路径;简化MainActivity和相关类,以提高性能和可维护性。 2026-07-09 16:17:34 +08:00
linfeng 75c42ea168 新增赛事信息页 2026-07-09 14:57:09 +08:00
linfeng c38f6d69c8 更新 AuthApi 枚举以添加获取推流地址的 API 路径;重构 Auth 页面以优化输入控件和按钮布局;更新扫码页面以导航到录制页面。 2026-07-09 14:32:39 +08:00
linfeng 9766c43722 更新 .gitignore 文件以排除 AGENTS.md 和 test/ 目录;在 AGENTS.md 中添加页面级 Feature 目录规范;删除不再使用的 dialog-record.dart 文件,并更新相关引用路径。 2026-07-09 14:01:37 +08:00
linfeng a1f6ea14cf 添加设备代码信息到 Android 和 iOS 平台信息;更新 Auth 页面以使用新的 TextEditingController 管理输入;重构推流测试页面以支持动态 RTMP URL 解析;删除不再需要的测试文件。 2026-07-09 12:26:41 +08:00
linfeng 98a3381716 更新 AndroidManifest.xml 以启用明文流量;在 index.html 中替换 token 值
增强 WebviewPage 的清理和导航功能。
2026-07-09 10:10:53 +08:00
linfeng bd5937f910 添加 HTML 资源路径到 pubspec.yaml;更新 Auth 页面以使用新的 Webview 组件加载本地 HTML 文件;重构 WebviewPage 以支持加载本地资产和注入 JavaScript 通信桥接;清理不必要的导入和注释。 2026-07-08 12:03:25 +08:00
linfeng b21857f364 添加 apivideo_live_stream 依赖;
修改 Auth 页面文本为“输入执裁口令”;
添加公用 AppBar 组件
模拟核心流程交互
2026-07-08 09:37:38 +08:00
linfeng f6c477c9be 添加webview_flutter及相关依赖
添加公共的 webview 组件
2026-07-07 17:40:24 +08:00
linfeng 1246e41e4b 添加mobile_scanner包,
添加AuthPageWidget
添加全局扫码组件
2026-07-07 17:16:51 +08:00
linfeng 26574808df Merge branch 'linfeng/run/dev/20260630' into linfeng/drone/dev/2026630 2026-07-01 12:18:58 +08:00
linfeng d4c7d7180e 删除AndroidManifest.xml中的READ_MEDIA_VIDEO权限,并更新view_model_recording中的权限逻辑。dart确保文件保存权限仅适用于Android SDK版本28及以下。添加测试以验证Android 13和未知SDK版本的权限行为。 2026-07-01 12:18:12 +08:00
linfeng 4a85b9f83e Merge run recording updates into drone branch 2026-07-01 11:54:06 +08:00
linfeng e4057c3d6a 添加 CLAUDE.md 到 .gitignore 文件 2026-07-01 11:32:22 +08:00
linfeng 90e8966528 重构通道名称,在Android和iOS实现中使用统一的命名空间‘app.record_tool’。相应地更新相关的常量和方法通道。增强在录制HUD中的缩放比例显示格式。 2026-07-01 11:19:30 +08:00
linfeng c8a7494344 1.广角/主摄切换按钮已上移:
2.新增 isSwitchingLens 状态、避免切换镜头    stop 按钮禁用,不会触发 stopRecording
倍距按钮禁用,避免连续切换
ViewModel 层也兜底:isSwitchingLens=true 时直接拒绝 stop
3.合并失败兜底提示
2026-07-01 10:59:28 +08:00
linfeng 02614c2817 更新 .gitignore 文件以排除 CLAUDE.md,并注释掉录制头部小部件中的 mock 按钮 2026-07-01 10:38:50 +08:00
linfeng 9f49f73a31 删除 agent 说明书 2026-07-01 10:37:09 +08:00
linfeng da2e69b014 支持录制中切换广角/主摄 2026-07-01 09:59:21 +08:00
linfeng f6347e99cd 兼容 IOS 2026-06-30 17:28:03 +08:00
linfeng d40c13d802 兼容 IOS 2026-06-30 17:27:54 +08:00
linfeng 23319cfddb 修复部分机型无法切换广角和主摄功能 2026-06-30 17:06:35 +08:00
408 changed files with 102828 additions and 3929 deletions
+4
View File
@@ -48,3 +48,7 @@ app.*.map.json
/android/app/release
/android/.kotlin
CLAUDE.md
AGENTS.md
test/
script
+1 -7
View File
@@ -4,7 +4,7 @@ plugins {
id("dev.flutter.flutter-gradle-plugin")
}
val appPackageName = "com.run.sportsx"
val appPackageName = "com.dronex.rec"
android {
namespace = appPackageName
@@ -42,12 +42,6 @@ kotlin {
}
dependencies {
val cameraxVersion = "1.4.1"
implementation("androidx.camera:camera-core:$cameraxVersion")
implementation("androidx.camera:camera-camera2:$cameraxVersion")
implementation("androidx.camera:camera-lifecycle:$cameraxVersion")
implementation("androidx.camera:camera-video:$cameraxVersion")
implementation("androidx.camera:camera-view:$cameraxVersion")
implementation("androidx.lifecycle:lifecycle-service:2.8.7")
implementation("androidx.core:core-ktx:1.15.0")
}
+5 -5
View File
@@ -1,5 +1,5 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.run.sportsx">
package="com.dronex.rec">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
@@ -10,7 +10,6 @@
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28" />
@@ -20,9 +19,10 @@
android:required="true" />
<application
android:label="酷跑录像工作台"
android:label="SportsX裁判工作台"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
android:icon="@mipmap/ic_launcher"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:exported="true"
@@ -57,4 +57,4 @@
<data android:mimeType="text/plain" />
</intent>
</queries>
</manifest>
</manifest>
@@ -0,0 +1,10 @@
package com.dronex.rec
object AppConstants {
private const val CHANNEL_NAMESPACE = "app.record_tool"
const val PLATFORM_INFO_CHANNEL = "$CHANNEL_NAMESPACE/platform_info"
const val RECORDING_METHOD_CHANNEL = "$CHANNEL_NAMESPACE/recording"
const val RECORDING_EVENT_CHANNEL = "$CHANNEL_NAMESPACE/recording_events"
const val RECORDING_ACTION_START = "$CHANNEL_NAMESPACE.recording.START"
const val RECORDING_ACTION_STOP = "$CHANNEL_NAMESPACE.recording.STOP"
}
@@ -1,4 +1,4 @@
package com.run.sportsx
package com.dronex.rec
import android.content.Context
import android.content.pm.ApplicationInfo
@@ -6,9 +6,8 @@ import android.os.BatteryManager
import android.os.Build
import android.os.Environment
import android.os.StatFs
import androidx.camera.view.PreviewView
import com.run.sportsx.recording.RecordingPlatformHandler
import com.run.sportsx.recording.RecordingPreviewFactory
import android.provider.Settings
import com.dronex.rec.recording.RecordingPlatformHandler
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
@@ -17,15 +16,8 @@ class MainActivity : FlutterActivity() {
private var platformHandler: RecordingPlatformHandler? = null
private var platformInfoChannel: MethodChannel? = null
var recordingPreviewView: PreviewView? = null
private set
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
flutterEngine.platformViewsController.registry.registerViewFactory(
"recording-camera-preview",
RecordingPreviewFactory(this),
)
platformInfoChannel =
MethodChannel(
@@ -50,16 +42,6 @@ class MainActivity : FlutterActivity() {
)
}
fun attachRecordingPreview(previewView: PreviewView) {
recordingPreviewView = previewView
}
fun detachRecordingPreview(previewView: PreviewView? = null) {
if (previewView == null || recordingPreviewView === previewView) {
recordingPreviewView = null
}
}
override fun onDestroy() {
platformInfoChannel?.setMethodCallHandler(null)
platformInfoChannel = null
@@ -111,6 +93,7 @@ class MainActivity : FlutterActivity() {
return mapOf(
"platform" to "android",
"deviceCode" to Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID).orEmpty(),
"brand" to Build.BRAND,
"model" to Build.MODEL,
"systemVersion" to Build.VERSION.RELEASE,
@@ -1,4 +1,4 @@
package com.run.sportsx.recording
package com.dronex.rec.recording
import android.content.Context
import android.content.Intent
@@ -1,4 +1,4 @@
package com.run.sportsx.recording
package com.dronex.rec.recording
import android.app.NotificationManager
import android.content.Context
@@ -1,4 +1,4 @@
package com.run.sportsx.recording
package com.dronex.rec.recording
import android.app.Notification
import android.app.NotificationChannel
@@ -14,8 +14,8 @@ import android.os.PowerManager
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleService
import com.run.sportsx.AppConstants
import com.run.sportsx.MainActivity
import com.dronex.rec.AppConstants
import com.dronex.rec.MainActivity
class RecordingForegroundService : LifecycleService() {
private var wakeLock: PowerManager.WakeLock? = null
@@ -0,0 +1,66 @@
package com.dronex.rec.recording
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.dronex.rec.AppConstants
import com.dronex.rec.MainActivity
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class RecordingPlatformHandler(
private val activity: MainActivity,
messenger: BinaryMessenger,
) : MethodChannel.MethodCallHandler {
private val methodChannel = MethodChannel(messenger, AppConstants.RECORDING_METHOD_CHANNEL)
init {
methodChannel.setMethodCallHandler(this)
}
fun dispose() {
methodChannel.setMethodCallHandler(null)
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"hasNotificationPolicyAccess" -> result.success(DoNotDisturbHelper.hasAccess(activity))
"openNotificationPolicySettings" -> {
DoNotDisturbHelper.openAccessSettings(activity)
result.success(null)
}
"enableDoNotDisturb" -> result.success(DoNotDisturbHelper.enable(activity))
"disableDoNotDisturb" -> {
DoNotDisturbHelper.disable(activity)
result.success(null)
}
"isIgnoringBatteryOptimizations" ->
result.success(BatteryOptimizationHelper.isIgnoringOptimizations(activity))
"openBatteryOptimizationSettings" -> {
BatteryOptimizationHelper.openSettings(activity)
result.success(null)
}
"setImmersiveMode" -> {
val enabled = call.argument<Boolean>("enabled") ?: false
setImmersiveMode(enabled)
result.success(null)
}
"isForegroundServiceRunning" -> result.success(RecordingForegroundService.isRunning)
else -> result.notImplemented()
}
}
private fun setImmersiveMode(enabled: Boolean) {
val window = activity.window
WindowCompat.setDecorFitsSystemWindows(window, !enabled)
val insetsController = WindowInsetsControllerCompat(window, window.decorView)
if (enabled) {
insetsController.hide(WindowInsetsCompat.Type.systemBars())
insetsController.systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
} else {
insetsController.show(WindowInsetsCompat.Type.systemBars())
}
}
}
@@ -1,10 +0,0 @@
package com.run.sportsx
object AppConstants {
const val PACKAGE_NAME = "com.run.sportsx"
const val PLATFORM_INFO_CHANNEL = "$PACKAGE_NAME/platform_info"
const val RECORDING_METHOD_CHANNEL = "$PACKAGE_NAME/recording"
const val RECORDING_EVENT_CHANNEL = "$PACKAGE_NAME/recording_events"
const val RECORDING_ACTION_START = "$PACKAGE_NAME.recording.START"
const val RECORDING_ACTION_STOP = "$PACKAGE_NAME.recording.STOP"
}
@@ -1,873 +0,0 @@
package com.run.sportsx.recording
import android.content.Context
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CaptureRequest
import android.os.Build
import android.util.Log
import androidx.camera.camera2.interop.Camera2CameraControl
import androidx.camera.camera2.interop.Camera2CameraInfo
import androidx.camera.camera2.interop.CaptureRequestOptions
import androidx.camera.camera2.interop.ExperimentalCamera2Interop
import androidx.camera.core.Camera
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.video.Quality
import androidx.camera.video.QualitySelector
import androidx.camera.video.Recorder
import androidx.camera.video.Recording
import androidx.camera.video.VideoCapture
import androidx.camera.video.VideoRecordEvent
import androidx.camera.view.PreviewView
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import java.util.concurrent.Executor
import kotlin.math.atan
import kotlin.math.round
class RecordingCameraController(
private val appContext: Context,
) {
private val mainExecutor: Executor = ContextCompat.getMainExecutor(appContext)
private var cameraProvider: ProcessCameraProvider? = null
private var preview: Preview? = null
private var videoCapture: VideoCapture<Recorder>? = null
private var camera: Camera? = null
private var mainCameraId: String? = null
private var ultraWideCameraId: String? = null
private var ultraWideZoomRatio: Float = DEFAULT_ULTRA_WIDE_ZOOM_RATIO
private var currentLensMode: LensMode = LensMode.MAIN
private var activeRecording: Recording? = null
private var boundLifecycleOwner: LifecycleOwner? = null
private var currentZoomRatio: Float = 1f
var status: RecordingStatus = RecordingStatus(RecordingState.IDLE)
private set
var statusListener: ((RecordingStatus) -> Unit)? = null
private var recordingStartedAt: Long = 0L
private var latestOutputPath: String? = null
private var pendingStopCallback: ((String?) -> Unit)? = null
fun bindPreview(
lifecycleOwner: LifecycleOwner,
previewView: PreviewView,
onReady: (Boolean) -> Unit,
) {
val future = ProcessCameraProvider.getInstance(appContext)
future.addListener(
{
try {
val provider = future.get()
cameraProvider = provider
boundLifecycleOwner = lifecycleOwner
preview =
Preview.Builder().build().also {
it.surfaceProvider = previewView.surfaceProvider
}
val recorder =
Recorder.Builder()
.setQualitySelector(QualitySelector.from(Quality.HD))
.build()
videoCapture = VideoCapture.withOutput(recorder)
discoverBackCameras(provider)
bindUseCases(provider, lifecycleOwner, selectorForCurrentLensMode())
applyCurrentZoom()
updateStatus(RecordingStatus(RecordingState.PREVIEWING))
onReady(true)
} catch (error: Exception) {
Log.e(TAG, "bindPreview failed", error)
updateStatus(
RecordingStatus(
RecordingState.ERROR,
message = error.message,
),
)
onReady(false)
}
},
mainExecutor,
)
}
fun rebindForRecording(
lifecycleOwner: LifecycleOwner,
previewView: PreviewView,
onReady: (Boolean) -> Unit,
) {
val provider = cameraProvider
if (provider == null) {
bindPreview(lifecycleOwner, previewView, onReady)
return
}
if (
boundLifecycleOwner === lifecycleOwner &&
preview != null &&
videoCapture != null
) {
onReady(true)
return
}
try {
boundLifecycleOwner = lifecycleOwner
bindUseCases(provider, lifecycleOwner, selectorForCurrentLensMode())
applyCurrentZoom()
onReady(true)
} catch (error: Exception) {
Log.e(TAG, "rebindForRecording failed", error)
onReady(false)
}
}
fun startRecording(
withAudio: Boolean,
displayName: String?,
onStarted: (Boolean, String?) -> Unit,
) {
val capture = videoCapture
if (capture == null || boundLifecycleOwner == null) {
onStarted(false, "Camera not ready")
return
}
if (activeRecording != null) {
onStarted(false, "Already recording")
return
}
val outputOptions =
RecordingOutputFactory.buildMediaStoreOutputOptions(
appContext,
displayName,
)
latestOutputPath = null
val pending =
capture.output.prepareRecording(appContext, outputOptions).apply {
if (withAudio) {
val granted =
ContextCompat.checkSelfPermission(
appContext,
android.Manifest.permission.RECORD_AUDIO,
) == android.content.pm.PackageManager.PERMISSION_GRANTED
if (granted) {
withAudioEnabled()
}
}
}
recordingStartedAt = System.currentTimeMillis()
updateStatus(
RecordingStatus(
RecordingState.RECORDING,
outputPath = latestOutputPath,
),
)
activeRecording =
pending.start(mainExecutor) { event ->
when (event) {
is VideoRecordEvent.Start -> Unit
is VideoRecordEvent.Finalize -> {
activeRecording = null
if (event.hasError()) {
updateStatus(
RecordingStatus(
RecordingState.ERROR,
message = event.cause?.message
?: "Recording failed",
),
)
} else {
latestOutputPath = event.outputResults.outputUri.toString()
updateStatus(
RecordingStatus(
RecordingState.PREVIEWING,
outputPath = latestOutputPath,
elapsedMillis =
System.currentTimeMillis() -
recordingStartedAt,
),
)
}
val stopCallback = pendingStopCallback
pendingStopCallback = null
stopCallback?.invoke(latestOutputPath)
}
}
}
onStarted(true, latestOutputPath ?: "recording")
}
fun stopRecording(onStopped: (String?) -> Unit) {
val recording = activeRecording
if (recording == null) {
onStopped(latestOutputPath)
return
}
pendingStopCallback = onStopped
updateStatus(
RecordingStatus(
RecordingState.STOPPING,
outputPath = latestOutputPath,
),
)
recording.stop()
activeRecording = null
}
fun zoomCapabilitiesMap(): Map<String, Any> {
val zoomState = camera?.cameraInfo?.zoomState?.value
val cameraXMin = zoomState?.minZoomRatio ?: 1f
val cameraXMax = zoomState?.maxZoomRatio ?: 3f
val camera2Range = mainCameraZoomRatioRange()
val logicalMin = camera2Range?.lower?.let { minOf(cameraXMin, it) } ?: cameraXMin
val logicalMax = camera2Range?.upper?.let { maxOf(cameraXMax, it) } ?: cameraXMax
val minZoom =
if (hasUltraWideCamera()) {
minOf(ultraWideZoomRatio, logicalMin)
} else {
logicalMin
}
val maxZoom = logicalMax
val zoom =
if (currentLensMode == LensMode.ULTRA_WIDE) {
ultraWideZoomRatio
} else {
(zoomState?.zoomRatio ?: currentZoomRatio).coerceIn(minZoom, maxZoom)
}
currentZoomRatio = zoom
Log.d(
TAG,
"zoomCapabilities hasUltraWide=${hasUltraWideCamera()} cameraXMin=$cameraXMin " +
"cameraXMax=$cameraXMax camera2Range=${camera2Range?.description()} " +
"ultraWideZoomRatio=$ultraWideZoomRatio minZoom=$minZoom maxZoom=$maxZoom zoom=$zoom",
)
return mapOf(
"zoomRatio" to zoom.toDouble(),
"minZoomRatio" to minZoom.toDouble(),
"maxZoomRatio" to maxZoom.toDouble(),
)
}
fun setZoomRatio(
ratio: Double,
onComplete: (Boolean, Map<String, Any>, String?) -> Unit,
) {
val boundCamera = camera
if (boundCamera == null) {
val clamped =
if (ratio < 1.0 && hasUltraWideCamera()) {
ultraWideZoomRatio
} else {
ratio.toFloat().coerceAtLeast(1f)
}
currentZoomRatio = clamped
onComplete(true, zoomCapabilitiesMap(), null)
return
}
if (ratio < 1.0 && hasUltraWideCamera()) {
val logicalRange = mainCameraZoomRatioRange()
if (logicalRange == null || !logicalRange.contains(ratio.toFloat())) {
switchToUltraWide(onComplete)
return
}
}
if (currentLensMode == LensMode.ULTRA_WIDE) {
switchToMainAndZoom(ratio, onComplete)
return
}
val zoomState = boundCamera.cameraInfo.zoomState.value
val camera2Range = mainCameraZoomRatioRange()
val minZoom = camera2Range?.lower ?: zoomState?.minZoomRatio ?: 1f
val maxZoom = camera2Range?.upper ?: zoomState?.maxZoomRatio ?: clampedMaxZoom()
val nextZoom = ratio.toFloat().coerceIn(minZoom, maxZoom)
currentZoomRatio = nextZoom
val future =
if (
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
camera2Range?.contains(nextZoom) == true
) {
applyCamera2ZoomRatio(boundCamera, nextZoom)
} else {
boundCamera.cameraControl.setZoomRatio(nextZoom)
}
future.addListener(
{
try {
future.get()
onComplete(true, zoomCapabilitiesMap(), null)
} catch (error: Exception) {
Log.e(TAG, "setZoomRatio failed", error)
onComplete(false, zoomCapabilitiesMap(), error.message)
}
},
mainExecutor,
)
}
fun unbind() {
activeRecording?.stop()
activeRecording = null
cameraProvider?.unbindAll()
cameraProvider = null
preview = null
videoCapture = null
camera = null
boundLifecycleOwner = null
currentLensMode = LensMode.MAIN
currentZoomRatio = 1f
ultraWideZoomRatio = DEFAULT_ULTRA_WIDE_ZOOM_RATIO
updateStatus(RecordingStatus(RecordingState.IDLE))
}
fun elapsedMillis(): Long {
if (status.state != RecordingState.RECORDING) return 0L
return System.currentTimeMillis() - recordingStartedAt
}
private fun updateStatus(next: RecordingStatus) {
status = next
statusListener?.invoke(next)
}
private fun applyCurrentZoom() {
val boundCamera = camera ?: return
if (currentLensMode == LensMode.ULTRA_WIDE) {
currentZoomRatio = ultraWideZoomRatio
boundCamera.cameraControl.setZoomRatio(1f)
return
}
val zoomState = boundCamera.cameraInfo.zoomState.value
val camera2Range = mainCameraZoomRatioRange()
val minZoom = camera2Range?.lower ?: zoomState?.minZoomRatio ?: 1f
val maxZoom = camera2Range?.upper ?: zoomState?.maxZoomRatio ?: clampedMaxZoom()
currentZoomRatio = currentZoomRatio.coerceIn(minZoom, maxZoom)
if (
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
camera2Range?.contains(currentZoomRatio) == true
) {
applyCamera2ZoomRatio(boundCamera, currentZoomRatio)
} else {
boundCamera.cameraControl.setZoomRatio(currentZoomRatio)
}
}
private fun clampedMaxZoom(): Float {
return camera?.cameraInfo?.zoomState?.value?.maxZoomRatio ?: 3f
}
private fun discoverBackCameras(provider: ProcessCameraProvider) {
val manager = appContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager
if (mainCameraId == null) {
mainCameraId = cameraIdForSelector(provider, CameraSelector.DEFAULT_BACK_CAMERA)
}
logPublicCameraDiagnostics(provider, manager, mainCameraId)
val ultraWideCamera = findUltraWideCamera(provider, mainCameraId)
ultraWideCameraId = ultraWideCamera?.cameraId
ultraWideZoomRatio = ultraWideCamera?.zoomRatio ?: DEFAULT_ULTRA_WIDE_ZOOM_RATIO
if (ultraWideCamera == null && currentLensMode == LensMode.ULTRA_WIDE) {
currentLensMode = LensMode.MAIN
currentZoomRatio = 1f
}
Log.d(
TAG,
"mainCameraId=$mainCameraId ultraWideCameraId=$ultraWideCameraId " +
"ultraWideZoomRatio=$ultraWideZoomRatio",
)
}
private fun cameraIdForSelector(
provider: ProcessCameraProvider,
selector: CameraSelector,
): String? {
return try {
val infos = selector.filter(provider.availableCameraInfos)
infos.firstOrNull()?.let { Camera2CameraInfo.from(it).cameraId }
} catch (error: Exception) {
Log.w(TAG, "cameraIdForSelector failed", error)
null
}
}
private fun findUltraWideCamera(
provider: ProcessCameraProvider,
excludedCameraId: String?,
): UltraWideCamera? {
val manager = appContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager
val candidates =
manager.cameraIdList
.mapNotNull { cameraId -> backCameraProfile(manager, cameraId) }
.onEach { profile ->
Log.d(
TAG,
"backCamera ${profile.description()} " +
"bindable=${provider.hasCameraSafely(selectorForCameraId(profile.cameraId))}",
)
}
.filter { it.cameraId != excludedCameraId }
.filter { provider.hasCameraSafely(selectorForCameraId(it.cameraId)) }
.sortedWith(
compareByDescending<CameraProfile> { it.horizontalFov }
.thenBy { it.minFocalLength },
)
val mainProfile = excludedCameraId?.let { backCameraProfile(manager, it) }
val widest =
candidates.firstOrNull()
?: run {
logPhysicalOnlyUltraWideDiagnostics(manager, mainProfile, excludedCameraId)
return null
}
val candidatesDesc =
candidates.joinToString { it.description() }
val mainDesc =
mainProfile?.description()
Log.d(TAG, "ultraWide candidates=[$candidatesDesc] main=$mainDesc")
if (mainProfile == null) {
return UltraWideCamera(widest.cameraId, DEFAULT_ULTRA_WIDE_ZOOM_RATIO)
}
val meaningfullyWider =
widest.horizontalFov > mainProfile.horizontalFov * ULTRA_WIDE_FOV_FACTOR ||
widest.minFocalLength < mainProfile.minFocalLength * ULTRA_WIDE_FOCAL_FACTOR
Log.d(
TAG,
"ultraWide decision widest=${widest.cameraId} meaningfullyWider=$meaningfullyWider " +
"(fovFactor=$ULTRA_WIDE_FOV_FACTOR focalFactor=$ULTRA_WIDE_FOCAL_FACTOR)",
)
if (!meaningfullyWider) {
logPhysicalOnlyUltraWideDiagnostics(manager, mainProfile, excludedCameraId)
return null
}
return UltraWideCamera(widest.cameraId, estimateUltraWideZoomRatio(widest, mainProfile))
}
private fun logPublicCameraDiagnostics(
provider: ProcessCameraProvider,
manager: CameraManager,
mainCameraId: String?,
) {
Log.d(TAG, "publicCameraIds=[${manager.cameraIdList.joinToString()}] mainCameraId=$mainCameraId")
manager.cameraIdList.forEach { cameraId ->
try {
val characteristics = manager.getCameraCharacteristics(cameraId)
val bindable = provider.hasCameraSafely(selectorForCameraId(cameraId))
val physicalIds = physicalCameraIds(characteristics)
Log.d(
TAG,
"publicCamera id=$cameraId facing=${lensFacingDescription(characteristics)} " +
"physicalIds=[${physicalIds.joinToString()}] " +
"capabilities=[${capabilitiesDescription(characteristics)}] " +
"zoomRange=${zoomRatioRangeFromCharacteristics(characteristics)?.description()} " +
"focals=${focalLengthsDescription(characteristics)} " +
"sensor=${sensorSizeDescription(characteristics)} bindable=$bindable",
)
if (cameraId == mainCameraId) {
logMainPhysicalCameraDiagnostics(manager, cameraId, physicalIds)
}
} catch (error: Exception) {
Log.w(TAG, "publicCamera diagnostics failed for cameraId=$cameraId", error)
}
}
}
private fun logMainPhysicalCameraDiagnostics(
manager: CameraManager,
mainCameraId: String,
physicalIds: Set<String>,
) {
Log.d(TAG, "mainCamera id=$mainCameraId physicalIds=[${physicalIds.joinToString()}]")
physicalIds.forEach { physicalId ->
try {
val characteristics = manager.getCameraCharacteristics(physicalId)
Log.d(
TAG,
"mainPhysicalCamera id=$physicalId facing=${lensFacingDescription(characteristics)} " +
"zoomRange=${zoomRatioRangeFromCharacteristics(characteristics)?.description()} " +
"focals=${focalLengthsDescription(characteristics)} " +
"sensor=${sensorSizeDescription(characteristics)}",
)
} catch (error: Exception) {
Log.w(TAG, "mainPhysicalCamera diagnostics failed for physicalId=$physicalId", error)
}
}
}
private fun logPhysicalOnlyUltraWideDiagnostics(
manager: CameraManager,
mainProfile: CameraProfile?,
mainCameraId: String?,
) {
if (mainProfile == null || mainCameraId == null) {
return
}
val characteristics =
try {
manager.getCameraCharacteristics(mainCameraId)
} catch (error: Exception) {
Log.w(TAG, "physicalOnlyUltraWide diagnostics failed for mainCameraId=$mainCameraId", error)
return
}
val physicalProfiles =
physicalCameraIds(characteristics)
.mapNotNull { physicalId -> backCameraProfile(manager, physicalId) }
.filter { it.cameraId != mainCameraId }
.sortedBy { it.minFocalLength }
val widestPhysical = physicalProfiles.firstOrNull()
if (widestPhysical == null) {
Log.d(TAG, "physicalOnlyUltraWide none main=${mainProfile.description()}")
return
}
val meaningfullyWider =
widestPhysical.horizontalFov > mainProfile.horizontalFov * ULTRA_WIDE_FOV_FACTOR ||
widestPhysical.minFocalLength < mainProfile.minFocalLength * ULTRA_WIDE_FOCAL_FACTOR
Log.d(
TAG,
"physicalOnlyUltraWide widest=${widestPhysical.description()} " +
"main=${mainProfile.description()} meaningfullyWider=$meaningfullyWider " +
"exposedAsBindableCamera=false action=diagnostic_only",
)
}
private fun backCameraProfile(
manager: CameraManager,
cameraId: String,
): CameraProfile? {
return try {
val characteristics = manager.getCameraCharacteristics(cameraId)
val facing = characteristics.get(CameraCharacteristics.LENS_FACING)
if (facing != CameraCharacteristics.LENS_FACING_BACK) {
return null
}
val focalLengths =
characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS)
?: return null
val physicalSize =
characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE)
?: return null
val minFocalLength = focalLengths.minOrNull() ?: return null
val horizontalFov =
2.0 * atan((physicalSize.width / (2.0f * minFocalLength)).toDouble())
CameraProfile(
cameraId,
minFocalLength,
horizontalFov,
zoomRatioRangeFromCharacteristics(characteristics),
)
} catch (error: Exception) {
Log.w(TAG, "backCameraProfile failed for cameraId=$cameraId", error)
null
}
}
private fun mainCameraZoomRatioRange(): ZoomRatioRange? {
val cameraId = mainCameraId ?: activeCameraId()
return zoomRatioRangeForCamera(cameraId)
}
private fun activeCameraId(): String? {
val boundCamera = camera ?: return null
return try {
Camera2CameraInfo.from(boundCamera.cameraInfo).cameraId
} catch (error: Exception) {
null
}
}
private fun zoomRatioRangeForCamera(cameraId: String?): ZoomRatioRange? {
if (cameraId == null) return null
return try {
val manager = appContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager
zoomRatioRangeFromCharacteristics(manager.getCameraCharacteristics(cameraId))
} catch (error: Exception) {
Log.w(TAG, "zoomRatioRangeForCamera failed for cameraId=$cameraId", error)
null
}
}
private fun zoomRatioRangeFromCharacteristics(
characteristics: CameraCharacteristics,
): ZoomRatioRange? {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
return null
}
val range = characteristics.get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE)
?: return null
return ZoomRatioRange(range.lower, range.upper)
}
private fun physicalCameraIds(characteristics: CameraCharacteristics): Set<String> {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
return emptySet()
}
return characteristics.physicalCameraIds
}
private fun lensFacingDescription(characteristics: CameraCharacteristics): String {
return when (val facing = characteristics.get(CameraCharacteristics.LENS_FACING)) {
CameraCharacteristics.LENS_FACING_BACK -> "BACK"
CameraCharacteristics.LENS_FACING_FRONT -> "FRONT"
CameraCharacteristics.LENS_FACING_EXTERNAL -> "EXTERNAL"
null -> "null"
else -> "UNKNOWN($facing)"
}
}
private fun capabilitiesDescription(characteristics: CameraCharacteristics): String {
val capabilities =
characteristics.get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES)
?: return "null"
return capabilities.joinToString { capabilityDescription(it) }
}
private fun capabilityDescription(capability: Int): String {
return when (capability) {
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE ->
"BACKWARD_COMPATIBLE"
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR -> "MANUAL_SENSOR"
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_POST_PROCESSING ->
"MANUAL_POST_PROCESSING"
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW -> "RAW"
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_PRIVATE_REPROCESSING ->
"PRIVATE_REPROCESSING"
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_READ_SENSOR_SETTINGS ->
"READ_SENSOR_SETTINGS"
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_BURST_CAPTURE -> "BURST_CAPTURE"
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_YUV_REPROCESSING ->
"YUV_REPROCESSING"
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_DEPTH_OUTPUT -> "DEPTH_OUTPUT"
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO ->
"CONSTRAINED_HIGH_SPEED_VIDEO"
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MOTION_TRACKING -> "MOTION_TRACKING"
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_LOGICAL_MULTI_CAMERA ->
"LOGICAL_MULTI_CAMERA"
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME -> "MONOCHROME"
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_SECURE_IMAGE_DATA -> "SECURE_IMAGE_DATA"
else -> "UNKNOWN($capability)"
}
}
private fun focalLengthsDescription(characteristics: CameraCharacteristics): String {
val focalLengths =
characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS)
?: return "null"
return focalLengths.joinToString(prefix = "[", postfix = "]")
}
private fun sensorSizeDescription(characteristics: CameraCharacteristics): String {
val size = characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE)
?: return "null"
return "${size.width}x${size.height}"
}
private fun estimateUltraWideZoomRatio(
ultraWide: CameraProfile,
main: CameraProfile,
): Float {
if (main.minFocalLength <= 0f) {
return DEFAULT_ULTRA_WIDE_ZOOM_RATIO
}
val rawRatio = ultraWide.minFocalLength / main.minFocalLength
val roundedRatio = round(rawRatio * 10f) / 10f
return roundedRatio.coerceIn(MIN_ULTRA_WIDE_ZOOM_RATIO, MAX_ULTRA_WIDE_ZOOM_RATIO)
}
@androidx.annotation.OptIn(ExperimentalCamera2Interop::class)
private fun applyCamera2ZoomRatio(
boundCamera: Camera,
zoomRatio: Float,
) =
Camera2CameraControl.from(boundCamera.cameraControl)
.setCaptureRequestOptions(
CaptureRequestOptions.Builder()
.setCaptureRequestOption(
CaptureRequest.CONTROL_ZOOM_RATIO,
zoomRatio,
)
.build(),
)
private fun selectorForCurrentLensMode(): CameraSelector {
val cameraId =
if (currentLensMode == LensMode.ULTRA_WIDE) {
ultraWideCameraId
} else {
mainCameraId
}
return if (cameraId != null) {
selectorForCameraId(cameraId)
} else {
CameraSelector.DEFAULT_BACK_CAMERA
}
}
private fun selectorForCameraId(cameraId: String): CameraSelector {
return CameraSelector.Builder()
.addCameraFilter { cameraInfos ->
cameraInfos.filter { Camera2CameraInfo.from(it).cameraId == cameraId }
}
.build()
}
private fun bindUseCases(
provider: ProcessCameraProvider,
lifecycleOwner: LifecycleOwner,
selector: CameraSelector,
) {
val boundPreview = preview ?: throw IllegalStateException("Preview is not ready")
val boundVideoCapture =
videoCapture ?: throw IllegalStateException("Video capture is not ready")
provider.unbindAll()
camera =
provider.bindToLifecycle(
lifecycleOwner,
selector,
boundPreview,
boundVideoCapture,
)
}
private fun switchToUltraWide(
onComplete: (Boolean, Map<String, Any>, String?) -> Unit,
) {
val ultraWideId = ultraWideCameraId
if (ultraWideId == null) {
onComplete(false, zoomCapabilitiesMap(), "Ultra-wide camera is unavailable")
return
}
if (currentLensMode == LensMode.ULTRA_WIDE) {
currentZoomRatio = ultraWideZoomRatio
onComplete(true, zoomCapabilitiesMap(), null)
return
}
if (activeRecording != null) {
onComplete(false, zoomCapabilitiesMap(), "Cannot switch physical camera while recording")
return
}
val provider = cameraProvider
val lifecycleOwner = boundLifecycleOwner
if (provider == null || lifecycleOwner == null) {
onComplete(false, zoomCapabilitiesMap(), "Camera is not ready")
return
}
try {
currentLensMode = LensMode.ULTRA_WIDE
currentZoomRatio = ultraWideZoomRatio
bindUseCases(provider, lifecycleOwner, selectorForCameraId(ultraWideId))
applyCurrentZoom()
onComplete(true, zoomCapabilitiesMap(), null)
} catch (error: Exception) {
Log.e(TAG, "switchToUltraWide failed", error)
currentLensMode = LensMode.MAIN
currentZoomRatio = 1f
try {
bindUseCases(provider, lifecycleOwner, selectorForCurrentLensMode())
applyCurrentZoom()
} catch (restoreError: Exception) {
Log.e(TAG, "restore main camera after ultra-wide failure failed", restoreError)
}
onComplete(false, zoomCapabilitiesMap(), error.message)
}
}
private fun switchToMainAndZoom(
ratio: Double,
onComplete: (Boolean, Map<String, Any>, String?) -> Unit,
) {
if (activeRecording != null) {
onComplete(false, zoomCapabilitiesMap(), "Cannot switch physical camera while recording")
return
}
val provider = cameraProvider
val lifecycleOwner = boundLifecycleOwner
if (provider == null || lifecycleOwner == null) {
onComplete(false, zoomCapabilitiesMap(), "Camera is not ready")
return
}
try {
currentLensMode = LensMode.MAIN
currentZoomRatio = ratio.toFloat().coerceAtLeast(1f)
bindUseCases(provider, lifecycleOwner, selectorForCurrentLensMode())
setZoomRatio(ratio, onComplete)
} catch (error: Exception) {
Log.e(TAG, "switchToMainAndZoom failed", error)
onComplete(false, zoomCapabilitiesMap(), error.message)
}
}
private fun hasUltraWideCamera(): Boolean {
return ultraWideCameraId != null
}
private fun ProcessCameraProvider.hasCameraSafely(selector: CameraSelector): Boolean {
return try {
hasCamera(selector)
} catch (error: Exception) {
false
}
}
private enum class LensMode {
MAIN,
ULTRA_WIDE,
}
private data class CameraProfile(
val cameraId: String,
val minFocalLength: Float,
val horizontalFov: Double,
val zoomRatioRange: ZoomRatioRange?,
) {
fun description(): String {
return "id=$cameraId fov=$horizontalFov focal=$minFocalLength " +
"zoomRange=${zoomRatioRange?.description()}"
}
}
private data class ZoomRatioRange(
val lower: Float,
val upper: Float,
) {
fun contains(ratio: Float): Boolean {
return ratio >= lower && ratio <= upper
}
fun description(): String {
return "$lower..$upper"
}
}
private data class UltraWideCamera(
val cameraId: String,
val zoomRatio: Float,
)
companion object {
private const val TAG = "RecordingCamera"
private const val DEFAULT_ULTRA_WIDE_ZOOM_RATIO = 0.6f
private const val MIN_ULTRA_WIDE_ZOOM_RATIO = 0.3f
private const val MAX_ULTRA_WIDE_ZOOM_RATIO = 0.99f
// 适度放宽判定宽容度,覆盖更多机型(更小的 FOV/焦距差异也视为超广角)。
private const val ULTRA_WIDE_FOV_FACTOR = 1.04
private const val ULTRA_WIDE_FOCAL_FACTOR = 0.96
}
}
@@ -1,50 +0,0 @@
package com.run.sportsx.recording
import android.content.ContentValues
import android.content.Context
import android.os.Build
import android.provider.MediaStore
import androidx.camera.video.MediaStoreOutputOptions
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
object RecordingOutputFactory {
private const val RELATIVE_PATH = "Movies/酷跑录像工作台"
private const val MIME_TYPE = "video/mp4"
fun buildMediaStoreOutputOptions(
context: Context,
displayName: String?,
): MediaStoreOutputOptions {
val fileName = resolveFileName(displayName)
val contentValues =
ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, MIME_TYPE)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.Video.Media.RELATIVE_PATH, RELATIVE_PATH)
}
}
return MediaStoreOutputOptions.Builder(
context.contentResolver,
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
)
.setContentValues(contentValues)
.build()
}
fun resolveFileName(displayName: String?): String {
val trimmed = displayName?.trim().orEmpty()
if (trimmed.isNotEmpty()) {
return if (trimmed.lowercase(Locale.US).endsWith(".mp4")) {
trimmed
} else {
"$trimmed.mp4"
}
}
val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
return "REC_$timestamp.mp4"
}
}
@@ -1,255 +0,0 @@
package com.run.sportsx.recording
import android.os.Handler
import android.os.Looper
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.run.sportsx.AppConstants
import com.run.sportsx.MainActivity
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class RecordingPlatformHandler(
private val activity: MainActivity,
messenger: BinaryMessenger,
) : MethodChannel.MethodCallHandler, EventChannel.StreamHandler {
private val methodChannel = MethodChannel(messenger, AppConstants.RECORDING_METHOD_CHANNEL)
private val eventChannel = EventChannel(messenger, AppConstants.RECORDING_EVENT_CHANNEL)
private val mainHandler = Handler(Looper.getMainLooper())
private var eventSink: EventChannel.EventSink? = null
private var elapsedTicker: Runnable? = null
private val controller by lazy { RecordingSession.controller(activity.applicationContext) }
init {
methodChannel.setMethodCallHandler(this)
eventChannel.setStreamHandler(this)
controller.statusListener = { status ->
mainHandler.post { eventSink?.success(status.toMap()) }
}
}
fun dispose() {
stopElapsedTicker()
methodChannel.setMethodCallHandler(null)
eventChannel.setStreamHandler(null)
controller.statusListener = null
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"initializePreview" -> initializePreview(result)
"startRecording" -> {
val withAudio = call.argument<Boolean>("withAudio") ?: true
val enableDnd = call.argument<Boolean>("enableDoNotDisturb") ?: true
val displayName = call.argument<String>("displayName")
startRecording(withAudio, enableDnd, displayName, result)
}
"stopRecording" -> stopRecording(result)
"getZoomCapabilities" -> result.success(controller.zoomCapabilitiesMap())
"setZoomRatio" -> {
val ratio = call.argument<Double>("zoomRatio") ?: 1.0
setZoomRatio(ratio, result)
}
"disposePreview" -> {
controller.unbind()
result.success(null)
}
"hasNotificationPolicyAccess" -> result.success(DoNotDisturbHelper.hasAccess(activity))
"openNotificationPolicySettings" -> {
DoNotDisturbHelper.openAccessSettings(activity)
result.success(null)
}
"enableDoNotDisturb" -> result.success(DoNotDisturbHelper.enable(activity))
"disableDoNotDisturb" -> {
DoNotDisturbHelper.disable(activity)
result.success(null)
}
"isIgnoringBatteryOptimizations" ->
result.success(BatteryOptimizationHelper.isIgnoringOptimizations(activity))
"openBatteryOptimizationSettings" -> {
BatteryOptimizationHelper.openSettings(activity)
result.success(null)
}
"setImmersiveMode" -> {
val enabled = call.argument<Boolean>("enabled") ?: false
setImmersiveMode(enabled)
result.success(null)
}
"getStatus" -> result.success(controller.status.toMap())
"isForegroundServiceRunning" -> result.success(RecordingForegroundService.isRunning)
else -> result.notImplemented()
}
}
private fun initializePreview(result: MethodChannel.Result) {
val previewView = activity.recordingPreviewView
if (previewView == null) {
result.error("NO_PREVIEW", "Camera preview is not attached", null)
return
}
controller.bindPreview(activity, previewView) { ready ->
mainHandler.post {
if (ready) {
result.success(controller.status.toMap())
} else {
result.error("PREVIEW_FAILED", "Failed to bind camera preview", null)
}
}
}
}
private fun startRecording(
withAudio: Boolean,
enableDnd: Boolean,
displayName: String?,
result: MethodChannel.Result,
) {
val previewView = activity.recordingPreviewView
if (previewView == null) {
result.error("NO_PREVIEW", "Camera preview is not attached", null)
return
}
RecordingSession.startForeground(activity)
fun beginCapture() {
if (enableDnd && DoNotDisturbHelper.hasAccess(activity)) {
DoNotDisturbHelper.enable(activity)
}
controller.startRecording(withAudio, displayName) { started, message ->
mainHandler.post {
if (started) {
startElapsedTicker()
result.success(
mapOf(
"outputPath" to message,
"status" to controller.status.toMap(),
),
)
} else {
RecordingSession.stopForeground(activity)
DoNotDisturbHelper.disable(activity)
result.error("START_FAILED", message, null)
}
}
}
}
fun rebindAndCapture() {
val lifecycleOwner = RecordingForegroundService.instance ?: activity
controller.rebindForRecording(lifecycleOwner, previewView) { ready ->
if (ready) {
beginCapture()
} else {
RecordingSession.stopForeground(activity)
result.error("REBIND_FAILED", "Failed to bind camera for recording", null)
}
}
}
if (RecordingForegroundService.instance != null) {
rebindAndCapture()
} else {
mainHandler.post { rebindAndCapture() }
}
}
private fun stopRecording(result: MethodChannel.Result) {
stopElapsedTicker()
controller.stopRecording { path ->
RecordingSession.stopForeground(activity)
DoNotDisturbHelper.disable(activity)
val previewView = activity.recordingPreviewView
if (previewView == null) {
mainHandler.post { deliverStopResult(result, path) }
return@stopRecording
}
controller.rebindForRecording(activity, previewView) { _ ->
mainHandler.post { deliverStopResult(result, path) }
}
}
}
private fun setZoomRatio(ratio: Double, result: MethodChannel.Result) {
controller.setZoomRatio(ratio) { success, capabilities, message ->
mainHandler.post {
if (success) {
result.success(capabilities)
} else {
result.error("ZOOM_FAILED", message ?: "Failed to set camera zoom", null)
}
}
}
}
private fun deliverStopResult(result: MethodChannel.Result, path: String?) {
val fileSaved = path != null && controller.status.state != RecordingState.ERROR
val payload =
mutableMapOf<String, Any?>(
"outputPath" to path,
"status" to controller.status.toMap(),
"fileSaved" to fileSaved,
)
if (!fileSaved) {
payload["fileErrorMessage"] = controller.status.message ?: "保存到文件夹失败"
}
result.success(payload)
}
private fun setImmersiveMode(enabled: Boolean) {
val window = activity.window
WindowCompat.setDecorFitsSystemWindows(window, !enabled)
val insetsController = WindowInsetsControllerCompat(window, window.decorView)
if (enabled) {
insetsController.hide(WindowInsetsCompat.Type.systemBars())
insetsController.systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
} else {
insetsController.show(WindowInsetsCompat.Type.systemBars())
}
}
private fun startElapsedTicker() {
stopElapsedTicker()
elapsedTicker =
object : Runnable {
override fun run() {
if (controller.status.state == RecordingState.RECORDING) {
eventSink?.success(
controller
.status
.copy(
elapsedMillis =
controller.elapsedMillis(),
)
.toMap(),
)
mainHandler.postDelayed(this, 1000L)
}
}
}
.also { mainHandler.post(it) }
}
private fun stopElapsedTicker() {
elapsedTicker?.let { mainHandler.removeCallbacks(it) }
elapsedTicker = null
}
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
eventSink = events
events?.success(controller.status.toMap())
}
override fun onCancel(arguments: Any?) {
eventSink = null
stopElapsedTicker()
}
}
@@ -1,37 +0,0 @@
package com.run.sportsx.recording
import android.content.Context
import android.view.View
import androidx.camera.view.PreviewView
import com.run.sportsx.MainActivity
import io.flutter.plugin.common.StandardMessageCodec
import io.flutter.plugin.platform.PlatformView
import io.flutter.plugin.platform.PlatformViewFactory
class RecordingPreviewFactory(
private val activity: MainActivity,
) : PlatformViewFactory(StandardMessageCodec.INSTANCE) {
override fun create(context: Context, viewId: Int, args: Any?): PlatformView {
return RecordingPreviewPlatformView(activity)
}
}
class RecordingPreviewPlatformView(
private val activity: MainActivity,
) : PlatformView {
val previewView: PreviewView =
PreviewView(activity).apply {
implementationMode = PreviewView.ImplementationMode.COMPATIBLE
scaleType = PreviewView.ScaleType.FILL_CENTER
}
init {
activity.attachRecordingPreview(previewView)
}
override fun getView(): View = previewView
override fun dispose() {
activity.detachRecordingPreview(previewView)
}
}
@@ -1,30 +0,0 @@
package com.run.sportsx.recording
import android.content.Context
import androidx.lifecycle.LifecycleService
object RecordingSession {
private var cameraController: RecordingCameraController? = null
fun controller(context: Context): RecordingCameraController {
return cameraController
?: RecordingCameraController(context.applicationContext).also {
cameraController = it
}
}
fun release() {
cameraController?.unbind()
cameraController = null
}
fun startForeground(context: Context) {
RecordingForegroundService.start(context)
}
fun stopForeground(context: Context) {
RecordingForegroundService.stop(context)
}
fun recordingLifecycleOwner(): LifecycleService? = RecordingForegroundService.instance
}
@@ -1,24 +0,0 @@
package com.run.sportsx.recording
enum class RecordingState {
IDLE,
PREVIEWING,
RECORDING,
STOPPING,
ERROR,
}
data class RecordingStatus(
val state: RecordingState,
val outputPath: String? = null,
val elapsedMillis: Long = 0L,
val message: String? = null,
) {
fun toMap(): Map<String, Any?> =
mapOf(
"state" to state.name.lowercase(),
"outputPath" to outputPath,
"elapsedMillis" to elapsedMillis,
"message" to message,
)
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 256 KiB

After

Width:  |  Height:  |  Size: 382 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.4 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.9 KiB

After

Width:  |  Height:  |  Size: 9.9 KiB

+47
View File
@@ -0,0 +1,47 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.aa {
margin: 100px;
width: 200px;
height: 100px;
border-radius: 20px;
}
</style>
</head>
<body>
<button class="aa" onclick="postMsgToAPP()">向 APP 发送数据</button>
</body>
<script>
(function () {
if (window.__appInstallData) {
return;
}
window.__appInstallData = true;
window.AppBridge.token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjgxNDI4NTczNTY2NjY4ODAwLCJkYXRhIjp7fSwic3ViIjoiODE0Mjg1NzM1NjY2Njg4MDAiLCJleHAiOjE3ODM5MzM1ODQsIm5iZiI6MTc4MzMyODc4NCwiaWF0IjoxNzgzMzI4Nzg0fQ.r1wYfvpV-5HIgwUuvq1Or3jPgjc3AhfJmoV1PNP23-Y';
///TODO 后续业务
})();
function postMsgToAPP() {
window.AppBridge.postMessage(JSON.stringify({ type: 'navigator_pop', value: null }))
console.log(window.AppBridge.token)
console.log(window.AppBridge.playId)
}
</script>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 509 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 795 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1011 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 248 KiB

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 833 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 293 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 633 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 5.1 KiB

+8 -1
View File
@@ -1 +1,8 @@
flutter build apk --release --split-per-abi
#!/bin/sh
set -e
flutter build apk --release --split-per-abi
# echo "构建完成时间: $(date '+%Y-%m-%d %H:%M:%S')"
pgyer upload build/app/outputs/flutter-apk/app-arm64-v8a-release.apk --build-update-description "主裁判 APP $(date '+%Y-%m-%d %H:%M:%S')"
+2
View File
@@ -1,3 +1,5 @@
description: This file stores settings for Dart & Flutter DevTools.
documentation: https://docs.flutter.dev/tools/devtools/extensions#configure-extension-enablement-states
extensions:
- riverpod: true
- shared_preferences: true
+53
View File
@@ -1,9 +1,26 @@
PODS:
- apivideo_live_stream (0.0.1):
- ApiVideoLiveStream (= 1.4.1)
- Flutter
- ApiVideoLiveStream (1.4.1):
- HaishinKit (= 1.7.3)
- connectivity_plus (0.0.1):
- Flutter
- device_info_plus (0.0.1):
- Flutter
- Flutter (1.0.0)
- HaishinKit (1.7.3):
- Logboard (~> 2.4.1)
- Logboard (2.4.2)
- mobile_scanner (7.0.0):
- Flutter
- FlutterMacOS
- native_device_orientation (0.0.1):
- Flutter
- permission_handler_apple (9.4.8):
- Flutter
- share_plus (0.0.1):
- Flutter
- shared_preferences_foundation (0.0.1):
- Flutter
- FlutterMacOS
@@ -12,36 +29,72 @@ PODS:
- FlutterMacOS
- url_launcher_ios (0.0.1):
- Flutter
- webview_flutter_wkwebview (0.0.1):
- Flutter
- FlutterMacOS
DEPENDENCIES:
- apivideo_live_stream (from `.symlinks/plugins/apivideo_live_stream/ios`)
- connectivity_plus (from `.symlinks/plugins/connectivity_plus/ios`)
- device_info_plus (from `.symlinks/plugins/device_info_plus/ios`)
- Flutter (from `Flutter`)
- mobile_scanner (from `.symlinks/plugins/mobile_scanner/darwin`)
- native_device_orientation (from `.symlinks/plugins/native_device_orientation/ios`)
- permission_handler_apple (from `.symlinks/plugins/permission_handler_apple/ios`)
- share_plus (from `.symlinks/plugins/share_plus/ios`)
- shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`)
- sqflite_darwin (from `.symlinks/plugins/sqflite_darwin/darwin`)
- url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`)
- webview_flutter_wkwebview (from `.symlinks/plugins/webview_flutter_wkwebview/darwin`)
SPEC REPOS:
trunk:
- ApiVideoLiveStream
- HaishinKit
- Logboard
EXTERNAL SOURCES:
apivideo_live_stream:
:path: ".symlinks/plugins/apivideo_live_stream/ios"
connectivity_plus:
:path: ".symlinks/plugins/connectivity_plus/ios"
device_info_plus:
:path: ".symlinks/plugins/device_info_plus/ios"
Flutter:
:path: Flutter
mobile_scanner:
:path: ".symlinks/plugins/mobile_scanner/darwin"
native_device_orientation:
:path: ".symlinks/plugins/native_device_orientation/ios"
permission_handler_apple:
:path: ".symlinks/plugins/permission_handler_apple/ios"
share_plus:
:path: ".symlinks/plugins/share_plus/ios"
shared_preferences_foundation:
:path: ".symlinks/plugins/shared_preferences_foundation/darwin"
sqflite_darwin:
:path: ".symlinks/plugins/sqflite_darwin/darwin"
url_launcher_ios:
:path: ".symlinks/plugins/url_launcher_ios/ios"
webview_flutter_wkwebview:
:path: ".symlinks/plugins/webview_flutter_wkwebview/darwin"
SPEC CHECKSUMS:
apivideo_live_stream: caab45dd35fb3b140d423c099d0f6672378e7abe
ApiVideoLiveStream: 8f9dce7f6d15d5e4bb3c7a25e406bf2a36337a5a
connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7dd
device_info_plus: 21fcca2080fbcd348be798aa36c3e5ed849eefbe
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
HaishinKit: 326e27c4d06427ba53bffc68e516a92033293051
Logboard: 759d82599c439945d430d5a0958455b5a1974a0c
mobile_scanner: 9157936403f5a0644ca3779a38ff8404c5434a93
native_device_orientation: d6a4dc6887cd8a5ce1049962367aec60139ea0f1
permission_handler_apple: 92d754bbaa7361d436db2d6c3c1c2a0fdcec462e
share_plus: 50da8cb520a8f0f65671c6c6a99b3617ed10a58a
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b
webview_flutter_wkwebview: 8ebf4fded22593026f7dbff1fbff31ea98573c8d
PODFILE CHECKSUM: 858401fbd980bedce6ecd2f9b429bf271f11f74b
Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 761 B

After

Width:  |  Height:  |  Size: 976 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 256 KiB

After

Width:  |  Height:  |  Size: 262 KiB

+71 -71
View File
@@ -1,78 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>飞行极控录像工作台</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>飞行极控录像工作台</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSCameraUsageDescription</key>
<string>需要访问相机以显示预览并录制视频。</string>
<key>NSMicrophoneUsageDescription</key>
<string>需要访问麦克风以录制视频声音;未授权时将静音录制。</string>
<key>UIFileSharingEnabled</key>
<true/>
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>
<key>UIApplicationSceneManifest</key>
<dict>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true />
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>酷跑录像工作台</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>酷跑录像工作台</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true />
<key>NSCameraUsageDescription</key>
<string>需要访问相机以显示预览并录制视频。</string>
<key>NSMicrophoneUsageDescription</key>
<string>需要访问麦克风以录制视频声音;未授权时将静音录制。</string>
<key>UIFileSharingEnabled</key>
<true />
<key>LSSupportsOpeningDocumentsInPlace</key>
<true />
<key>UIApplicationSceneManifest</key>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</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>FlutterSceneDelegate</string>
<key>UISceneStoryboardFile</key>
<string>Main</string>
</dict>
</array>
</dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneClassName</key>
<string>UIWindowScene</string>
<key>UISceneConfigurationName</key>
<string>flutter</string>
<key>UISceneDelegateClassName</key>
<string>FlutterSceneDelegate</string>
<key>UISceneStoryboardFile</key>
<string>Main</string>
</dict>
</array>
</dict>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true />
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
+2 -1
View File
@@ -4,7 +4,7 @@ import UIKit
final class PlatformInfoPlugin: NSObject, FlutterPlugin {
static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(
name: "com.dronex.rec/platform_info",
name: "app.record_tool/platform_info",
binaryMessenger: registrar.messenger()
)
let plugin = PlatformInfoPlugin()
@@ -62,6 +62,7 @@ final class PlatformInfoPlugin: NSObject, FlutterPlugin {
let device = UIDevice.current
return [
"platform": "ios",
"deviceCode": "",
"brand": device.systemName,
"model": machineIdentifier(),
"systemVersion": device.systemVersion,
+3 -3
View File
@@ -633,9 +633,9 @@ private final class RecordingCameraController: NSObject, AVCaptureFileOutputReco
}
private enum RecordingChannelNames {
static let packageName = "com.dronex.rec"
static let method = "\(packageName)/recording"
static let events = "\(packageName)/recording_events"
static let namespace = "app.record_tool"
static let method = "\(namespace)/recording"
static let events = "\(namespace)/recording_events"
}
final class RecordingPlugin: NSObject, FlutterPlugin, FlutterStreamHandler {
+3 -33
View File
@@ -1,46 +1,16 @@
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:recording_tool/app/config/app_config.dart';
import 'package:recording_tool/app/router/app_navigator.dart';
import 'package:recording_tool/app/theme/app_theme.dart';
import 'package:recording_tool/features/recording/pages/page_record.dart';
import 'package:recording_tool/features/recording/view-model/view_model_recording.dart';
import 'package:recording_tool/features/auth/pages/page_auth.dart';
class FlutterTemplateApp extends ConsumerStatefulWidget {
class FlutterTemplateApp extends StatelessWidget {
const FlutterTemplateApp({super.key});
@override
ConsumerState<FlutterTemplateApp> createState() => _FlutterTemplateAppState();
}
class _FlutterTemplateAppState extends ConsumerState<FlutterTemplateApp>
with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
WidgetsBinding.instance.addPostFrameCallback((_) {
ref.read(recordingViewModelProvider.notifier).getClipboardContent();
});
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
ref.read(recordingViewModelProvider.notifier).getClipboardContent();
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
Widget build(BuildContext context) {
return ScreenUtilInit(
@@ -74,7 +44,7 @@ class _FlutterTemplateAppState extends ConsumerState<FlutterTemplateApp>
home: RefreshConfiguration(
enableLoadingWhenNoData: false,
headerTriggerDistance: 80.h,
child: const RecordingPage(),
child: const AuthPageWidget(),
),
);
},
+19 -1
View File
@@ -3,10 +3,14 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_ume/flutter_ume.dart';
import 'package:flutter_ume_kit_device/components/device_info/device_info_panel.dart';
import 'package:flutter_ume_kit_dio/flutter_ume_kit_dio.dart';
import 'package:recording_tool/app/app.dart';
import 'package:recording_tool/app/config/app_config.dart';
import 'package:recording_tool/core/cache/app_storage.dart';
import 'package:recording_tool/core/logging/app_logger.dart';
import 'package:recording_tool/core/network/app_dio.dart';
import 'package:recording_tool/core/platform/app_platform_info.dart';
class AppBootstrapper {
@@ -25,7 +29,21 @@ class AppBootstrapper {
AppLogger.debug('App started in ${AppConfig.current.environment.name}');
runApp(const ProviderScope(child: FlutterTemplateApp()));
// 注册 UME 调试插件(DioInspector 需与业务共用同一 Dio 实例)
PluginManager.instance
..register(DioInspector(dio: AppDio.instance))
..register(DeviceInfoPanel());
runApp(
UMEWidget(
enable: true,
child: Stack(
alignment: Alignment.center,
children: [const ProviderScope(child: FlutterTemplateApp())],
),
),
);
// runApp(const ProviderScope(child: FlutterTemplateApp()));
// Load native package metadata after the first frame can render.
// Awaiting MethodChannel calls before runApp() can stall the Android
+28
View File
@@ -0,0 +1,28 @@
enum AuthApi {
/// 获取 token
getToken('/api/events/device/token'),
/// 获取推流地址
getStreamKey('/api/events/device/stream/key'),
/// 根据赛事目录获取视频列表
getRecordList('/api/files'),
/// 获取参赛队伍列表
getTeamList('/api/events/device/item/group'),
/// 参赛队伍详情
getTeamDetail('/api/events/device/schedule/pending'),
/// 人工设置晋级/淘汰
setTeamStatus('/api/events/device/schedule/team/score'),
/// 获取登录设备信息
getLoginDeviceInfo('/api/events/device/nas/info'),
/// 获取选手的赛事信息
playerRegistrationList('/api/events/device/player/registration/list');
final String path;
const AuthApi(this.path);
}
+16 -5
View File
@@ -8,11 +8,13 @@ class EnvironmentValues {
required this.environment,
required this.baseUrl,
required this.enableNetworkLog,
this.mainRefereeScoreH5Url = '',
});
final AppEnvironment environment;
final String baseUrl;
final bool enableNetworkLog;
final String mainRefereeScoreH5Url;
}
class AppConfig {
@@ -21,8 +23,10 @@ class AppConfig {
static late EnvironmentValues current;
static AppPackageInfo? packageInfo;
static const appName = '酷跑录像工作台';
static const designSize = Size(375, 812);
static const appName = 'SportsX裁判工作台';
static const designSize = Size(640, 1024);
/// 主裁判计分 H5 链接
static void configure({
required AppEnvironment environment,
@@ -32,17 +36,24 @@ class AppConfig {
current = switch (environment) {
AppEnvironment.dev => const EnvironmentValues(
environment: AppEnvironment.dev,
baseUrl: 'https://example.com/api',
// baseUrl: 'http://192.168.1.104:8000',
baseUrl: 'https://apitest.dronex.cc',
mainRefereeScoreH5Url:
'https://drone.apptest.sportsx.cc/#/pages/h5/score-entry',
enableNetworkLog: true,
),
AppEnvironment.staging => const EnvironmentValues(
environment: AppEnvironment.staging,
baseUrl: 'https://example.com/api',
baseUrl: 'https://apitest.dronex.cc',
mainRefereeScoreH5Url:
'https://drone.apptest.sportsx.cc/#/pages/h5/score-entry',
enableNetworkLog: true,
),
AppEnvironment.prod => const EnvironmentValues(
environment: AppEnvironment.prod,
baseUrl: 'https://example.com/api',
baseUrl: 'https://api.dronex.cc',
mainRefereeScoreH5Url:
'https://drone.sportsx.cc/#/pages/h5/score-entry',
enableNetworkLog: false,
),
};
+1 -4
View File
@@ -103,10 +103,7 @@ class AppNavigator {
}
static void pop<T extends Object?>({BuildContext? context, T? result}) {
Navigator.of(
context ?? AppNavigator.context!,
rootNavigator: true,
).pop<T>(result);
Navigator.maybePop(context ?? AppNavigator.context!);
}
static void popTimes({BuildContext? context, int count = 1}) {
+18 -3
View File
@@ -38,11 +38,15 @@ class ApiClient {
return _parseData<T>(raw, parser);
}
if (raw is! Map<String, dynamic>) {
final payload = raw is Map ? Map<String, dynamic>.from(raw) : null;
if (payload == null ||
!(payload.containsKey('code') || payload.containsKey('message'))) {
return _parseData<T>(raw, parser);
}
final wrapped = ApiResponse<T>.fromJson(raw, fromJsonT: parser);
// 先按 {code,message,data} 解包,再用业务 parser 解析 data
// 避免把 Map 直接强转成业务模型。
final wrapped = ApiResponse<dynamic>.fromJson(payload);
if (!wrapped.isSuccess) {
throw ApiException(
code: wrapped.code,
@@ -52,7 +56,17 @@ class ApiClient {
);
}
return wrapped.data as T;
if (wrapped.data == null) {
if (null is T) return null as T;
throw ApiException(
code: wrapped.code,
statusCode: response.statusCode,
message: '响应 data 为空',
details: raw,
);
}
return _parseData<T>(wrapped.data, parser);
} on DioException catch (error) {
throw _mapDioException(error);
}
@@ -108,6 +122,7 @@ class ApiClient {
final statusCode = error.response?.statusCode;
final message = switch (error.type) {
DioExceptionType.connectionTimeout => '网络连接超时',
DioExceptionType.transformTimeout => '网络请求处理超时',
DioExceptionType.sendTimeout => '请求发送超时',
DioExceptionType.receiveTimeout => '响应接收超时',
DioExceptionType.badCertificate => '证书校验失败',
+18 -2
View File
@@ -5,16 +5,32 @@ class ApiResponse<T> {
final String message;
final T? data;
bool get isSuccess => code >= 200 && code < 300;
bool get isSuccess => code == 0 || code >= 200 && code < 300;
factory ApiResponse.fromJson(
Map<String, dynamic> json, {
T Function(dynamic json)? fromJsonT,
}) {
final rawData = json['data'];
T? data;
if (rawData != null && fromJsonT != null) {
data = fromJsonT(rawData);
} else if (rawData != null && fromJsonT == null) {
// 无 parser 时仅在类型已匹配时接收,避免 Map 被强转为业务模型。
if (rawData is T) {
data = rawData;
} else {
throw FormatException(
'ApiResponse data 类型不匹配,且未提供 fromJsonT;'
'期望 $T,实际 ${rawData.runtimeType}',
);
}
}
return ApiResponse<T>(
code: (json['code'] as num?)?.toInt() ?? 200,
message: (json['message'] ?? json['msg'] ?? '').toString(),
data: fromJsonT == null ? json['data'] as T? : fromJsonT(json['data']),
data: data,
);
}
}
+21
View File
@@ -0,0 +1,21 @@
import 'package:dio/dio.dart';
import 'package:recording_tool/app/config/app_config.dart';
/// 应用全局 Dio 单例,供业务请求与调试插件共用。
class AppDio {
AppDio._();
static Dio? _instance;
static Dio get instance {
return _instance ??= Dio(
BaseOptions(
baseUrl: AppConfig.current.baseUrl,
connectTimeout: const Duration(seconds: 30),
receiveTimeout: const Duration(seconds: 30),
sendTimeout: const Duration(seconds: 30),
responseType: ResponseType.json,
),
);
}
}
+16
View File
@@ -2,9 +2,12 @@ import 'dart:io';
import 'package:dio/dio.dart';
import 'package:recording_tool/app/config/app_config.dart';
import 'package:recording_tool/app/router/app_navigator.dart';
import 'package:recording_tool/core/cache/app_storage.dart';
import 'package:recording_tool/core/cache/storage_keys.dart';
import 'package:recording_tool/core/utils/device_utils.dart';
import 'package:recording_tool/features/auth/pages/page_auth.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';
class HeaderInterceptor extends Interceptor {
@override
@@ -28,4 +31,17 @@ class HeaderInterceptor extends Interceptor {
handler.next(options);
}
@override
Future<void> onError(
DioException err,
ErrorInterceptorHandler handler,
) async {
if (err.response?.statusCode == 401) {
await AppStorage.remove(StorageKeys.authToken);
AppToast.show('口令已过期,请重新输入执裁口令');
AppNavigator.pushAndRemoveUntil(AuthPageWidget());
}
handler.next(err);
}
}
+21 -21
View File
@@ -2,36 +2,36 @@ import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:recording_tool/app/config/app_config.dart';
import 'package:recording_tool/core/network/api_client.dart';
import 'package:recording_tool/core/network/app_dio.dart';
import 'package:recording_tool/core/network/header_interceptor.dart';
import 'package:recording_tool/core/network/offline_queue/offline_queue_interceptor.dart';
import 'package:recording_tool/core/network/providers/network_providers.dart';
import 'package:recording_tool/core/network/providers/offline_queue_providers.dart';
bool _dioConfigured = false;
final dioProvider = Provider<Dio>((ref) {
final dio = Dio(
BaseOptions(
baseUrl: AppConfig.current.baseUrl,
connectTimeout: const Duration(seconds: 30),
receiveTimeout: const Duration(seconds: 30),
sendTimeout: const Duration(seconds: 30),
responseType: ResponseType.json,
),
);
final dio = AppDio.instance;
dio.interceptors.add(HeaderInterceptor());
if (!_dioConfigured) {
_dioConfigured = true;
dio.interceptors.add(HeaderInterceptor());
final monitor = ref.watch(networkMonitorProvider);
final queueManager = ref.watch(offlineQueueManagerProvider);
dio.interceptors.add(
OfflineQueueInterceptor(
monitor: monitor,
manager: queueManager,
enabled: false,
),
);
final monitor = ref.read(networkMonitorProvider);
final queueManager = ref.read(offlineQueueManagerProvider);
dio.interceptors.add(
OfflineQueueInterceptor(
monitor: monitor,
manager: queueManager,
enabled: false,
),
);
if (AppConfig.current.enableNetworkLog) {
dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));
if (AppConfig.current.enableNetworkLog) {
dio.interceptors.add(
LogInterceptor(requestBody: true, responseBody: true),
);
}
}
return dio;
+4 -1
View File
@@ -31,6 +31,7 @@ class AppDeviceInfo {
required this.platform,
required this.isPhysicalDevice,
required this.values,
required this.deviceCode,
});
factory AppDeviceInfo.fromMap(Map<Object?, Object?> map) {
@@ -48,19 +49,21 @@ class AppDeviceInfo {
platform: map['platform'] as String? ?? Platform.operatingSystem,
isPhysicalDevice: isPhysicalDevice is bool ? isPhysicalDevice : true,
values: values,
deviceCode: values['deviceCode'] ?? '',
);
}
final String platform;
final bool isPhysicalDevice;
final Map<String, String> values;
final String deviceCode;
}
class AppPlatformInfo {
AppPlatformInfo._();
static const MethodChannel _channel = MethodChannel(
'com.run.sportsx/platform_info',
'app.record_tool/platform_info',
);
static Future<AppPackageInfo> packageInfo() async {
+8
View File
@@ -28,4 +28,12 @@ class DeviceUtils {
}
return (await AppPlatformInfo.deviceInfo()).values;
}
static Future<String> deviceCode() async {
try {
return (await AppPlatformInfo.deviceInfo()).deviceCode.trim();
} catch (_) {
return '';
}
}
}
+142
View File
@@ -0,0 +1,142 @@
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:network_info_plus/network_info_plus.dart';
/// 局域网 NAS IP 探测(结果仅存内存静态字段)。
class UtilSearchNasIp {
UtilSearchNasIp._();
static const String _defaultPreUrl = 'http://192.168.1.';
static const String _probePath =
':5666/sac/rpcproxy/v1/new-user-guide/status';
static const Duration _timeout = Duration(seconds: 1);
/// 命中的 NAS IPv4(仅内存,进程内有效)。
static String? nasIp;
/// 并发扫同网段 1~255,超时 1s;首个有 HTTP 响应者写入 [nasIp] 并返回。
static Future<String?> discover() async {
if (nasIp != null && nasIp!.isNotEmpty) {
return nasIp;
}
final startedAt = DateTime.now();
final preUrl = await _resolvePreUrl();
final dio = Dio(
BaseOptions(
connectTimeout: _timeout,
receiveTimeout: _timeout,
sendTimeout: _timeout,
validateStatus: (_) => true,
),
);
final cancelToken = CancelToken();
try {
await Future.wait([
for (var host = 1; host <= 255; host++)
_probeHost(
dio: dio,
cancelToken: cancelToken,
preUrl: preUrl,
host: host,
startedAt: startedAt,
),
]);
if (nasIp == null) {
final elapsedMs = DateTime.now().difference(startedAt).inMilliseconds;
debugPrint('NAS 探测未命中,总耗时: ${elapsedMs}ms');
}
return nasIp;
} finally {
dio.close(force: true);
}
}
/// 由本机 WiFi IPv4 推导 `http://a.b.c.`,失败则用默认网段。
static Future<String> _resolvePreUrl() async {
try {
final wifiIp = await NetworkInfo().getWifiIP();
if (wifiIp == null || wifiIp.isEmpty) return _defaultPreUrl;
final parts = wifiIp.split('.');
if (parts.length != 4) return _defaultPreUrl;
return 'http://${parts[0]}.${parts[1]}.${parts[2]}.';
} catch (_) {
return _defaultPreUrl;
}
}
/// 探测单个主机;任意 HTTP 响应视为命中。
static Future<void> _probeHost({
required Dio dio,
required CancelToken cancelToken,
required String preUrl,
required int host,
required DateTime startedAt,
}) async {
if (cancelToken.isCancelled || nasIp != null) return;
final target = '$preUrl$host$_probePath';
try {
await dio.get<dynamic>(target, cancelToken: cancelToken);
_onHit(preUrl, host, cancelToken, startedAt);
} on DioException catch (error) {
if (error.type == DioExceptionType.cancel) return;
// 带 response 的 DioException 也表示已连通
if (error.response != null) {
_onHit(preUrl, host, cancelToken, startedAt);
}
} catch (_) {
// 超时 / 连接失败:未命中
}
}
/// 记录命中:写 [nasIp]、打印 IP 与总耗时,并取消其余请求。
static void _onHit(
String preUrl,
int host,
CancelToken cancelToken,
DateTime startedAt,
) {
if (nasIp != null) return;
final ip = '${_hostPrefix(preUrl)}$host';
nasIp = ip;
final elapsedMs = DateTime.now().difference(startedAt).inMilliseconds;
debugPrint('NAS IP: $ip,探测总耗时: ${elapsedMs}ms');
if (!cancelToken.isCancelled) {
cancelToken.cancel('nas-found');
}
}
/// `http://192.168.1.` → `192.168.1.`
static String _hostPrefix(String preUrl) {
return preUrl.replaceFirst(RegExp(r'^https?://'), '');
}
}
// ---------------------------------------------------------------------------
// 调用案例
// ---------------------------------------------------------------------------
//
// 1) Auth 页静默探测(不阻塞登录):
//
// import 'dart:async';
// import 'package:recording_tool/core/utils/util_search_nasIp.dart';
//
// WidgetsBinding.instance.addPostFrameCallback((_) {
// unawaited(UtilSearchNasIp.discover());
// });
//
// 2) 业务侧读取已命中 IP
//
// final ip = UtilSearchNasIp.nasIp;
// if (ip != null) {
// final base = 'http://$ip:5666';
// // 使用 base 访问 NAS...
// }
//
// 3) 主动等待探测结果(少用,会阻塞当前异步流程):
//
// final ip = await UtilSearchNasIp.discover();
// debugPrint('result: $ip');
//
+94
View File
@@ -0,0 +1,94 @@
/// 获取 TOKEN 响应模型
class GetTokenResModel {
GetTokenResModel({required this.deviceAccessToken});
final String deviceAccessToken;
factory GetTokenResModel.fromJson(Map<String, dynamic> json) {
return GetTokenResModel(
deviceAccessToken: (json['deviceAccessToken'] ?? '').toString(),
);
}
Map<String, dynamic> toJson() {
return {'deviceAccessToken': deviceAccessToken};
}
}
/// 查看录像响应模型
class GetRecordListResModel {
String? path;
List<RecordListItem>? items;
GetRecordListResModel({this.path, this.items});
factory GetRecordListResModel.fromJson(Map<String, dynamic> json) {
final rawItems = json['items'];
return GetRecordListResModel(
path: json['path']?.toString(),
items: rawItems is! List
? []
: rawItems
.whereType<Map>()
.map(
(x) => RecordListItem.fromJson(Map<String, dynamic>.from(x)),
)
.toList(),
);
}
Map<String, dynamic> toJson() => {
'path': path,
'items': items == null
? []
: List<dynamic>.from(items!.map((x) => x.toJson())),
};
}
enum RecordItemType {
file('file'),
directory('dir');
final String value;
const RecordItemType(this.value);
}
class RecordListItem {
String? name;
String? path;
String? type;
int? size;
DateTime? modTime;
String? url;
String? extension;
RecordListItem({
this.name,
this.path,
this.type,
this.size,
this.modTime,
this.url,
this.extension,
});
factory RecordListItem.fromJson(Map<String, dynamic> json) => RecordListItem(
name: json['name'] ?? '',
path: json['path'] ?? '',
type: json['type'] ?? '',
size: json['size'] ?? 0,
modTime: json['modTime'] == null ? null : DateTime.parse(json['modTime']),
url: json['url'] ?? '',
extension: json['extension'] ?? '',
);
Map<String, dynamic> toJson() => {
'name': name,
'path': path,
'type': type,
'size': size,
'modTime': modTime?.toIso8601String(),
'url': url,
'extension': extension,
};
}
+67
View File
@@ -0,0 +1,67 @@
// To parse this JSON data, do
//
// final jwtDecodedData = jwtDecodedDataFromJson(jsonString);
import 'dart:convert';
JwtDecodedData jwtDecodedDataFromJson(String str) =>
JwtDecodedData.fromJson(json.decode(str));
String jwtDecodedDataToJson(JwtDecodedData data) => json.encode(data.toJson());
class JwtDecodedData {
String? authType;
String? deviceCode;
int? deviceId;
String? deviceRole;
String? eventName;
String? oId;
List<String>? oIds;
String? organizerId;
String? nasIpAddr;
JwtDecodedData({
this.authType,
this.deviceCode,
this.deviceId,
this.deviceRole,
this.eventName,
this.oId,
this.oIds,
this.organizerId,
this.nasIpAddr,
});
factory JwtDecodedData.fromJson(Map<String, dynamic> json) => JwtDecodedData(
authType: json['authType']?.toString(),
deviceCode: json['deviceCode']?.toString(),
deviceId: _readInt(json['deviceId']),
deviceRole: json['deviceRole']?.toString(),
eventName: json['eventName']?.toString(),
oId: json['oId']?.toString(),
oIds: json['oIds'] == null
? []
: List<String>.from(json['oIds']!.map((x) => x?.toString())),
organizerId: json['organizerId']?.toString(),
nasIpAddr: json['nasIpAddr']?.toString(),
);
Map<String, dynamic> toJson() => {
'authType': authType,
'deviceCode': deviceCode,
'deviceId': deviceId,
'deviceRole': deviceRole,
'eventName': eventName,
'oId': oId,
'oIds': oIds == null ? [] : List<dynamic>.from(oIds!.map((x) => x)),
'organizerId': organizerId,
'nasIpAddr': nasIpAddr,
};
}
int? _readInt(dynamic value) {
if (value == null) return null;
if (value is int) return value;
if (value is num) return value.toInt();
return int.tryParse(value.toString());
}
+269
View File
@@ -0,0 +1,269 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/app/router/app_navigator.dart';
import 'package:recording_tool/core/cache/app_storage.dart';
import 'package:recording_tool/core/cache/storage_keys.dart';
import 'package:recording_tool/core/utils/device_utils.dart';
import 'package:recording_tool/features/auth/view_model_auth/view_model_auth.dart';
import 'package:recording_tool/features/scan_qrcode/pages/page_scan_qrcode.dart';
import 'package:recording_tool/gen/assets.gen.dart';
import 'package:recording_tool/shared/widgets/app_dialog.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';
class AuthPageWidget extends ConsumerStatefulWidget {
const AuthPageWidget({super.key});
@override
ConsumerState<AuthPageWidget> createState() => _AuthPageWidgetState();
}
class _AuthPageWidgetState extends ConsumerState<AuthPageWidget> {
late final TextEditingController _controller;
/// 记录点击次数
int _clickCount = 0;
@override
void initState() {
super.initState();
_controller = TextEditingController(text: '');
WidgetsBinding.instance.addPostFrameCallback((_) async {
final token = AppStorage.getString(StorageKeys.authToken);
if (token?.isNotEmpty ?? false) {
final success = await ref
.read(authProvider.notifier)
.parseTokenSetState();
if (!success) {
return;
}
AppNavigator.push(const ScanQrCodePage());
}
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _showDeviceCodeDialog() async {
final deviceCode = await DeviceUtils.deviceCode();
if (!mounted) return;
AppDialog.confirm(context, title: '设备码:$deviceCode');
}
@override
Widget build(BuildContext context) {
final authState = ref.watch(authProvider);
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.dark.copyWith(
statusBarColor: Colors.transparent,
systemNavigationBarColor: Colors.white,
),
child: Scaffold(
backgroundColor: Colors.white,
body: Stack(
children: [
Positioned.fill(
child: Image.asset(
_AuthAssets.pageBg,
width: double.infinity,
fit: BoxFit.fill,
),
),
SafeArea(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 32.w),
child: SingleChildScrollView(
child: Column(
children: [
SizedBox(height: 190.h),
ClipRRect(
borderRadius: BorderRadius.circular(24.r),
child: GestureDetector(
onTap: () {
_clickCount++;
if (_clickCount >= 5) {
_showDeviceCodeDialog();
_clickCount = 0;
}
},
child: Image.asset(
_AuthAssets.appIcon,
width: 82.w,
height: 82.w,
fit: BoxFit.cover,
),
),
),
SizedBox(height: 18.h),
Image.asset(
_AuthAssets.appNameText,
width: 132.w,
height: 28.w,
fit: BoxFit.cover,
),
SizedBox(height: 78.h),
_PassCodeInput(controller: _controller),
SizedBox(height: 20.h),
_GradientConfirmButton(
isLoading: authState.isLoading,
onPressed: _handleSubmit,
),
// SizedBox(height: 20.h),
// AppButton(
// onPressed: () async {
// final deviceCode = await DeviceUtils.deviceCode();
// if (!mounted) return;
// AppDialog.confirm(context, title: '设备码:$deviceCode');
// },
// label: '获取设备码',
// ),
],
),
),
),
),
],
),
),
);
}
Future<void> _handleSubmit() async {
final success = await ref
.read(authProvider.notifier)
.auth(_controller.text);
if (!mounted) return;
if (success) {
_controller.clear();
AppNavigator.push(const ScanQrCodePage());
return;
}
final message = ref.read(authProvider).errorMessage;
if (message != null && message.isNotEmpty) {
AppToast.show(message);
}
}
}
class _PassCodeInput extends StatelessWidget {
const _PassCodeInput({required this.controller});
final TextEditingController controller;
@override
Widget build(BuildContext context) {
return Container(
height: 50.h,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12.r),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.08),
blurRadius: 10.r,
offset: Offset(0, 2.h),
),
],
),
child: TextField(
controller: controller,
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
maxLength: 6,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(6),
],
style: TextStyle(
color: const Color(0xFF2F3338),
fontSize: 16.sp,
fontWeight: FontWeight.w500,
),
decoration: InputDecoration(
hintText: '请输入执裁口令',
hintStyle: TextStyle(
color: const Color(0xFFB6B9BF),
fontSize: 16.sp,
fontWeight: FontWeight.w400,
),
counterText: '',
border: InputBorder.none,
contentPadding: EdgeInsets.symmetric(
horizontal: 16.w,
vertical: 14.h,
),
),
),
);
}
}
class _GradientConfirmButton extends StatelessWidget {
const _GradientConfirmButton({
required this.isLoading,
required this.onPressed,
});
final bool isLoading;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return Opacity(
opacity: isLoading ? 0.72 : 1,
child: GestureDetector(
onTap: isLoading ? null : onPressed,
child: Container(
height: 50.h,
width: double.infinity,
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25.r),
gradient: const LinearGradient(
colors: [Color(0xFF268DFF), Color(0xFF5DD4F6)],
),
boxShadow: [
BoxShadow(
color: const Color(0xFF2196F3).withValues(alpha: 0.28),
blurRadius: 14.r,
offset: Offset(0, 6.h),
),
],
),
child: isLoading
? SizedBox.square(
dimension: 18.r,
child: CircularProgressIndicator(
strokeWidth: 2.r,
valueColor: const AlwaysStoppedAnimation<Color>(
Colors.white,
),
),
)
: Text(
'确定',
style: TextStyle(
color: Colors.white,
fontSize: 16.sp,
fontWeight: FontWeight.w500,
),
),
),
),
);
}
}
class _AuthAssets {
const _AuthAssets._();
static String pageBg = Assets.images.imagePageBg.path;
static String appIcon = Assets.images.imageAppIcon.path;
static String appNameText = Assets.images.imageAppNameText.path;
}
+84
View File
@@ -0,0 +1,84 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:recording_tool/app/config/api_common.dart';
import 'package:recording_tool/core/network/providers/dio_providers.dart';
import 'package:recording_tool/core/utils/device_utils.dart';
import 'package:recording_tool/features/auth/model/model_auth.dart';
import 'package:recording_tool/features/auth/model/model_jwt.dart';
class AuthServer {
/// [passCode] 口令码
static Future<GetTokenResModel> login(String passCode, Ref ref) async {
final deviceCode = await DeviceUtils.deviceCode();
if (deviceCode.isEmpty) {
throw const FormatException('无法获取设备标识');
}
final apiClient = ref.read(apiClientProvider);
final data = await apiClient.post<GetTokenResModel>(
AuthApi.getToken.path,
data: {'deviceCode': deviceCode, 'passCode': passCode},
parser: (json) => GetTokenResModel.fromJson(json as Map<String, dynamic>),
);
if (data.deviceAccessToken.isEmpty) {
throw const FormatException('登录响应缺少 TOKEN');
}
return data;
}
/// 获取赛事列表
/// [path] 赛事目录
/// [nasIpAddr] NAS IP,由调用方传入,避免在 authProvider 内部再 read(authProvider)。
static Future<GetRecordListResModel?> getRecordList(
Ref ref, {
required String path,
required String nasIpAddr,
}) async {
try {
if (nasIpAddr.isEmpty) {
throw const FormatException('无法获取NAS IP地址');
}
final apiClient = ref.read(apiClientProvider);
// NAS /api/files 直接返回 {path, items},不是业务网关的 {code,message,data} 包装。
final data = await apiClient.get<GetRecordListResModel>(
'http://$nasIpAddr:9001/${AuthApi.getRecordList.path}',
queryParameters: {'path': path},
wrapResponse: false,
parser: (json) {
if (json is! Map) {
throw const FormatException('录像列表响应格式错误');
}
return GetRecordListResModel.fromJson(
Map<String, dynamic>.from(json),
);
},
);
return data;
} catch (error) {
debugPrint('getRecordList failed: $error');
return null;
}
}
/// 获取登录设备信息
static Future<JwtDecodedData?> getLoginDeviceInfo(Ref ref) async {
try {
final apiClient = ref.read(apiClientProvider);
final data = await apiClient.get<JwtDecodedData>(
AuthApi.getLoginDeviceInfo.path,
parser: (json) {
if (json is! Map) {
throw const FormatException('登录设备信息响应格式错误');
}
return JwtDecodedData.fromJson(Map<String, dynamic>.from(json));
},
);
return data;
} catch (error) {
debugPrint('getLoginDeviceInfo failed: $error');
return null;
}
}
}
+34
View File
@@ -0,0 +1,34 @@
import 'package:recording_tool/features/auth/model/model_auth.dart';
import 'package:recording_tool/features/auth/model/model_jwt.dart';
class AuthState {
const AuthState({
this.isLoading = false,
this.errorMessage,
this.jwtDecodedData,
this.recordList,
});
final bool isLoading;
final String? errorMessage;
/// 解析后的 TOKEN 数据
final JwtDecodedData? jwtDecodedData;
/// 赛事列表
final List<RecordListItem>? recordList;
AuthState copyWith({
bool? isLoading,
String? errorMessage,
JwtDecodedData? jwtDecodedData,
List<RecordListItem>? recordList,
}) {
return AuthState(
isLoading: isLoading ?? this.isLoading,
errorMessage: errorMessage ?? this.errorMessage,
jwtDecodedData: jwtDecodedData ?? this.jwtDecodedData,
recordList: recordList ?? this.recordList,
);
}
}
@@ -0,0 +1,105 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/legacy.dart';
import 'package:recording_tool/core/cache/app_storage.dart';
import 'package:recording_tool/core/cache/storage_keys.dart';
import 'package:recording_tool/core/network/api_exception.dart';
import 'package:recording_tool/features/auth/model/model_auth.dart';
import 'package:recording_tool/features/auth/server/server_auth.dart';
import 'package:recording_tool/features/auth/state/state_auth.dart';
final authProvider =
StateNotifierProvider.autoDispose<AuthViewModel, AuthState>((ref) {
return AuthViewModel(ref);
});
class AuthViewModel extends StateNotifier<AuthState> {
AuthViewModel(this._ref) : super(const AuthState());
final Ref _ref;
/// 鉴权获取 token
Future<bool> auth(String code) async {
final passCode = code.trim();
if (passCode.isEmpty) {
state = const AuthState(errorMessage: '请输入执裁口令');
return false;
}
state = const AuthState(isLoading: true);
try {
final data = await AuthServer.login(passCode, _ref);
await AppStorage.setString(StorageKeys.authToken, data.deviceAccessToken);
state = const AuthState();
if (data.deviceAccessToken.isNotEmpty) {
final ok = await parseTokenSetState();
if (!ok) {
state = const AuthState(errorMessage: '获取赛事信息失败,请重试');
return false;
}
}
return true;
} on FormatException catch (error) {
state = AuthState(errorMessage: error.message);
return false;
} on ApiException catch (error) {
state = AuthState(errorMessage: error.message);
return false;
} catch (_) {
state = const AuthState(errorMessage: '认证失败,请重试');
return false;
}
}
/// 解析 TOKEN,并更新状态
Future<bool> parseTokenSetState() async {
final data = await AuthServer.getLoginDeviceInfo(_ref);
if (data == null) return false;
state = state.copyWith(jwtDecodedData: data);
return true;
// final decoded = JwtDecoder.decode(token);
// final rawData = decoded['data'];
// if (rawData is! Map) return false;
// try {
// final data = JwtDecodedData.fromJson(Map<String, dynamic>.from(rawData));
// state = state.copyWith(jwtDecodedData: data);
// return true;
// } catch (error) {
// debugPrint('认证失败,请重试: $error');
// return false;
// }
}
/// 获取赛事列表
Future<bool> getRecordList(String eventName) async {
if (eventName.isEmpty) return false;
final nasIpAddr = state.jwtDecodedData?.nasIpAddr?.trim() ?? '';
if (nasIpAddr.isEmpty) return false;
final data = await AuthServer.getRecordList(
_ref,
path: eventName,
nasIpAddr: nasIpAddr,
);
if (data == null) return false;
if (data.items == null) return false;
state = state.copyWith(recordList: data.items);
return true;
}
/// 获取指定目录的录像列表(不更新 state,用于目录下钻)
Future<List<RecordListItem>?> fetchRecordList(String path) async {
if (path.isEmpty) return null;
final nasIpAddr = state.jwtDecodedData?.nasIpAddr?.trim() ?? '';
if (nasIpAddr.isEmpty) return null;
final data = await AuthServer.getRecordList(
_ref,
path: path,
nasIpAddr: nasIpAddr,
);
return data?.items;
}
/// 清空授权信息(本地 token + 内存状态)
Future<void> clearAuth() async {
await AppStorage.remove(StorageKeys.authToken);
state = const AuthState();
}
}
@@ -0,0 +1,171 @@
class CompetitionPlayer {
const CompetitionPlayer({required this.id, required this.name});
final String id;
final String name;
}
class CompetitionTeam {
const CompetitionTeam({
required this.id,
required this.name,
required this.players,
});
final String id;
final String name;
final List<CompetitionPlayer> players;
String get playerNames => players.map((player) => player.name).join('');
}
class CompetitionMatchup {
const CompetitionMatchup({
required this.id,
required this.teamA,
required this.teamB,
this.winnerTeamId,
});
final String id;
final CompetitionTeam teamA;
final CompetitionTeam teamB;
final String? winnerTeamId;
CompetitionMatchup copyWith({String? winnerTeamId}) {
return CompetitionMatchup(
id: id,
teamA: teamA,
teamB: teamB,
winnerTeamId: winnerTeamId ?? this.winnerTeamId,
);
}
}
/// 参赛项目/组别列表项(来自 /api/events/device/item/group
class CompetitionTeamListItem {
const CompetitionTeamListItem({
required this.eventId,
required this.itemId,
required this.name,
required this.groupName,
this.matchStartTime = '',
this.matchEndTime = '',
this.matchups = const [],
});
final String eventId;
final String itemId;
final String name;
final String groupName;
final String matchStartTime;
final String matchEndTime;
/// 对阵明细暂未由列表接口返回,默认空
final List<CompetitionMatchup> matchups;
String get title => groupName.isEmpty ? name : '$name $groupName';
String get scheduleTime {
if (matchStartTime.isEmpty && matchEndTime.isEmpty) return '';
if (matchStartTime.isNotEmpty && matchEndTime.isNotEmpty) {
return '$matchStartTime-$matchEndTime';
}
if (matchStartTime.isNotEmpty) return matchStartTime;
return matchEndTime;
}
factory CompetitionTeamListItem.fromJson(Map<String, dynamic> json) {
return CompetitionTeamListItem(
eventId: (json['eventId'] ?? '').toString(),
itemId: (json['itemId'] ?? '').toString(),
name: (json['name'] ?? '').toString(),
groupName: (json['groupName'] ?? '').toString(),
matchStartTime: (json['matchStartTime'] ?? '').toString(),
matchEndTime: (json['matchEndTime'] ?? '').toString(),
);
}
CompetitionTeamListItem copyWith({List<CompetitionMatchup>? matchups}) {
return CompetitionTeamListItem(
eventId: eventId,
itemId: itemId,
name: name,
groupName: groupName,
matchStartTime: matchStartTime,
matchEndTime: matchEndTime,
matchups: matchups ?? this.matchups,
);
}
}
class CompetitionTeamPageResult {
const CompetitionTeamPageResult({
required this.items,
required this.total,
required this.page,
required this.pageSize,
});
final List<CompetitionTeamListItem> items;
final int total;
final int page;
final int pageSize;
bool get hasMore => page * pageSize < total;
factory CompetitionTeamPageResult.fromJson(
dynamic json, {
required int page,
required int pageSize,
}) {
if (json is List) {
// 整表无分页:本页即全部,hasMore = false
final items = json
.whereType<Map>()
.map(
(item) => CompetitionTeamListItem.fromJson(
Map<String, dynamic>.from(item),
),
)
.toList(growable: false);
final effectivePageSize = items.isEmpty ? pageSize : items.length;
return CompetitionTeamPageResult(
items: items,
total: items.length,
page: page,
pageSize: effectivePageSize,
);
}
if (json is Map) {
final map = Map<String, dynamic>.from(json);
final rawItems =
map['items'] ?? map['rows'] ?? map['list'] ?? map['records'];
final items = rawItems is List
? rawItems
.whereType<Map>()
.map(
(item) => CompetitionTeamListItem.fromJson(
Map<String, dynamic>.from(item),
),
)
.toList(growable: false)
: const <CompetitionTeamListItem>[];
final total = (map['total'] as num?)?.toInt() ?? items.length;
return CompetitionTeamPageResult(
items: items,
total: total,
page: page,
pageSize: pageSize,
);
}
return CompetitionTeamPageResult(
items: const [],
total: 0,
page: page,
pageSize: pageSize,
);
}
}
@@ -0,0 +1,174 @@
/// 参赛队伍详情
class CompetitionTeamDetail {
String? scheduleId;
String? itemId;
String? eventId;
String? itemName;
String? groupName;
String? matchPlace;
String? matchStartTime;
String? matchEndTime;
List<Matchup>? matchups;
CompetitionTeamDetail({
this.scheduleId,
this.itemId,
this.eventId,
this.itemName,
this.groupName,
this.matchPlace,
this.matchStartTime,
this.matchEndTime,
this.matchups,
});
factory CompetitionTeamDetail.fromJson(Map<String, dynamic> json) =>
CompetitionTeamDetail(
scheduleId: json['scheduleId']?.toString(),
itemId: json['itemId']?.toString(),
eventId: json['eventId']?.toString(),
itemName: json['itemName']?.toString(),
groupName: json['groupName']?.toString(),
matchPlace: json['matchPlace']?.toString(),
matchStartTime: json['matchStartTime']?.toString(),
matchEndTime: json['matchEndTime']?.toString(),
matchups: json['matchups'] == null
? const []
: List<Matchup>.from(
(json['matchups'] as List).whereType<Map>().map(
(x) => Matchup.fromJson(Map<String, dynamic>.from(x)),
),
),
);
/// 兼容 data 为对象或数组(取首项)
factory CompetitionTeamDetail.fromResponse(dynamic json) {
if (json is List) {
if (json.isEmpty) return CompetitionTeamDetail(matchups: const []);
final first = json.first;
if (first is Map) {
return CompetitionTeamDetail.fromJson(Map<String, dynamic>.from(first));
}
return CompetitionTeamDetail(matchups: const []);
}
if (json is Map) {
return CompetitionTeamDetail.fromJson(Map<String, dynamic>.from(json));
}
return CompetitionTeamDetail(matchups: const []);
}
Map<String, dynamic> toJson() => {
'scheduleId': scheduleId,
'itemId': itemId,
'eventId': eventId,
'itemName': itemName,
'groupName': groupName,
'matchPlace': matchPlace,
'matchStartTime': matchStartTime,
'matchEndTime': matchEndTime,
'matchups': matchups == null
? []
: List<dynamic>.from(matchups!.map((x) => x.toJson())),
};
}
class Matchup {
String? matchTitle;
String? opponentId;
List<Team>? teamA;
List<Team>? teamB;
Matchup({this.matchTitle, this.opponentId, this.teamA, this.teamB});
factory Matchup.fromJson(Map<String, dynamic> json) => Matchup(
matchTitle: json['matchTitle']?.toString(),
opponentId: json['opponentId']?.toString(),
teamA: json['teamA'] == null
? const []
: List<Team>.from(
(json['teamA'] as List).whereType<Map>().map(
(x) => Team.fromJson(Map<String, dynamic>.from(x)),
),
),
teamB: json['teamB'] == null
? const []
: List<Team>.from(
(json['teamB'] as List).whereType<Map>().map(
(x) => Team.fromJson(Map<String, dynamic>.from(x)),
),
),
);
Map<String, dynamic> toJson() => {
'matchTitle': matchTitle,
'opponentId': opponentId,
'teamA': teamA == null
? []
: List<dynamic>.from(teamA!.map((x) => x.toJson())),
'teamB': teamB == null
? []
: List<dynamic>.from(teamB!.map((x) => x.toJson())),
};
}
class Team {
String? teamName;
List<Player>? players;
Team({this.teamName, this.players});
String get playerNames => (players ?? const <Player>[])
.map((player) => player.name?.trim() ?? '')
.where((name) => name.isNotEmpty)
.join('');
/// 队长 Player.id;无队长则取首个选手
String? get leaderUserId {
final list = players ?? const <Player>[];
for (final player in list) {
final id = player.id?.trim() ?? '';
if (player.isLeader == true && id.isNotEmpty) return id;
}
if (list.isEmpty) return null;
final firstId = list.first.id?.trim() ?? '';
return firstId.isEmpty ? null : firstId;
}
factory Team.fromJson(Map<String, dynamic> json) => Team(
teamName: json['teamName']?.toString(),
players: json['players'] == null
? const []
: List<Player>.from(
(json['players'] as List).whereType<Map>().map(
(x) => Player.fromJson(Map<String, dynamic>.from(x)),
),
),
);
Map<String, dynamic> toJson() => {
'teamName': teamName,
'players': players == null
? []
: List<dynamic>.from(players!.map((x) => x.toJson())),
};
}
class Player {
String? id;
String? name;
bool? isLeader;
Player({this.id, this.name, this.isLeader});
factory Player.fromJson(Map<String, dynamic> json) => Player(
id: json['id']?.toString(),
name: json['name']?.toString(),
isLeader: json['isLeader'] as bool?,
);
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'isLeader': isLeader,
};
}
@@ -0,0 +1,324 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/core/network/api_exception.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team_detail.dart';
import 'package:recording_tool/features/competition_teams/widgets/widget_manual_winner_dialog.dart';
import 'package:recording_tool/features/events/request_model/request_model_event.dart';
import 'package:recording_tool/features/events/server/server_events.dart';
import 'package:recording_tool/gen/assets.gen.dart';
import 'package:recording_tool/shared/widgets/app_bar.dart';
import 'package:recording_tool/shared/widgets/app_empty_view.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';
class CompetitionTeamDetailPage extends ConsumerStatefulWidget {
const CompetitionTeamDetailPage({super.key, required this.detail});
final CompetitionTeamDetail detail;
@override
ConsumerState<CompetitionTeamDetailPage> createState() =>
_CompetitionTeamDetailPageState();
}
class _CompetitionTeamDetailPageState
extends ConsumerState<CompetitionTeamDetailPage> {
/// matchupIndex -> winner side index0=teamA1=teamB
final Map<int, int> _winners = {};
CompetitionTeamDetail get _detail => widget.detail;
String get _title {
final name = _detail.itemName?.trim() ?? '';
final group = _detail.groupName?.trim() ?? '';
if (name.isEmpty) return '参赛队伍';
return group.isEmpty ? name : '$name $group';
}
List<Matchup> get _matchups => _detail.matchups ?? const <Matchup>[];
CompetitionTeam _toCompetitionTeam(Team team, {required String fallbackId}) {
return CompetitionTeam(
id: team.leaderUserId ?? fallbackId,
name: team.teamName?.trim().isNotEmpty == true ? team.teamName! : '未命名队伍',
players: (team.players ?? const <Player>[])
.map(
(player) => CompetitionPlayer(
id: player.id?.trim() ?? '',
name: player.name?.trim().isNotEmpty == true
? player.name!
: '选手',
),
)
.toList(growable: false),
);
}
CompetitionMatchup? _toCompetitionMatchup(Matchup matchup, int index) {
final teamA = matchup.teamA;
final teamB = matchup.teamB;
if (teamA == null || teamA.isEmpty || teamB == null || teamB.isEmpty) {
return null;
}
final winnerSide = _winners[index];
final convertedA = _toCompetitionTeam(teamA.first, fallbackId: 'team-a');
final convertedB = _toCompetitionTeam(teamB.first, fallbackId: 'team-b');
return CompetitionMatchup(
id: '${_detail.scheduleId ?? _detail.itemId ?? 'match'}-$index',
teamA: convertedA,
teamB: convertedB,
winnerTeamId: winnerSide == 0
? convertedA.id
: winnerSide == 1
? convertedB.id
: null,
);
}
@override
Widget build(BuildContext context) {
final matchups = _matchups;
return Scaffold(
backgroundColor: const Color(0xFFF2F4F7),
appBar: AppPageBar(title: _title),
body: matchups.isEmpty
? const AppEmptyView(message: '暂无对阵信息')
: ListView.separated(
padding: EdgeInsets.only(bottom: 36.h),
itemCount: matchups.length,
separatorBuilder: (_, _) => SizedBox(height: 12.h),
itemBuilder: (context, index) {
final raw = matchups[index];
final matchup = _toCompetitionMatchup(raw, index);
if (matchup == null) {
return const SizedBox.shrink();
}
return _MatchupCard(
matchup: matchup,
onManualProcess: () => _handleManualProcess(raw, index),
);
},
),
);
}
Team? _sideTeam(Matchup matchup, {required bool isTeamA}) {
final list = isTeamA ? matchup.teamA : matchup.teamB;
if (list == null || list.isEmpty) return null;
return list.first;
}
Future<void> _handleManualProcess(Matchup raw, int index) async {
final winnerSide = await ManualWinnerDialog.show(
context,
matchup: raw,
initialWinnerSideIndex: _winners[index],
);
if (winnerSide == null || !mounted) return;
final teamA = _sideTeam(raw, isTeamA: true);
final teamB = _sideTeam(raw, isTeamA: false);
final winnerTeam = winnerSide == 0 ? teamA : teamB;
final loserTeam = winnerSide == 0 ? teamB : teamA;
final winnerLeaderId = winnerTeam?.leaderUserId;
final loserLeaderId = loserTeam?.leaderUserId;
if (winnerLeaderId == null ||
winnerLeaderId.isEmpty ||
loserLeaderId == null ||
loserLeaderId.isEmpty) {
AppToast.show('无法识别双方队长');
return;
}
try {
await ref
.read(eventsServerProvider)
.setTeamStatus(
req: SetTeamStatusReq(
scheduleId: _detail.scheduleId ?? '',
opponentId: raw.opponentId ?? '',
teamScore: [
TeamScore(
userId: winnerLeaderId,
firstHalfScore: 0,
secondHalfScore: 0,
decisiveScore: 0,
ifWithdraw: true,
),
TeamScore(
userId: loserLeaderId,
firstHalfScore: 0,
secondHalfScore: 0,
decisiveScore: 0,
ifWithdraw: false,
),
],
),
);
if (!mounted) return;
setState(() => _winners[index] = winnerSide);
final winnerName = winnerTeam?.teamName?.trim().isNotEmpty == true
? winnerTeam!.teamName!
: '胜方';
AppToast.show('已设置$winnerName直接获胜');
} catch (error) {
if (!mounted) return;
final message = error is ApiException && error.message.isNotEmpty
? error.message
: '设置失败,请重试';
AppToast.show(message);
}
}
}
class _MatchupCard extends StatelessWidget {
const _MatchupCard({required this.matchup, required this.onManualProcess});
/// 背景图 image_team_vs_bg.png 的原始宽高比(1920 x 318)。
static const double _vsBgAspectRatio = 1920 / 318;
final CompetitionMatchup matchup;
final VoidCallback onManualProcess;
@override
Widget build(BuildContext context) {
return Container(
key: ValueKey('competition-matchup-${matchup.id}'),
color: Colors.white,
padding: EdgeInsets.fromLTRB(12.w, 4.h, 12.w, 24.h),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Align(
alignment: Alignment.centerRight,
child: TextButton(
key: ValueKey('manual-process-${matchup.id}'),
onPressed: onManualProcess,
style: TextButton.styleFrom(
padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
minimumSize: Size.zero,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
child: Text(
'人工处理',
style: TextStyle(
fontSize: 15.sp,
fontWeight: FontWeight.w500,
color: const Color(0xFF078AF2),
),
),
),
),
SizedBox(height: 8.h),
AspectRatio(
aspectRatio: _vsBgAspectRatio,
child: DecoratedBox(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(Assets.images.imageTeamVsBg.path),
fit: BoxFit.fill,
),
),
child: Row(
children: [
Expanded(
child: _TeamPanel(
team: matchup.teamA,
isLeft: true,
winner: matchup.winnerTeamId == matchup.teamA.id,
accentColor: const Color(0xFFFF6B75),
),
),
Expanded(
child: _TeamPanel(
team: matchup.teamB,
isLeft: false,
winner: matchup.winnerTeamId == matchup.teamB.id,
accentColor: const Color(0xFF12A6C8),
),
),
],
),
),
),
],
),
);
}
}
class _TeamPanel extends StatelessWidget {
const _TeamPanel({
required this.team,
required this.isLeft,
required this.winner,
required this.accentColor,
});
final CompetitionTeam team;
/// 左半区(红色面板,右对齐、略偏上);右半区(蓝色面板,左对齐、略偏下)。
final bool isLeft;
final bool winner;
final Color accentColor;
@override
Widget build(BuildContext context) {
final textAlign = isLeft ? TextAlign.end : TextAlign.start;
final nameRow = Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Text(
team.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: textAlign,
style: TextStyle(
fontSize: 15.sp,
fontWeight: FontWeight.w600,
color: const Color(0xFF282E37),
),
),
),
if (winner) ...[
SizedBox(width: 4.w),
Icon(
Icons.emoji_events,
key: ValueKey('winner-${team.id}'),
size: 14.r,
color: accentColor,
),
],
],
);
return Padding(
// 中线两侧留出 VS 图案空间,外侧避开斜切边缘。
padding: isLeft
? EdgeInsets.only(left: 16.w, right: 30.w, bottom: 10.h)
: EdgeInsets.only(left: 30.w, right: 16.w, top: 10.h),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: isLeft
? CrossAxisAlignment.end
: CrossAxisAlignment.start,
children: [
nameRow,
SizedBox(height: 4.h),
Text(
team.playerNames,
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: textAlign,
style: TextStyle(fontSize: 13.sp, color: const Color(0xFF4E5662)),
),
],
),
);
}
}
@@ -0,0 +1,189 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/app/router/app_navigator.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team.dart';
import 'package:recording_tool/features/competition_teams/pages/page_competition_team_detail.dart';
import 'package:recording_tool/features/competition_teams/server/server_competition_teams.dart';
import 'package:recording_tool/features/competition_teams/view_model/view_model_competition_teams.dart';
import 'package:recording_tool/shared/widgets/app_bar.dart';
import 'package:recording_tool/shared/widgets/app_empty_view.dart';
import 'package:recording_tool/shared/widgets/app_error_view.dart';
import 'package:recording_tool/shared/widgets/app_loading_view.dart';
import 'package:recording_tool/shared/widgets/app_refresh_list.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';
class CompetitionTeamListPage extends ConsumerStatefulWidget {
const CompetitionTeamListPage({super.key});
@override
ConsumerState<CompetitionTeamListPage> createState() =>
_CompetitionTeamListPageState();
}
class _CompetitionTeamListPageState
extends ConsumerState<CompetitionTeamListPage> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
ref.read(competitionTeamsProvider.notifier).loadInitial();
});
}
@override
Widget build(BuildContext context) {
final state = ref.watch(competitionTeamsProvider);
return Scaffold(
backgroundColor: const Color(0xFFF5F6F8),
appBar: AppPageBar(title: '参赛队伍'),
body: SafeArea(
top: false,
child: Builder(
builder: (context) {
if (state.isInitialLoading && state.items.isEmpty) {
return const AppLoadingView(message: '正在加载参赛队伍...');
}
if (state.errorMessage != null && state.items.isEmpty) {
return AppErrorView(
message: state.errorMessage!,
onRetry: () =>
ref.read(competitionTeamsProvider.notifier).loadInitial(),
);
}
return AppRefreshList<CompetitionTeamListItem>(
items: state.items,
onRefresh: ref.read(competitionTeamsProvider.notifier).refresh,
onLoadMore: ref.read(competitionTeamsProvider.notifier).loadMore,
enablePullUp: state.hasMore,
padding: EdgeInsets.fromLTRB(10.w, 10.h, 10.w, 24.h),
separator: SizedBox(height: 8.h),
empty: const AppEmptyView(message: '暂无参赛队伍'),
itemBuilder: (context, item, index) {
return _CompetitionScheduleCard(
item: item,
onTap: () async {
try {
final detail = await ref
.read(competitionTeamsServerProvider)
.fetchTeamDetail(
itemId: item.itemId,
eventId: item.eventId,
);
if (!context.mounted) return;
AppNavigator.push(
CompetitionTeamDetailPage(detail: detail),
context: context,
);
} catch (error) {
AppToast.show('对阵详情加载失败,请重试');
}
},
);
},
);
},
),
),
);
}
}
class _CompetitionScheduleCard extends StatelessWidget {
const _CompetitionScheduleCard({required this.item, required this.onTap});
final CompetitionTeamListItem item;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Material(
key: ValueKey('competition-team-item-${item.itemId}'),
color: Colors.white,
borderRadius: BorderRadius.circular(6.r),
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(6.r),
child: Container(
constraints: BoxConstraints(minHeight: 86.h),
padding: EdgeInsets.fromLTRB(12.w, 10.h, 14.w, 10.h),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(6.r),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13.sp,
height: 1.2,
color: const Color(0xFF30343A),
fontWeight: FontWeight.w700,
),
),
SizedBox(height: 6.h),
_MetaText(_formatScheduleTime(item)),
],
),
),
SizedBox(width: 12.w),
Icon(
Icons.chevron_right,
size: 20.r,
color: const Color(0xFF9AA3AF),
),
],
),
),
),
);
}
}
class _MetaText extends StatelessWidget {
const _MetaText(this.text);
final String text;
@override
Widget build(BuildContext context) {
return Text(
text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 10.sp,
height: 1.2,
color: const Color(0xFF6E747D),
fontWeight: FontWeight.w400,
),
);
}
}
String _formatScheduleTime(CompetitionTeamListItem item) {
final start = DateTime.tryParse(item.matchStartTime);
final end = DateTime.tryParse(item.matchEndTime);
if (start == null && end == null) {
return item.scheduleTime.isEmpty ? '时间待定' : item.scheduleTime;
}
if (start != null && end != null) {
return '${start.month}${start.day}${_formatClock(start)}-${_formatClock(end)}';
}
final value = start ?? end!;
return '${value.month}${value.day}${_formatClock(value)}';
}
String _formatClock(DateTime value) {
return '${value.hour}:${value.minute.toString().padLeft(2, '0')}';
}
@@ -0,0 +1,717 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/app/config/app_config.dart';
import 'package:recording_tool/app/router/app_navigator.dart';
import 'package:recording_tool/core/network/api_exception.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team_detail.dart';
import 'package:recording_tool/features/competition_teams/widgets/widget_manual_winner_dialog.dart';
import 'package:recording_tool/features/events/model/model_event_info.dart';
import 'package:recording_tool/features/events/request_model/request_model_event.dart';
import 'package:recording_tool/features/events/server/server_events.dart';
import 'package:recording_tool/gen/assets.gen.dart';
import 'package:recording_tool/shared/widgets/app_bar.dart';
import 'package:recording_tool/shared/widgets/app_qr_scanner_dialog.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';
import 'package:recording_tool/shared/widgets/app_webview.dart';
typedef TeamQrScanner = Future<String?> Function(BuildContext context);
class EventTeamMatchPage extends ConsumerStatefulWidget {
const EventTeamMatchPage({
super.key,
required this.playerId,
this.qrScanner,
required this.detail,
required this.item,
});
final CompetitionTeamDetail detail;
final String playerId;
final TeamQrScanner? qrScanner;
final EventRegistrationItem item;
@override
ConsumerState<EventTeamMatchPage> createState() => _EventTeamMatchPageState();
}
class _EventTeamMatchPageState extends ConsumerState<EventTeamMatchPage> {
final Set<String> _verifiedUserIds = <String>{};
/// 0 = 红队(teamA)1 = 蓝队(teamB)
int? _winnerSideIndex;
CompetitionTeamDetail get _detail => widget.detail;
/// 备注:teamA 为红队,teamB 为蓝队。
Matchup? get _firstMatchup {
final matchups = _detail.matchups;
if (matchups == null || matchups.isEmpty) return null;
return matchups.first;
}
/// 红队(teamA
Team? get _redRawTeam {
final teams = _firstMatchup?.teamA;
if (teams == null || teams.isEmpty) return null;
return teams.first;
}
/// 蓝队(teamB
Team? get _blueRawTeam {
final teams = _firstMatchup?.teamB;
if (teams == null || teams.isEmpty) return null;
return teams.first;
}
CompetitionTeam get _redTeam => _toCompetitionTeam(
_redRawTeam,
fallbackId: 'red-team',
fallbackName: '红队',
);
CompetitionTeam get _blueTeam => _toCompetitionTeam(
_blueRawTeam,
fallbackId: 'blue-team',
fallbackName: '蓝队',
);
List<EventTeamMember> get _redMembers =>
_toEventMembers(_redRawTeam?.players);
List<EventTeamMember> get _blueMembers =>
_toEventMembers(_blueRawTeam?.players);
CompetitionTeam _toCompetitionTeam(
Team? team, {
required String fallbackId,
required String fallbackName,
}) {
final id = team?.leaderUserId ?? '';
final name = team?.teamName?.trim() ?? '';
final players = (team?.players ?? const <Player>[])
.map(
(player) => CompetitionPlayer(
id: player.id?.trim() ?? '',
name: player.name?.trim() ?? '',
),
)
.toList(growable: false);
return CompetitionTeam(
id: id.isNotEmpty ? id : fallbackId,
name: name.isNotEmpty ? name : fallbackName,
players: players,
);
}
List<EventTeamMember> _toEventMembers(List<Player>? players) {
if (players == null || players.isEmpty) return const [];
return players
.map(
(player) => EventTeamMember(
userId: player.id?.trim() ?? '',
name: player.name?.trim() ?? '',
isLeader: player.isLeader ?? false,
),
)
.toList(growable: false);
}
@override
void initState() {
super.initState();
final initialPlayerId = widget.playerId.trim();
if (_isKnownMember(initialPlayerId)) {
_verifiedUserIds.add(initialPlayerId);
}
}
bool _isKnownMember(String userId) {
if (userId.isEmpty) return false;
return _redMembers.any((member) => member.userId == userId) ||
_blueMembers.any((member) => member.userId == userId);
}
String _memberNameOf(String userId) {
for (final member in [..._redMembers, ..._blueMembers]) {
if (member.userId == userId) {
return member.name.isEmpty ? '参赛成员' : member.name;
}
}
return '';
}
Future<void> _continueScan() async {
final scan = widget.qrScanner ?? AppQrScannerDialog.show;
final result = (await scan(context))?.trim();
if (!mounted || result == null || result.isEmpty) return;
if (!_isKnownMember(result)) {
AppToast.show('未找到对应参赛成员');
return;
}
if (_verifiedUserIds.contains(result)) {
AppToast.show('${_memberNameOf(result)}已完成核验');
return;
}
setState(() => _verifiedUserIds.add(result));
AppToast.show('${_memberNameOf(result)}核验成功');
}
Future<void> _manualProcess() async {
final matchup = _firstMatchup;
if (matchup == null) {
AppToast.show('暂无对阵信息');
return;
}
final winnerSide = await ManualWinnerDialog.show(
context,
matchup: matchup,
initialWinnerSideIndex: _winnerSideIndex,
);
if (!mounted || winnerSide == null) return;
final winnerTeam = winnerSide == 0 ? _redRawTeam : _blueRawTeam;
final loserTeam = winnerSide == 0 ? _blueRawTeam : _redRawTeam;
final winnerLeaderId = winnerTeam?.leaderUserId;
final loserLeaderId = loserTeam?.leaderUserId;
if (winnerLeaderId == null ||
winnerLeaderId.isEmpty ||
loserLeaderId == null ||
loserLeaderId.isEmpty) {
AppToast.show('无法识别双方队长');
return;
}
try {
await ref
.read(eventsServerProvider)
.setTeamStatus(
req: SetTeamStatusReq(
scheduleId: _detail.scheduleId ?? '',
opponentId: widget.item.opponentId,
teamScore: [
TeamScore(
userId: winnerLeaderId,
firstHalfScore: 0,
secondHalfScore: 0,
decisiveScore: 0,
ifWithdraw: true,
),
TeamScore(
userId: loserLeaderId,
firstHalfScore: 0,
secondHalfScore: 0,
decisiveScore: 0,
ifWithdraw: false,
),
],
),
);
if (!mounted) return;
setState(() => _winnerSideIndex = winnerSide);
final winnerName = winnerTeam?.teamName?.trim().isNotEmpty == true
? winnerTeam!.teamName!
: (winnerSide == 0 ? _redTeam.name : _blueTeam.name);
AppToast.show('已设置$winnerName直接获胜');
} catch (error) {
if (!mounted) return;
final message = error is ApiException && error.message.isNotEmpty
? error.message
: '设置失败,请重试';
AppToast.show(message);
}
}
void _startDirectly() {
AppNavigator.push(
buildTeamScorePage(item: widget.item, playerId: widget.playerId),
context: context,
);
}
@override
Widget build(BuildContext context) {
final redTeam = _redTeam;
final blueTeam = _blueTeam;
return Scaffold(
backgroundColor: const Color(0xFFF6F7F9),
appBar: myAppBar(
context: context,
titleWidget: Text(
'选手检录',
style: TextStyle(
fontSize: 14.sp,
fontWeight: FontWeight.w500,
color: Colors.white,
fontFamily: 'PingFang SC',
),
),
actions: [
TextButton(
key: const ValueKey('event-team-manual-process'),
onPressed: _manualProcess,
style: TextButton.styleFrom(
foregroundColor: Colors.white,
padding: EdgeInsets.symmetric(horizontal: 14.w),
minimumSize: Size(72.w, kToolbarHeight),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
child: Text(
'人工处理',
style: TextStyle(
fontSize: 14.sp,
fontWeight: FontWeight.w500,
color: Colors.white.withValues(alpha: 0.8),
fontFamily: 'PingFang SC',
),
),
),
],
),
body: SafeArea(
top: false,
child: Column(
children: [
// SizedBox(height: 10.h),
_MatchMetadata(detail: _detail),
// SizedBox(height: 12.h),
Expanded(
child: SingleChildScrollView(
padding: EdgeInsets.symmetric(horizontal: 0.w, vertical: 20.h),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_TeamCard(
sideLabel: '红方',
team: redTeam,
members: _redMembers,
backgroundImage: Assets.images.imageRedTeam.path,
accentColor: const Color(0xFFE84B5B),
verifiedUserIds: _verifiedUserIds,
winner: _winnerSideIndex == 0,
),
SizedBox(height: 8.h),
_TeamCard(
sideLabel: '蓝方',
team: blueTeam,
members: _blueMembers,
backgroundImage: Assets.images.imageBlueTeam.path,
accentColor: const Color(0xFF287FDD),
verifiedUserIds: _verifiedUserIds,
winner: _winnerSideIndex == 1,
emptyMessage: '暂无蓝队成员数据',
),
],
),
),
),
Padding(
padding: EdgeInsets.fromLTRB(16.w, 16.h, 16.w, 24.h),
child: Column(
children: [
_TeamActionButton(
label: '继续扫码',
iconPath: Assets.images.imageScan.path,
onPressed: _continueScan,
filled: true,
),
SizedBox(height: 12.h),
_TeamActionButton(
label: '直接开赛',
iconPath: 'assets/images/image_start.png',
onPressed: _startDirectly,
),
],
),
),
],
),
),
);
}
}
WebviewPage buildTeamScorePage({
required EventRegistrationItem item,
required String playerId,
}) {
return WebviewPage(
url: AppConfig.current.mainRefereeScoreH5Url,
eventRegistrationItem: item,
playerId: playerId,
);
}
class _MatchMetadata extends StatelessWidget {
const _MatchMetadata({required this.detail});
final CompetitionTeamDetail detail;
@override
Widget build(BuildContext context) {
final itemName = detail.itemName?.trim() ?? '';
final matchPlace = detail.matchPlace?.trim() ?? '';
final groupName = detail.groupName?.trim() ?? '';
return Container(
width: double.infinity,
padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 12.h),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.04),
blurRadius: 12.r,
offset: Offset(0, 4.h),
),
],
),
child: Row(
children: [
Expanded(
child: _MetadataText(label: '场地', value: matchPlace),
),
SizedBox(width: 6.w),
Expanded(
child: _MetadataText(label: '赛项', value: itemName),
),
SizedBox(width: 6.w),
Expanded(
child: _MetadataText(label: '组别', value: groupName),
),
],
),
);
}
}
class _MetadataText extends StatelessWidget {
const _MetadataText({required this.label, required this.value});
final String label;
final String value;
@override
Widget build(BuildContext context) {
return Text(
'$label${value.isEmpty ? '暂无' : value}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13.sp,
height: 1.35,
color: const Color(0xFF858B95),
fontWeight: FontWeight.w600,
fontFamily: 'PingFang SC',
),
);
}
}
class _TeamCard extends StatelessWidget {
const _TeamCard({
required this.sideLabel,
required this.team,
required this.members,
required this.backgroundImage,
required this.accentColor,
required this.verifiedUserIds,
required this.winner,
this.emptyMessage = '暂无成员数据',
});
final String sideLabel;
final CompetitionTeam team;
final List<EventTeamMember> members;
final String backgroundImage;
final Color accentColor;
final Set<String> verifiedUserIds;
final bool winner;
final String emptyMessage;
@override
Widget build(BuildContext context) {
final visibleMembers = members
.where((member) => member.userId.isNotEmpty || member.name.isNotEmpty)
.toList(growable: false);
final leader = _leaderOf(visibleMembers);
final players = visibleMembers
.where((member) => !identical(member, leader))
.toList(growable: false);
final leaderVerified =
leader != null && verifiedUserIds.contains(leader.userId);
return Container(
width: double.infinity,
constraints: BoxConstraints(minHeight: 106.h),
padding: EdgeInsets.fromLTRB(12.w, 16.h, 16.w, 12.h),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(backgroundImage),
fit: BoxFit.fill,
),
color: Colors.white,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Text(
'$sideLabel队伍名称${team.name}队伍',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 16.sp,
fontWeight: FontWeight.w700,
color: const Color(0xFF30343B),
fontFamily: 'PingFang SC',
),
),
),
if (winner)
Container(
key: ValueKey('event-team-winner-${team.id}'),
padding: EdgeInsets.symmetric(
horizontal: 10.w,
vertical: 4.h,
),
decoration: BoxDecoration(
color: accentColor,
borderRadius: BorderRadius.circular(12.r),
),
child: Text(
'胜方',
style: TextStyle(
color: Colors.white,
fontSize: 11.sp,
fontWeight: FontWeight.w700,
fontFamily: 'PingFang SC',
),
),
),
],
),
SizedBox(height: 6.h),
if (visibleMembers.isEmpty)
Text(
emptyMessage,
style: TextStyle(
fontSize: 13.sp,
color: const Color(0xFF747D89),
fontFamily: 'PingFang SC',
),
)
else ...[
if (leader != null)
_TeamTextLine(
label: '队长',
text: _formatMember(leader),
showOk: verifiedUserIds.contains(leader.userId),
),
if (players.isNotEmpty)
Row(
children: [
Text(
'选手:',
style: TextStyle(
fontSize: 13.sp,
height: 1.35,
color: const Color(0xFF747B86),
fontWeight: FontWeight.w500,
fontFamily: 'PingFang SC',
),
),
...players.map(
(member) => Row(
children: [
Text(
_formatMember(member),
style: TextStyle(
fontSize: 13.sp,
height: 1.35,
color: const Color(0xFF4D545F),
),
),
if (verifiedUserIds.contains(member.userId))
Padding(
padding: EdgeInsets.only(left: 6.w),
child: Image.asset(
Assets.images.imageOk.path,
width: 18.w,
height: 14.h,
fit: BoxFit.contain,
),
),
Text(
(member != players.last ? '' : ''),
style: TextStyle(
fontSize: 13.sp,
height: 1.35,
color: const Color(0xFF4D545F),
),
),
],
),
),
],
),
],
],
),
);
}
EventTeamMember? _leaderOf(List<EventTeamMember> members) {
for (final member in members) {
if (member.isLeader) return member;
}
return members.isEmpty ? null : members.first;
}
String _formatMember(EventTeamMember member) {
final name = member.name.trim().isEmpty ? '暂无' : member.name.trim();
// final id = member.userId.trim();
// return id.isEmpty ? name : '$name$id';
return name;
}
}
class _TeamTextLine extends StatelessWidget {
const _TeamTextLine({
required this.label,
required this.text,
required this.showOk,
});
final String label;
final String text;
final bool showOk;
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top: 4.h),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
'$label',
style: TextStyle(
fontSize: 13.sp,
height: 1.35,
color: const Color(0xFF747B86),
fontWeight: FontWeight.w500,
fontFamily: 'PingFang SC',
),
),
Flexible(
child: Text(
text.isEmpty ? '暂无' : text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13.sp,
height: 1.35,
color: const Color(0xFF4D545F),
fontWeight: FontWeight.w500,
fontFamily: 'PingFang SC',
),
),
),
if (showOk)
Padding(
padding: EdgeInsets.only(left: 6.w),
child: Image.asset(
Assets.images.imageOk.path,
width: 18.w,
height: 14.h,
fit: BoxFit.contain,
),
),
],
),
);
}
}
class _TeamActionButton extends StatelessWidget {
const _TeamActionButton({
required this.label,
required this.iconPath,
required this.onPressed,
this.filled = false,
});
final String label;
final String iconPath;
final VoidCallback onPressed;
final bool filled;
@override
Widget build(BuildContext context) {
final radius = BorderRadius.circular(28.r);
final content = Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Image.asset(
iconPath,
width: filled ? 18.w : 18.w,
height: filled ? 18.h : 18.h,
fit: BoxFit.contain,
),
SizedBox(width: 4.w),
Text(
label,
style: TextStyle(
color: filled ? Colors.white : const Color(0xFF359FED),
fontSize: 16.sp,
fontWeight: FontWeight.w700,
fontFamily: 'PingFang SC',
),
),
],
);
return SizedBox(
width: double.infinity,
height: 45.h,
child: DecoratedBox(
decoration: BoxDecoration(
gradient: filled
? const LinearGradient(
colors: [Color(0xFF2F8DFF), Color(0xFF57D2EE)],
)
: null,
color: filled ? null : Colors.white,
borderRadius: radius,
border: filled
? null
: Border.all(color: const Color(0xFF9FD0F5), width: 1.w),
boxShadow: filled
? [
BoxShadow(
color: const Color(0xFF2F8DFF).withValues(alpha: 0.24),
blurRadius: 10.r,
offset: Offset(0, 5.h),
),
]
: null,
),
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onPressed,
borderRadius: radius,
child: Center(child: content),
),
),
),
);
}
}
@@ -0,0 +1,49 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:recording_tool/app/config/api_common.dart';
import 'package:recording_tool/core/network/api_client.dart';
import 'package:recording_tool/core/network/providers/dio_providers.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team_detail.dart';
final competitionTeamsServerProvider = Provider<CompetitionTeamsServer>((ref) {
return CompetitionTeamsServer(ref.watch(apiClientProvider));
});
class CompetitionTeamsServer {
CompetitionTeamsServer(this._apiClient);
final ApiClient _apiClient;
Future<CompetitionTeamPageResult> fetchPage({
required int page,
required int pageSize,
}) {
return _apiClient.get(
AuthApi.getTeamList.path,
queryParameters: {'page': page, 'pageSize': pageSize},
parser: (json) => CompetitionTeamPageResult.fromJson(
json,
page: page,
pageSize: pageSize,
),
);
}
Future<CompetitionTeamDetail> fetchTeamDetail({
required String itemId,
required String eventId,
String? scheduleId,
String? opponentId,
}) {
return _apiClient.post(
AuthApi.getTeamDetail.path,
data: {
'itemId': itemId,
'eventId': eventId,
'scheduleId': scheduleId,
'opponentId': opponentId,
},
parser: (json) => CompetitionTeamDetail.fromResponse(json),
);
}
}
@@ -0,0 +1,42 @@
import 'package:recording_tool/features/competition_teams/model/model_competition_team.dart';
class CompetitionTeamsState {
const CompetitionTeamsState({
this.items = const [],
this.page = 0,
this.hasMore = true,
this.isInitialLoading = false,
this.isRefreshing = false,
this.isLoadingMore = false,
this.errorMessage,
});
final List<CompetitionTeamListItem> items;
final int page;
final bool hasMore;
final bool isInitialLoading;
final bool isRefreshing;
final bool isLoadingMore;
final String? errorMessage;
CompetitionTeamsState copyWith({
List<CompetitionTeamListItem>? items,
int? page,
bool? hasMore,
bool? isInitialLoading,
bool? isRefreshing,
bool? isLoadingMore,
String? errorMessage,
bool clearError = false,
}) {
return CompetitionTeamsState(
items: items ?? this.items,
page: page ?? this.page,
hasMore: hasMore ?? this.hasMore,
isInitialLoading: isInitialLoading ?? this.isInitialLoading,
isRefreshing: isRefreshing ?? this.isRefreshing,
isLoadingMore: isLoadingMore ?? this.isLoadingMore,
errorMessage: clearError ? null : errorMessage ?? this.errorMessage,
);
}
}
@@ -0,0 +1,98 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/legacy.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team.dart';
import 'package:recording_tool/features/competition_teams/server/server_competition_teams.dart';
import 'package:recording_tool/features/competition_teams/state/state_competition_teams.dart';
final competitionTeamsProvider =
StateNotifierProvider<CompetitionTeamsViewModel, CompetitionTeamsState>((
ref,
) {
return CompetitionTeamsViewModel(ref);
});
class CompetitionTeamsViewModel extends StateNotifier<CompetitionTeamsState> {
CompetitionTeamsViewModel(this._ref) : super(const CompetitionTeamsState());
static const pageSize = 5;
final Ref _ref;
Future<void> loadInitial() async {
state = state.copyWith(
isInitialLoading: true,
isLoadingMore: false,
isRefreshing: false,
clearError: true,
);
await _loadPage(page: 1, replace: true);
}
Future<void> refresh() async {
if (state.isRefreshing) return;
state = state.copyWith(isRefreshing: true, clearError: true);
await _loadPage(page: 1, replace: true);
}
Future<void> loadMore() async {
if (!state.hasMore || state.isLoadingMore || state.isInitialLoading) return;
state = state.copyWith(isLoadingMore: true, clearError: true);
await _loadPage(page: state.page + 1, replace: false);
}
void selectWinner({
required String itemId,
required String matchupId,
required String winnerTeamId,
}) {
final updatedItems = state.items
.map((item) {
if (item.itemId != itemId) return item;
final updatedMatchups = item.matchups
.map((matchup) {
if (matchup.id != matchupId) return matchup;
final validWinner =
winnerTeamId == matchup.teamA.id ||
winnerTeamId == matchup.teamB.id;
return validWinner
? matchup.copyWith(winnerTeamId: winnerTeamId)
: matchup;
})
.toList(growable: false);
return item.copyWith(matchups: updatedMatchups);
})
.toList(growable: false);
state = state.copyWith(items: updatedItems);
}
CompetitionTeamListItem? findItem(String itemId) {
for (final item in state.items) {
if (item.itemId == itemId) return item;
}
return null;
}
Future<void> _loadPage({required int page, required bool replace}) async {
try {
final result = await _ref
.read(competitionTeamsServerProvider)
.fetchPage(page: page, pageSize: pageSize);
state = state.copyWith(
items: replace ? result.items : [...state.items, ...result.items],
page: result.page,
hasMore: result.hasMore,
isInitialLoading: false,
isRefreshing: false,
isLoadingMore: false,
clearError: true,
);
} catch (error) {
state = state.copyWith(
isInitialLoading: false,
isRefreshing: false,
isLoadingMore: false,
errorMessage: '参赛队伍加载失败,请重试',
);
}
}
}
@@ -0,0 +1,353 @@
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team_detail.dart';
import 'package:recording_tool/gen/assets.gen.dart';
/// 弹窗回传选中侧索引:0 = teamA(红队),1 = teamB(蓝队)
class ManualWinnerDialog extends StatefulWidget {
const ManualWinnerDialog({
super.key,
required this.matchup,
this.initialWinnerSideIndex,
});
final Matchup matchup;
final int? initialWinnerSideIndex;
static Future<int?> show(
BuildContext context, {
required Matchup matchup,
int? initialWinnerSideIndex,
}) {
return showDialog<int>(
context: context,
barrierDismissible: false,
builder: (_) => ManualWinnerDialog(
matchup: matchup,
initialWinnerSideIndex: initialWinnerSideIndex,
),
);
}
@override
State<ManualWinnerDialog> createState() => _ManualWinnerDialogState();
}
class _ManualWinnerDialogState extends State<ManualWinnerDialog> {
/// 0 = teamA1 = teamB
int? _selectedSideIndex;
Team? get _teamA {
final teams = widget.matchup.teamA;
if (teams == null || teams.isEmpty) return null;
return teams.first;
}
Team? get _teamB {
final teams = widget.matchup.teamB;
if (teams == null || teams.isEmpty) return null;
return teams.first;
}
@override
void initState() {
super.initState();
final initial = widget.initialWinnerSideIndex;
if (initial == 0 || initial == 1) {
_selectedSideIndex = initial;
}
}
@override
Widget build(BuildContext context) {
final teamA = _teamA;
final teamB = _teamB;
final maxHeight = MediaQuery.sizeOf(context).height * 0.78;
return Dialog(
insetPadding: EdgeInsets.symmetric(horizontal: 48.w),
backgroundColor: Colors.transparent,
elevation: 0,
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 380.w, maxHeight: maxHeight),
child: Stack(
clipBehavior: Clip.none,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(16.r),
child: Material(
color: Colors.white,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: EdgeInsets.fromLTRB(18.w, 18.h, 18.w, 18.h),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(height: 26.h),
Text(
'请在比赛结束前处理',
key: const ValueKey('manual-winner-dialog-title'),
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18.sp,
height: 1.3,
fontWeight: FontWeight.w700,
color: const Color(0xFF20242B),
fontFamily: 'PingFang SC',
),
),
SizedBox(height: 16.h),
if (teamA != null) ...[
_TeamChoice(
team: teamA,
sideIndex: 0,
color: const Color(0xFFFF6575),
selected: _selectedSideIndex == 0,
onTap: () =>
setState(() => _selectedSideIndex = 0),
),
SizedBox(height: 10.h),
],
if (teamB != null)
_TeamChoice(
team: teamB,
sideIndex: 1,
color: const Color(0xFF21C5AC),
selected: _selectedSideIndex == 1,
onTap: () =>
setState(() => _selectedSideIndex = 1),
),
SizedBox(height: 18.h),
Row(
children: [
Expanded(
child: _DialogActionButton(
label: '取消',
onPressed: () =>
Navigator.of(context).pop(),
),
),
SizedBox(width: 14.w),
Expanded(
child: _DialogActionButton(
label: '确定',
filled: true,
onPressed: _selectedSideIndex == null
? null
: () => Navigator.of(
context,
).pop(_selectedSideIndex),
),
),
],
),
],
),
),
],
),
),
),
),
Positioned(
top: -90.h,
left: 0,
right: 0,
child: Image.asset(
Assets.images.imageDialogBg.path,
width: double.infinity,
height: 112.h,
fit: BoxFit.cover,
alignment: Alignment.topCenter,
),
),
],
),
),
);
}
}
class _TeamChoice extends StatelessWidget {
const _TeamChoice({
required this.team,
required this.sideIndex,
required this.color,
required this.selected,
required this.onTap,
});
final Team team;
final int sideIndex;
final Color color;
final bool selected;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final name = team.teamName?.trim().isNotEmpty == true
? team.teamName!
: '未命名队伍';
final players = team.playerNames;
final backgroundColor = selected
? color.withValues(alpha: 0.13)
: color.withValues(alpha: 0.07);
return Semantics(
selected: selected,
button: true,
label: '选择$name直接获胜',
child: Material(
color: backgroundColor,
borderRadius: BorderRadius.circular(12.r),
child: InkWell(
key: ValueKey('winner-choice-side-$sideIndex'),
onTap: onTap,
borderRadius: BorderRadius.circular(12.r),
child: Container(
width: double.infinity,
padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.h),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12.r),
border: Border.all(
color: selected ? color : color.withValues(alpha: 0.32),
width: 1,
),
),
child: Row(
children: [
AnimatedContainer(
duration: const Duration(milliseconds: 160),
width: 22.r,
height: 22.r,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: selected ? color : const Color(0xFFB0B4BB),
width: 1.2.r,
),
color: Colors.transparent,
),
child: selected
? Center(
child: Container(
width: 10.r,
height: 10.r,
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
),
),
)
: null,
),
SizedBox(width: 12.w),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 17.sp,
height: 1.25,
fontWeight: FontWeight.w700,
color: const Color(0xFF20242B),
fontFamily: 'PingFang SC',
),
),
if (players.isNotEmpty) ...[
SizedBox(height: 4.h),
Text(
players,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 15.sp,
height: 1.25,
color: const Color(0xFF69717E),
fontFamily: 'PingFang SC',
),
),
],
],
),
),
SizedBox(width: 8.w),
Text(
'直接获胜',
maxLines: 1,
style: TextStyle(
fontSize: 15.sp,
fontWeight: FontWeight.w700,
color: color,
fontFamily: 'PingFang SC',
),
),
],
),
),
),
),
);
}
}
class _DialogActionButton extends StatelessWidget {
const _DialogActionButton({
required this.label,
required this.onPressed,
this.filled = false,
});
final String label;
final VoidCallback? onPressed;
final bool filled;
@override
Widget build(BuildContext context) {
final enabled = onPressed != null;
final radius = BorderRadius.circular(24.r);
final backgroundColor = filled
? (enabled ? null : const Color(0xFFD2D3D8))
: const Color(0xFFF1F1F1);
final gradient = filled && enabled
? const LinearGradient(colors: [Color(0xFF2F8DFF), Color(0xFF58D1EE)])
: null;
return SizedBox(
height: 40.h,
child: DecoratedBox(
decoration: BoxDecoration(
color: backgroundColor,
gradient: gradient,
borderRadius: radius,
),
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onPressed,
borderRadius: radius,
child: Center(
child: Text(
label,
style: TextStyle(
fontSize: 15.sp,
fontWeight: FontWeight.w500,
color: filled
? (enabled ? Colors.white : const Color(0xFF8D9098))
: const Color(0xFF343941),
fontFamily: 'PingFang SC',
),
),
),
),
),
),
);
}
}
@@ -0,0 +1,340 @@
import 'package:recording_tool/features/recording/model/model_recording_context.dart';
class PlayerRegistrationListReq {
const PlayerRegistrationListReq({required this.userId, this.status = ''});
final String userId;
final String status;
Map<String, dynamic> toFormDataMap() {
return {'userId': userId, 'status': status};
}
}
class StreamKeyReq {
const StreamKeyReq({
required this.eventId,
required this.itemId,
required this.userId,
});
final String eventId;
final String itemId;
final String userId;
Map<String, dynamic> toFormDataMap() {
return {'eventId': eventId, 'itemId': itemId, 'userId': userId};
}
}
class EventProfile {
const EventProfile({
required this.name,
required this.phone,
required this.eventTitle,
this.avatarUrl = '',
this.avatarLabel = '头像',
});
final String name;
final String phone;
final String eventTitle;
final String avatarUrl;
final String avatarLabel;
}
class EventTeamMember {
const EventTeamMember({
required this.userId,
required this.name,
required this.isLeader,
});
final String userId;
final String name;
final bool isLeader;
factory EventTeamMember.fromJson(Map<dynamic, dynamic> json) {
final map = Map<String, dynamic>.from(json);
return EventTeamMember(
userId: _readString(map, const ['userId']),
name: _readString(map, const ['name']),
isLeader: _readBool(map, const ['isLeader']),
);
}
}
class EventRegistrationList {
const EventRegistrationList({
required this.userId,
required this.name,
required this.avatar,
required this.total,
required this.items,
});
final String userId;
final String name;
final String avatar;
final int total;
final List<EventRegistrationItem> items;
factory EventRegistrationList.fromJson(dynamic json) {
final map = _extractObject(json);
final rawItems = _extractList(json);
final userId = _readString(map, const ['userId']);
final name = _readString(map, const [
'name',
'playerName',
'userName',
'realName',
]);
final avatar = _readString(map, const ['avatar', 'avatarUrl']);
return EventRegistrationList(
userId: userId,
name: name,
avatar: avatar,
total: _readInt(map, const ['total'], fallback: rawItems.length),
items: rawItems
.whereType<Map>()
.map(
(item) => EventRegistrationItem.fromJson(
item,
userId: userId,
playerName: name,
),
)
.toList(),
);
}
EventProfile toProfile() {
return EventProfile(
name: name,
phone: '',
eventTitle: items.isEmpty ? '赛事信息' : items.first.eventName,
avatarUrl: avatar,
);
}
}
class EventRegistrationItem {
const EventRegistrationItem({
required this.eventId,
required this.itemId,
required this.scheduleId,
required this.eventName,
required this.itemName,
required this.groupName,
required this.matchPlace,
this.matchStartTime = '',
this.matchEndTime = '',
this.completed = false,
this.opponentId = '',
this.opponentName = '',
this.teamMembers = const [],
this.userId = '',
this.playerName = '',
this.playerPhone = '',
this.playerNo = '',
});
final String eventId;
final String itemId;
final String scheduleId;
final String eventName;
final String itemName;
final String groupName;
final String matchPlace;
final String matchStartTime;
final String matchEndTime;
final bool completed;
final String opponentId;
final String opponentName;
final List<EventTeamMember> teamMembers;
final String playerNo;
/// 来自报名列表父级,不在 item JSON 内
final String userId;
final String playerName;
final String playerPhone;
String get scheduleTime => _formatScheduleTime(matchStartTime, matchEndTime);
String? get statusLabel => completed ? '已完成' : null;
EventTeamMember? get teamLeader {
for (final member in teamMembers) {
if (member.isLeader) return member;
}
return teamMembers.isEmpty ? null : teamMembers.first;
}
factory EventRegistrationItem.fromJson(
Map<dynamic, dynamic> json, {
String userId = '',
String playerName = '',
}) {
final map = Map<String, dynamic>.from(json);
final startTime = _readString(map, const ['matchStartTime']);
final endTime = _readString(map, const ['matchEndTime']);
final teamMembersRaw = map['teamMembers'];
return EventRegistrationItem(
eventId: _readString(map, const ['eventId']),
itemId: _readString(map, const ['itemId']),
scheduleId: _readString(map, const ['scheduleId']),
eventName: _readString(map, const ['eventName'], fallback: '赛事信息'),
itemName: _readString(map, const ['itemName'], fallback: '未命名项目'),
groupName: _readString(map, const ['groupName']),
matchPlace: _readString(map, const ['matchPlace']),
matchStartTime: startTime,
matchEndTime: endTime,
completed: _readBool(map, const ['completed']),
opponentId: _readString(map, const ['opponentId']),
opponentName: _readString(map, const ['opponentName']),
teamMembers: teamMembersRaw is List
? teamMembersRaw
.whereType<Map>()
.map(EventTeamMember.fromJson)
.toList(growable: false)
: const [],
userId: userId,
playerName: playerName,
playerNo: _readString(map, const ['playerNo']),
);
}
EventProfile toProfile() {
return EventProfile(
name: playerName,
phone: playerPhone,
eventTitle: eventName,
);
}
RecordingContext toRecordingContext({EventProfile? profile}) {
return RecordingContext(
eventTitle: eventName,
matchName: itemName,
group: groupName,
venue: matchPlace,
time: scheduleTime,
playerName: profile?.name ?? playerName,
playerPhone: profile?.phone ?? playerPhone,
status: statusLabel,
);
}
}
class StreamKeyResponse {
const StreamKeyResponse({required this.rawData});
final Map<String, dynamic> rawData;
factory StreamKeyResponse.fromJson(dynamic json) {
if (json is Map) {
return StreamKeyResponse(rawData: Map<String, dynamic>.from(json));
}
return StreamKeyResponse(rawData: {'value': json});
}
@override
String toString() => rawData.toString();
}
List<dynamic> _extractList(dynamic json) {
if (json is List) return json;
if (json is Map) {
for (final key in const ['records', 'items', 'rows', 'list', 'data']) {
final value = json[key];
if (value is List) return value;
if (value is Map) {
final nested = _extractList(value);
if (nested.isNotEmpty) return nested;
}
}
}
return const [];
}
Map<String, dynamic> _extractObject(dynamic json) {
if (json is Map) {
final map = Map<String, dynamic>.from(json);
final data = map['data'];
if (data is Map) return Map<String, dynamic>.from(data);
return map;
}
return const {};
}
String _readString(
Map<String, dynamic> map,
List<String> keys, {
String fallback = '',
}) {
return _readNullableString(map, keys) ?? fallback;
}
String _formatScheduleTime(String startTime, String endTime) {
if (startTime.isNotEmpty && endTime.isNotEmpty) {
return '$startTime-$endTime';
}
if (startTime.isNotEmpty) return startTime;
if (endTime.isNotEmpty) return endTime;
return '';
}
int _readInt(Map<String, dynamic> map, List<String> keys, {int fallback = 0}) {
for (final key in keys) {
final value = _findValue(map, key);
if (value is int) return value;
if (value is num) return value.toInt();
if (value is String) {
final parsed = int.tryParse(value.trim());
if (parsed != null) return parsed;
}
}
return fallback;
}
bool _readBool(Map<String, dynamic> map, List<String> keys) {
for (final key in keys) {
final value = _findValue(map, key);
if (value is bool) return value;
if (value is num) return value != 0;
if (value is String) {
final text = value.trim().toLowerCase();
if (text == 'true' || text == '1') return true;
if (text == 'false' || text == '0') return false;
}
}
return false;
}
String? _readNullableString(Map<String, dynamic> map, List<String> keys) {
for (final key in keys) {
final value = _findValue(map, key);
if (value == null) continue;
final text = value.toString().trim();
if (text.isNotEmpty) return text;
}
return null;
}
dynamic _findValue(dynamic value, String key) {
if (value is Map) {
if (value.containsKey(key)) return value[key];
for (final child in value.values) {
final found = _findValue(child, key);
if (found != null) return found;
}
}
if (value is List) {
for (final child in value) {
final found = _findValue(child, key);
if (found != null) return found;
}
}
return null;
}
@@ -0,0 +1,530 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/app/config/app_config.dart';
import 'package:recording_tool/app/router/app_navigator.dart';
import 'package:recording_tool/features/competition_teams/model/model_competition_team_detail.dart';
import 'package:recording_tool/features/competition_teams/pages/page_event_team_match.dart';
import 'package:recording_tool/features/competition_teams/server/server_competition_teams.dart';
import 'package:recording_tool/features/events/model/model_event_info.dart';
import 'package:recording_tool/features/events/state/state_event_info.dart';
import 'package:recording_tool/features/events/view_model/view_model_event_info.dart';
import 'package:recording_tool/gen/assets.gen.dart';
import 'package:recording_tool/shared/widgets/app_webview.dart';
import 'package:recording_tool/shared/widgets/widgets.dart';
class EventInfoPage extends ConsumerStatefulWidget {
const EventInfoPage({super.key, required this.playerId});
final String playerId;
@override
ConsumerState<EventInfoPage> createState() => _EventInfoPageState();
}
class _EventInfoPageState extends ConsumerState<EventInfoPage> {
@override
void initState() {
super.initState();
}
Future<void> onItemTap(EventRegistrationItem item) async {
if (!mounted) return;
CompetitionTeamDetail? detail;
if (item.opponentId.isNotEmpty && item.opponentId != '0') {
detail = await ref
.read(competitionTeamsServerProvider)
.fetchTeamDetail(
itemId: item.itemId,
eventId: item.eventId,
scheduleId: item.scheduleId,
opponentId: item.opponentId,
);
if (!mounted) return;
AppNavigator.push(
buildEventRegistrationDestination(
item: item,
playerId: widget.playerId,
detail: detail,
),
context: context,
);
return;
}
if (!mounted) return;
AppNavigator.push(
buildEventRegistrationDestination(
item: item,
playerId: widget.playerId,
detail: null,
),
context: context,
);
}
@override
Widget build(BuildContext context) {
final state = ref.watch(eventInfoProvider);
final profile = state.profile;
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.light.copyWith(
statusBarColor: Colors.transparent,
systemNavigationBarColor: const Color(0xFFF5F6F8),
),
child: Scaffold(
backgroundColor: const Color(0xFFF5F6F8),
appBar: myAppBar(context: context),
body: Stack(
children: [
const _TopGradientHeader(),
SafeArea(
bottom: false,
child: Column(
children: [
// _Header(onBack: () => AppNavigator.pop(context: context)),
SizedBox(height: 10.h),
Padding(
padding: EdgeInsets.symmetric(horizontal: 10.w),
child: _ProfileSection(
profile: profile,
eventTitle: state.eventTitle,
),
),
SizedBox(height: 8.h),
Expanded(
child: _ScheduleList(
state: state,
onRetry: () => ref
.read(eventInfoProvider.notifier)
.loadRegistrationList(),
onItemTap: onItemTap,
),
),
],
),
),
],
),
),
);
}
}
class _TopGradientHeader extends StatelessWidget {
const _TopGradientHeader();
@override
Widget build(BuildContext context) {
return Positioned(
top: -10.h,
left: 0,
right: 0,
child: SizedBox(
height: 219.h,
width: double.infinity,
child: Image.asset(Assets.images.imageEventInfoBarBg.path),
),
);
}
}
Widget buildEventRegistrationDestination({
required EventRegistrationItem item,
required String playerId,
required CompetitionTeamDetail? detail,
}) {
if (detail != null) {
return EventTeamMatchPage(playerId: playerId, detail: detail, item: item);
}
return WebviewPage(
url: AppConfig.current.mainRefereeScoreH5Url,
eventRegistrationItem: item,
playerId: playerId,
);
}
class _Header extends StatelessWidget {
const _Header({required this.onBack});
final VoidCallback onBack;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 44.h,
child: Align(
alignment: Alignment.centerLeft,
child: IconButton(
onPressed: onBack,
icon: Icon(Icons.chevron_left_rounded, size: 28.r),
color: Colors.white,
tooltip: '返回',
padding: EdgeInsets.only(left: 10.w),
constraints: BoxConstraints(minWidth: 44.w, minHeight: 44.h),
),
),
);
}
}
class _ProfileSection extends StatelessWidget {
const _ProfileSection({required this.profile, required this.eventTitle});
final EventProfile profile;
final String eventTitle;
@override
Widget build(BuildContext context) {
final title = eventTitle.trim().isEmpty ? '赛事信息' : eventTitle.trim();
return Container(
clipBehavior: Clip.antiAlias,
padding: EdgeInsets.fromLTRB(12.w, 10.h, 12.w, 12.h),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(6.r),
),
child: Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
profile.avatarUrl.isEmpty
? AppAvatar(
size: 52.r,
initials: profile.name.isEmpty ? 'S' : profile.name,
)
: AppAvatar(size: 52.r, imageUrl: profile.avatarUrl),
SizedBox(width: 12.w),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
profile.name.isEmpty ? '参赛选手' : profile.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 18.sp,
height: 1.2,
color: const Color(0xFF33363B),
fontWeight: FontWeight.w700,
),
),
SizedBox(height: 5.h),
Text(
profile.phone,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 10.sp,
height: 1.2,
color: const Color(0xFF969CA6),
),
),
],
),
),
],
),
SizedBox(height: 10.h),
Divider(
height: 1.h,
thickness: 1.h,
color: const Color(0xFFE8EAED),
),
SizedBox(height: 10.h),
_EventTitleHighlight(title: title),
],
),
],
),
);
}
}
class _EventTitleHighlight extends StatelessWidget {
const _EventTitleHighlight({required this.title});
final String title;
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.centerLeft,
child: IntrinsicWidth(
child: Stack(
alignment: Alignment.bottomLeft,
children: [
Positioned(
left: 0,
right: 0,
bottom: 2.h,
child: Container(
height: 8.h,
decoration: BoxDecoration(
color: const Color(0xFFB8F5E8),
borderRadius: BorderRadius.circular(4.r),
),
),
),
Text(
title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 16.sp,
height: 1.25,
color: const Color(0xFF33363B),
fontWeight: FontWeight.w600,
),
),
],
),
),
);
}
}
class _ScheduleList extends StatelessWidget {
const _ScheduleList({
required this.state,
required this.onRetry,
required this.onItemTap,
});
final EventInfoState state;
final VoidCallback onRetry;
final ValueChanged<EventRegistrationItem> onItemTap;
@override
Widget build(BuildContext context) {
if (state.items.isEmpty) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'暂无赛事报名信息',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 16.sp, color: const Color(0xFF3A3D42)),
),
SizedBox(height: 14.h),
TextButton(onPressed: onRetry, child: const Text('重新加载')),
],
),
);
}
return ListView.separated(
padding: EdgeInsets.fromLTRB(10.w, 0, 10.w, 24.h),
itemCount: state.items.length,
separatorBuilder: (_, _) => SizedBox(height: 8.h),
itemBuilder: (context, index) {
final item = state.items[index];
return _ScheduleCard(
item: item,
scheduleIndex: index + 1,
onTap: () => onItemTap(item),
);
},
);
}
}
class _ScheduleCard extends StatelessWidget {
const _ScheduleCard({
required this.item,
required this.scheduleIndex,
required this.onTap,
});
final EventRegistrationItem item;
final int scheduleIndex;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Material(
color: Colors.white,
borderRadius: BorderRadius.circular(6.r),
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(6.r),
child: Container(
constraints: BoxConstraints(minHeight: 86.h),
padding: EdgeInsets.fromLTRB(12.w, 10.h, 14.w, 10.h),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(6.r),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: _ScheduleDetails(
item: item,
scheduleIndex: scheduleIndex,
),
),
SizedBox(width: 12.w),
_ScheduleStatus(item: item),
],
),
),
),
);
}
}
class _ScheduleDetails extends StatelessWidget {
const _ScheduleDetails({required this.item, required this.scheduleIndex});
final EventRegistrationItem item;
final int scheduleIndex;
@override
Widget build(BuildContext context) {
final memberLine = _formatMemberLine(item);
final opponentLine = _formatOpponentLine(item);
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_formatTitle(item),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13.sp,
height: 1.2,
color: const Color(0xFF30343A),
fontWeight: FontWeight.w700,
),
),
SizedBox(height: 6.h),
_MetaText(_formatVenue(item, scheduleIndex)),
SizedBox(height: 3.h),
_MetaText(_formatScheduleTime(item)),
if (memberLine.isNotEmpty) ...[
SizedBox(height: 3.h),
_MetaText(memberLine),
],
if (opponentLine.isNotEmpty) ...[
SizedBox(height: 3.h),
_MetaText(opponentLine),
],
],
);
}
}
class _MetaText extends StatelessWidget {
const _MetaText(this.text);
final String text;
@override
Widget build(BuildContext context) {
return Text(
text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 10.sp,
height: 1.2,
color: const Color(0xFF6E747D),
fontWeight: FontWeight.w400,
),
);
}
}
class _ScheduleStatus extends StatelessWidget {
const _ScheduleStatus({required this.item});
final EventRegistrationItem item;
@override
Widget build(BuildContext context) {
final status = item.statusLabel;
if (status != null) {
return Text(
status,
style: TextStyle(
fontSize: 10.sp,
height: 1.2,
color: const Color(0xFF1DBF73),
fontWeight: FontWeight.w500,
),
);
}
return Text(
_formatNumberBadge(item),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 20.sp,
height: 1,
color: const Color(0xFFF27D69),
fontWeight: FontWeight.w700,
),
);
}
}
String _formatTitle(EventRegistrationItem item) {
if (item.groupName.isEmpty) return item.itemName;
return '${item.itemName} ${item.groupName}';
}
String _formatVenue(EventRegistrationItem item, int scheduleIndex) {
final place = item.matchPlace.trim();
if (place.isEmpty) return '$scheduleIndex号场馆$scheduleIndex区';
return '$place号场馆$scheduleIndex区';
}
String _formatScheduleTime(EventRegistrationItem item) {
final start = DateTime.tryParse(item.matchStartTime);
final end = DateTime.tryParse(item.matchEndTime);
if (start == null && end == null) return item.scheduleTime;
if (start != null && end != null) {
return '${start.month}${start.day}${_formatClock(start)}-${_formatClock(end)}';
}
final value = start ?? end!;
return '${value.month}${value.day}${_formatClock(value)}';
}
String _formatClock(DateTime value) {
return '${value.hour}:${value.minute.toString().padLeft(2, '0')}';
}
String _formatMemberLine(EventRegistrationItem item) {
final names = item.teamMembers
.map((member) => member.name.trim())
.where((name) => name.isNotEmpty)
.toList(growable: false);
return names.join('');
}
String _formatOpponentLine(EventRegistrationItem item) {
final opponent = item.opponentName.trim();
if (opponent.isEmpty) return '';
return '对手:$opponent';
}
String _formatNumberBadge(EventRegistrationItem item) {
return item.playerNo.trim().isEmpty ? '' : '${item.playerNo.trim()}';
// final place = item.matchPlace.trim();
// if (place.isEmpty) return '';
// final match = RegExp(r'\d+').firstMatch(place);
// if (match != null) return '${match.group(0)}号';
// return place;
}
@@ -0,0 +1,58 @@
class SetTeamStatusReq {
final String scheduleId;
final String opponentId;
final List<TeamScore> teamScore;
SetTeamStatusReq({
required this.scheduleId,
required this.opponentId,
required this.teamScore,
});
factory SetTeamStatusReq.fromJson(Map<String, dynamic> json) =>
SetTeamStatusReq(
scheduleId: json['scheduleId'],
opponentId: json['opponentId'],
teamScore: List<TeamScore>.from(
json['teamScore'].map((x) => TeamScore.fromJson(x)),
),
);
Map<String, dynamic> toJson() => {
'scheduleId': scheduleId,
'opponentId': opponentId,
'teamScore': List<dynamic>.from(teamScore.map((x) => x.toJson())),
};
}
class TeamScore {
final String userId;
final int firstHalfScore;
final int secondHalfScore;
final int decisiveScore;
final bool ifWithdraw;
TeamScore({
required this.userId,
required this.firstHalfScore,
required this.secondHalfScore,
required this.decisiveScore,
required this.ifWithdraw,
});
factory TeamScore.fromJson(Map<String, dynamic> json) => TeamScore(
userId: json['userId'],
firstHalfScore: json['firstHalfScore'],
secondHalfScore: json['secondHalfScore'],
decisiveScore: json['decisiveScore'],
ifWithdraw: json['ifWithdraw'],
);
Map<String, dynamic> toJson() => {
'userId': userId,
'firstHalfScore': firstHalfScore,
'secondHalfScore': secondHalfScore,
'decisiveScore': decisiveScore,
'ifWithdraw': ifWithdraw,
};
}
@@ -0,0 +1,48 @@
import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:recording_tool/app/config/api_common.dart';
import 'package:recording_tool/core/network/api_client.dart';
import 'package:recording_tool/core/network/http_method.dart';
import 'package:recording_tool/core/network/providers/dio_providers.dart';
import 'package:recording_tool/features/events/model/model_event_info.dart';
import 'package:recording_tool/features/events/request_model/request_model_event.dart';
final eventsServerProvider = Provider<EventsServer>((ref) {
return EventsServer(ref.watch(apiClientProvider));
});
class EventsServer {
const EventsServer(this._apiClient);
final ApiClient _apiClient;
Future<EventRegistrationList> fetchPlayerRegistrationList(
PlayerRegistrationListReq req,
) {
return _apiClient.request<EventRegistrationList>(
AuthApi.playerRegistrationList.path,
method: HttpMethod.get,
data: FormData.fromMap(req.toFormDataMap()),
parser: EventRegistrationList.fromJson,
);
}
Future<StreamKeyResponse> fetchStreamKey(StreamKeyReq req) {
return _apiClient.request<StreamKeyResponse>(
AuthApi.getStreamKey.path,
method: HttpMethod.get,
data: FormData.fromMap(req.toFormDataMap()),
parser: StreamKeyResponse.fromJson,
);
}
/// 人工设置晋级/淘汰
Future<void> setTeamStatus({required SetTeamStatusReq req}) {
print('req: ${req.toJson()}');
return _apiClient.post(
AuthApi.setTeamStatus.path,
data: req.toJson(),
parser: (json) => json,
);
}
}
@@ -0,0 +1,33 @@
import 'package:recording_tool/features/events/model/model_event_info.dart';
class EventInfoState {
const EventInfoState({
this.isRequestingStreamKey = false,
this.profile = const EventProfile(name: '', phone: '', eventTitle: '赛事信息'),
this.total = 0,
this.items = const [],
});
final bool isRequestingStreamKey;
final EventProfile profile;
final int total;
final List<EventRegistrationItem> items;
String get eventTitle =>
items.isEmpty ? profile.eventTitle : items.first.eventName;
EventInfoState copyWith({
bool? isRequestingStreamKey,
EventProfile? profile,
int? total,
List<EventRegistrationItem>? items,
}) {
return EventInfoState(
isRequestingStreamKey:
isRequestingStreamKey ?? this.isRequestingStreamKey,
profile: profile ?? this.profile,
total: total ?? this.total,
items: items ?? this.items,
);
}
}
@@ -0,0 +1,77 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/legacy.dart';
import 'package:recording_tool/core/network/api_exception.dart';
import 'package:recording_tool/features/events/model/model_event_info.dart';
import 'package:recording_tool/features/events/server/server_events.dart';
import 'package:recording_tool/features/events/state/state_event_info.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';
final eventInfoProvider =
StateNotifierProvider<EventInfoViewModel, EventInfoState>((ref) {
return EventInfoViewModel(ref);
});
class EventInfoViewModel extends StateNotifier<EventInfoState> {
EventInfoViewModel(this._ref) : super(const EventInfoState());
static const defaultRegistrationRequest = PlayerRegistrationListReq(
userId: '',
status: '',
);
static const _fallbackEventId = '';
static const _fallbackItemId = '';
static const _fallbackStreamUserId = '';
final Ref _ref;
Future<bool> loadRegistrationList({
PlayerRegistrationListReq request = defaultRegistrationRequest,
}) async {
if (request.userId.isEmpty) {
return false;
}
try {
final result = await _ref
.read(eventsServerProvider)
.fetchPlayerRegistrationList(request);
debugPrint('报名列表请求成功: $result');
state = state.copyWith(
profile: result.toProfile(),
total: result.total,
items: result.items,
);
return true;
} catch (error) {
debugPrint('报名列表请求失败: $error');
AppToast.show('报名列表加载失败');
return false;
}
}
Future<void> requestStreamKey(EventRegistrationItem item) async {
state = state.copyWith(isRequestingStreamKey: true);
final req = StreamKeyReq(
eventId: item.eventId.isNotEmpty ? item.eventId : _fallbackEventId,
itemId: item.itemId.isNotEmpty ? item.itemId : _fallbackItemId,
userId: item.userId.isNotEmpty ? item.userId : _fallbackStreamUserId,
);
try {
final response = await _ref
.read(eventsServerProvider)
.fetchStreamKey(req);
debugPrint('推流 Key 接口响应: $response');
state = state.copyWith(isRequestingStreamKey: false);
} on ApiException catch (error) {
debugPrint('推流 Key 接口请求失败: ${error.message}');
state = state.copyWith(isRequestingStreamKey: false);
AppToast.show(error.message);
} catch (error) {
debugPrint('推流 Key 接口请求失败: $error');
state = state.copyWith(isRequestingStreamKey: false);
AppToast.show('推流 Key 获取失败');
}
}
}
@@ -1,61 +0,0 @@
/// 小程序复制到剪切板的录制信息。
class ClipboardRecordingModel {
final String title;
int? startTimestamp;
int? endTimestamp;
final String address;
/// 录制文件名模板,如「选手名称_选手ID_赛事名称_赛项」。
final String? filename;
ClipboardRecordingModel({
required this.title,
this.startTimestamp,
this.endTimestamp,
required this.address,
this.filename,
});
factory ClipboardRecordingModel.fromJson(Map<String, dynamic> json) {
return ClipboardRecordingModel(
title: _readString(json, 'title'),
startTimestamp: _readOptionalInt(json, 'startTimestamp'),
endTimestamp: _readOptionalInt(json, 'endTimestamp'),
address: _readString(json, 'address'),
filename: _readOptionalString(json, 'filename'),
);
}
Map<String, dynamic> toJson() {
return {
'title': title,
'startTimestamp': startTimestamp,
'endTimestamp': endTimestamp,
'address': address,
if (filename != null) 'filename': filename,
};
}
static String? _readOptionalString(Map<String, dynamic> json, String key) {
final value = json[key];
if (value == null) return null;
if (value is String && value.isNotEmpty) return value;
if (value is! String) {
throw FormatException('Clipboard field "$key" must be a String.');
}
return null;
}
static String _readString(Map<String, dynamic> json, String key) {
final value = json[key];
if (value is String) return value;
throw FormatException('Clipboard field "$key" must be a String.');
}
static int? _readOptionalInt(Map<String, dynamic> json, String key) {
final value = json[key];
if (value == null) return null;
if (value is int) return value;
throw FormatException('Clipboard field "$key" must be an int.');
}
}
@@ -1,51 +1,26 @@
import 'package:recording_tool/features/recording/model/model_clipboard.dart';
import 'package:recording_tool/features/recording/model/model_recording_context.dart';
import 'package:recording_tool/features/recording/model/model_recording_session.dart';
class RecordingModel {
/// 剪切板内容
final ClipboardRecordingModel clipboardRecordingModel;
/// 剪切板是否包含有效的小程序录制信息
final bool hasValidClipboardInfo;
/// 从赛事项进入录制页时传入的录制上下文。
final RecordingContext recordingContext;
/// 录制会话状态
final RecordingSessionState session;
RecordingModel({
required this.clipboardRecordingModel,
this.hasValidClipboardInfo = false,
required this.recordingContext,
this.session = const RecordingSessionState(),
});
bool get isRecording => session.isRecording;
factory RecordingModel.fromJson(Map<String, dynamic> json) {
return RecordingModel(
clipboardRecordingModel: ClipboardRecordingModel.fromJson(
json['clipboardRecordingModel'],
),
);
}
Map<String, dynamic> toJson() {
return {'clipboardRecordingModel': clipboardRecordingModel.toJson()};
}
/// 剪切板是否包含可用于命名的 [ClipboardRecordingModel.filename]。
bool get hasClipboardFilename {
final name = clipboardRecordingModel.filename?.trim();
return hasValidClipboardInfo && name != null && name.isNotEmpty;
}
RecordingModel copyWith({
ClipboardRecordingModel? clipboardRecordingModel,
bool? hasValidClipboardInfo,
RecordingContext? recordingContext,
RecordingSessionState? session,
}) {
return RecordingModel(
clipboardRecordingModel:
clipboardRecordingModel ?? this.clipboardRecordingModel,
hasValidClipboardInfo:
hasValidClipboardInfo ?? this.hasValidClipboardInfo,
recordingContext: recordingContext ?? this.recordingContext,
session: session ?? this.session,
);
}
@@ -0,0 +1,55 @@
class RecordingContext {
const RecordingContext({
required this.eventTitle,
required this.matchName,
required this.group,
required this.venue,
required this.time,
required this.playerName,
required this.playerPhone,
this.laneNo,
this.status,
});
const RecordingContext.empty()
: eventTitle = '',
matchName = '',
group = '',
venue = '',
time = '',
playerName = '',
playerPhone = '',
laneNo = null,
status = null;
final String eventTitle;
final String matchName;
final String group;
final String venue;
final String time;
final String playerName;
final String playerPhone;
final String? laneNo;
final String? status;
String get title => '$matchName $group';
String get address => venue;
String get displayName {
final parts = [
playerName,
matchName,
group,
if (laneNo != null && laneNo!.trim().isNotEmpty) laneNo!,
];
return parts.map(_sanitize).where((part) => part.isNotEmpty).join('_');
}
static String _sanitize(String value) {
return value
.trim()
.replaceAll(RegExp(r'[\\/:*?"<>|]'), '_')
.replaceAll(RegExp(r'\s+'), '_');
}
}

Some files were not shown because too many files have changed in this diff Show More