preview_media_handler.dart 1.61 KB
import 'package:appframe/config/routes.dart';
import 'package:appframe/data/models/media_item.dart';
import 'package:appframe/services/dispatcher.dart';

/// previewMedia 指令处理类
///
/// 参数格式:
/// {
///   "sources": [
///     {
///       "url": "https://xxx/a.png",   // 必填,支持远程/本地
///       "type": "image",                // 可选,image=图片,video=视频
///       "poster": "https://xxx/p.jpg"  // 可选,视频封面图
///     },
///     ...
///   ],
///   "current": 0  // 可选,当前显示资源序号,默认 0
/// }
class PreviewMediaHandler extends MessageHandler {
  @override
  Future<dynamic> handleMessage(params) async {
    if (params is! Map<String, dynamic>) {
      throw Exception('参数错误');
    }

    final dynamic raw = params['sources'];
    if (raw is! List) {
      throw Exception('参数错误');
    }

    final List<MediaItem> items = <MediaItem>[];
    for (final dynamic e in raw) {
      if (e is! Map) {
        continue;
      }
      final MediaItem item = MediaItem.fromSource(e);
      if (item.url.isEmpty) {
        continue;
      }
      items.add(item);
    }
    if (items.isEmpty) {
      throw Exception('参数错误');
    }

    int current = 0;
    if (params.containsKey('current')) {
      final dynamic c = params['current'];
      if (c is int) {
        current = c;
      } else if (c is num) {
        current = c.toInt();
      }
    }
    if (current < 0 || current >= items.length) {
      current = 0;
    }

    router.push('/previewMedia', extra: {
      'items': items,
      'current': current,
    });

    return true;
  }
}