2024-04-18 14:33:55 +00:00
|
|
|
import 'dart:async';
|
2024-04-30 12:31:54 +00:00
|
|
|
import 'dart:convert';
|
2024-04-18 14:33:55 +00:00
|
|
|
|
2024-04-30 12:31:54 +00:00
|
|
|
import 'package:flutter/material.dart';
|
2024-05-01 16:49:38 +00:00
|
|
|
import 'package:http/http.dart';
|
2024-04-30 12:31:54 +00:00
|
|
|
import 'package:livekit_client/livekit_client.dart';
|
|
|
|
import 'package:permission_handler/permission_handler.dart';
|
|
|
|
import 'package:provider/provider.dart';
|
|
|
|
import 'package:solian/models/call.dart';
|
|
|
|
import 'package:solian/models/channel.dart';
|
2024-04-18 14:33:55 +00:00
|
|
|
import 'package:solian/providers/auth.dart';
|
|
|
|
import 'package:solian/utils/service_url.dart';
|
2024-04-30 12:31:54 +00:00
|
|
|
import 'package:solian/widgets/chat/call/exts.dart';
|
|
|
|
import 'package:solian/widgets/exts.dart';
|
|
|
|
import 'package:wakelock_plus/wakelock_plus.dart';
|
2024-04-18 14:33:55 +00:00
|
|
|
import 'package:web_socket_channel/web_socket_channel.dart';
|
2024-04-30 12:31:54 +00:00
|
|
|
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
|
2024-04-18 14:33:55 +00:00
|
|
|
|
2024-04-30 12:31:54 +00:00
|
|
|
class ChatProvider extends ChangeNotifier {
|
2024-04-18 14:33:55 +00:00
|
|
|
bool isOpened = false;
|
2024-05-01 16:49:38 +00:00
|
|
|
bool isCallShown = false;
|
2024-04-30 12:31:54 +00:00
|
|
|
|
2024-05-01 16:49:38 +00:00
|
|
|
Call? ongoingCall;
|
|
|
|
Channel? focusChannel;
|
|
|
|
ChatCallInstance? currentCall;
|
2024-04-18 14:33:55 +00:00
|
|
|
|
|
|
|
Future<WebSocketChannel?> connect(AuthProvider auth) async {
|
2024-05-01 03:27:48 +00:00
|
|
|
if (auth.client == null) await auth.loadClient();
|
2024-04-18 14:33:55 +00:00
|
|
|
if (!await auth.isAuthorized()) return null;
|
|
|
|
|
|
|
|
await auth.refreshToken();
|
|
|
|
|
2024-04-25 13:33:53 +00:00
|
|
|
var ori = getRequestUri('messaging', '/api/ws');
|
2024-04-18 14:33:55 +00:00
|
|
|
var uri = Uri(
|
|
|
|
scheme: ori.scheme.replaceFirst('http', 'ws'),
|
|
|
|
host: ori.host,
|
|
|
|
path: ori.path,
|
2024-05-01 09:37:34 +00:00
|
|
|
queryParameters: {
|
|
|
|
'tk': Uri.encodeComponent(auth.client!.credentials.accessToken)
|
|
|
|
},
|
2024-04-18 14:33:55 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
final channel = WebSocketChannel.connect(uri);
|
|
|
|
await channel.ready;
|
|
|
|
|
|
|
|
return channel;
|
|
|
|
}
|
2024-04-30 12:31:54 +00:00
|
|
|
|
2024-05-01 16:49:38 +00:00
|
|
|
Future<Channel> fetchChannel(String alias) async {
|
|
|
|
final Client client = Client();
|
|
|
|
|
|
|
|
var uri = getRequestUri('messaging', '/api/channels/$alias');
|
|
|
|
var res = await client.get(uri);
|
|
|
|
if (res.statusCode == 200) {
|
|
|
|
final result = jsonDecode(utf8.decode(res.bodyBytes));
|
|
|
|
focusChannel = Channel.fromJson(result);
|
|
|
|
notifyListeners();
|
|
|
|
return focusChannel!;
|
|
|
|
} else {
|
|
|
|
var message = utf8.decode(res.bodyBytes);
|
|
|
|
throw Exception(message);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<Call?> fetchOngoingCall(String alias) async {
|
|
|
|
final Client client = Client();
|
|
|
|
|
|
|
|
var uri = getRequestUri('messaging', '/api/channels/$alias/calls/ongoing');
|
|
|
|
var res = await client.get(uri);
|
|
|
|
if (res.statusCode == 200) {
|
|
|
|
final result = jsonDecode(utf8.decode(res.bodyBytes));
|
|
|
|
ongoingCall = Call.fromJson(result);
|
|
|
|
notifyListeners();
|
|
|
|
return ongoingCall;
|
|
|
|
} else if (res.statusCode != 404) {
|
|
|
|
var message = utf8.decode(res.bodyBytes);
|
|
|
|
throw Exception(message);
|
|
|
|
} else {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
bool handleCallJoin(Call call, Channel channel,
|
2024-05-01 09:37:34 +00:00
|
|
|
{Function? onUpdate, Function? onDispose}) {
|
2024-05-01 16:49:38 +00:00
|
|
|
if (currentCall != null) return false;
|
2024-04-30 12:31:54 +00:00
|
|
|
|
2024-05-01 16:49:38 +00:00
|
|
|
currentCall = ChatCallInstance(
|
2024-04-30 12:31:54 +00:00
|
|
|
onUpdate: () {
|
|
|
|
notifyListeners();
|
|
|
|
if (onUpdate != null) onUpdate();
|
|
|
|
},
|
|
|
|
onDispose: () {
|
2024-05-01 16:49:38 +00:00
|
|
|
currentCall = null;
|
2024-04-30 12:31:54 +00:00
|
|
|
notifyListeners();
|
|
|
|
if (onDispose != null) onDispose();
|
|
|
|
},
|
|
|
|
channel: channel,
|
|
|
|
info: call,
|
|
|
|
);
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2024-05-01 16:49:38 +00:00
|
|
|
void setOngoingCall(Call? item) {
|
|
|
|
ongoingCall = item;
|
|
|
|
notifyListeners();
|
|
|
|
}
|
|
|
|
|
|
|
|
void setCallShown(bool state) {
|
|
|
|
isCallShown = state;
|
2024-04-30 12:31:54 +00:00
|
|
|
notifyListeners();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class ChatCallInstance {
|
|
|
|
final Function onUpdate;
|
|
|
|
final Function onDispose;
|
|
|
|
|
|
|
|
final Call info;
|
|
|
|
final Channel channel;
|
|
|
|
|
|
|
|
bool isMounted = false;
|
|
|
|
|
|
|
|
String? token;
|
|
|
|
String? endpoint;
|
|
|
|
|
|
|
|
StreamSubscription? subscription;
|
|
|
|
List<MediaDevice> audioInputs = [];
|
|
|
|
List<MediaDevice> videoInputs = [];
|
|
|
|
|
|
|
|
bool enableAudio = true;
|
|
|
|
bool enableVideo = false;
|
|
|
|
LocalAudioTrack? audioTrack;
|
|
|
|
LocalVideoTrack? videoTrack;
|
|
|
|
MediaDevice? videoDevice;
|
|
|
|
MediaDevice? audioDevice;
|
|
|
|
|
|
|
|
final VideoParameters videoParameters = VideoParametersPresets.h720_169;
|
|
|
|
|
|
|
|
late Room room;
|
|
|
|
late EventsListener<RoomEvent> listener;
|
|
|
|
|
|
|
|
List<ParticipantTrack> participantTracks = [];
|
|
|
|
ParticipantTrack? focusTrack;
|
|
|
|
|
|
|
|
ChatCallInstance({
|
|
|
|
required this.onUpdate,
|
|
|
|
required this.onDispose,
|
|
|
|
required this.channel,
|
|
|
|
required this.info,
|
|
|
|
});
|
|
|
|
|
|
|
|
void init() {
|
2024-05-01 09:37:34 +00:00
|
|
|
subscription =
|
|
|
|
Hardware.instance.onDeviceChange.stream.listen(revertDevices);
|
2024-04-30 12:31:54 +00:00
|
|
|
room = Room();
|
|
|
|
listener = room.createListener();
|
|
|
|
Hardware.instance.enumerateDevices().then(revertDevices);
|
|
|
|
WakelockPlus.enable();
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> checkPermissions() async {
|
2024-05-01 16:49:38 +00:00
|
|
|
if (lkPlatformIs(PlatformType.macOS) || lkPlatformIs(PlatformType.linux)) {
|
2024-05-01 09:37:34 +00:00
|
|
|
return;
|
2024-05-01 16:49:38 +00:00
|
|
|
}
|
2024-04-30 12:31:54 +00:00
|
|
|
|
|
|
|
await Permission.camera.request();
|
|
|
|
await Permission.microphone.request();
|
|
|
|
await Permission.bluetooth.request();
|
|
|
|
await Permission.bluetoothConnect.request();
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<(String, String)> exchangeToken(BuildContext context) async {
|
|
|
|
await checkPermissions();
|
|
|
|
|
|
|
|
final auth = context.read<AuthProvider>();
|
|
|
|
if (!await auth.isAuthorized()) {
|
|
|
|
onDispose();
|
2024-05-01 16:49:38 +00:00
|
|
|
throw Exception('unauthorized');
|
2024-04-30 12:31:54 +00:00
|
|
|
}
|
|
|
|
|
2024-05-01 09:37:34 +00:00
|
|
|
var uri = getRequestUri(
|
|
|
|
'messaging', '/api/channels/${channel.alias}/calls/ongoing/token');
|
2024-04-30 12:31:54 +00:00
|
|
|
|
|
|
|
var res = await auth.client!.post(uri);
|
|
|
|
if (res.statusCode == 200) {
|
|
|
|
final result = jsonDecode(utf8.decode(res.bodyBytes));
|
|
|
|
token = result['token'];
|
|
|
|
endpoint = 'wss://${result['endpoint']}';
|
|
|
|
joinRoom(context, endpoint!, token!);
|
|
|
|
return (token!, endpoint!);
|
|
|
|
} else {
|
|
|
|
var message = utf8.decode(res.bodyBytes);
|
|
|
|
context.showErrorDialog(message);
|
|
|
|
throw Exception(message);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void joinRoom(BuildContext context, String url, String token) async {
|
|
|
|
if (isMounted) {
|
|
|
|
return;
|
|
|
|
} else {
|
|
|
|
isMounted = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
ScaffoldMessenger.of(context).clearSnackBars();
|
|
|
|
|
|
|
|
final notify = ScaffoldMessenger.of(context).showSnackBar(
|
|
|
|
SnackBar(
|
|
|
|
content: Text(AppLocalizations.of(context)!.connectingServer),
|
|
|
|
duration: const Duration(minutes: 1),
|
|
|
|
),
|
|
|
|
);
|
|
|
|
|
|
|
|
try {
|
|
|
|
await room.connect(
|
|
|
|
url,
|
|
|
|
token,
|
|
|
|
roomOptions: RoomOptions(
|
|
|
|
dynacast: true,
|
|
|
|
adaptiveStream: true,
|
|
|
|
defaultAudioPublishOptions: const AudioPublishOptions(
|
|
|
|
name: 'call_voice',
|
|
|
|
stream: 'call_stream',
|
|
|
|
),
|
|
|
|
defaultVideoPublishOptions: const VideoPublishOptions(
|
|
|
|
name: 'callvideo',
|
|
|
|
stream: 'call_stream',
|
|
|
|
simulcast: true,
|
|
|
|
backupVideoCodec: BackupVideoCodec(enabled: true),
|
|
|
|
),
|
|
|
|
defaultScreenShareCaptureOptions: const ScreenShareCaptureOptions(
|
|
|
|
useiOSBroadcastExtension: true,
|
|
|
|
params: VideoParameters(
|
|
|
|
dimensions: VideoDimensionsPresets.h1080_169,
|
2024-05-01 09:37:34 +00:00
|
|
|
encoding:
|
|
|
|
VideoEncoding(maxBitrate: 3 * 1000 * 1000, maxFramerate: 30),
|
2024-04-30 12:31:54 +00:00
|
|
|
),
|
|
|
|
),
|
2024-05-01 09:37:34 +00:00
|
|
|
defaultCameraCaptureOptions:
|
|
|
|
CameraCaptureOptions(maxFrameRate: 30, params: videoParameters),
|
2024-04-30 12:31:54 +00:00
|
|
|
),
|
|
|
|
fastConnectOptions: FastConnectOptions(
|
|
|
|
microphone: TrackOption(track: audioTrack),
|
|
|
|
camera: TrackOption(track: videoTrack),
|
|
|
|
),
|
|
|
|
);
|
|
|
|
|
|
|
|
setupRoom(context);
|
|
|
|
} catch (e) {
|
|
|
|
context.showErrorDialog(e);
|
|
|
|
} finally {
|
|
|
|
notify.close();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void autoPublish(BuildContext context) async {
|
|
|
|
try {
|
|
|
|
if (enableVideo) await room.localParticipant?.setCameraEnabled(true);
|
|
|
|
} catch (error) {
|
|
|
|
await context.showErrorDialog(error);
|
|
|
|
}
|
|
|
|
try {
|
|
|
|
if (enableAudio) await room.localParticipant?.setMicrophoneEnabled(true);
|
|
|
|
} catch (error) {
|
|
|
|
await context.showErrorDialog(error);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void setupRoom(BuildContext context) {
|
|
|
|
room.addListener(onRoomDidUpdate);
|
|
|
|
setupRoomListeners(context);
|
|
|
|
sortParticipants();
|
2024-05-01 09:37:34 +00:00
|
|
|
WidgetsBindingCompatible.instance
|
|
|
|
?.addPostFrameCallback((_) => autoPublish(context));
|
2024-04-30 12:31:54 +00:00
|
|
|
|
|
|
|
if (lkPlatformIsMobile()) {
|
|
|
|
Hardware.instance.setSpeakerphoneOn(true);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void setupRoomListeners(BuildContext context) {
|
|
|
|
listener
|
|
|
|
..on<RoomDisconnectedEvent>((event) async {
|
|
|
|
if (event.reason != null) {
|
|
|
|
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
|
|
|
content: Text('Call disconnected... ${event.reason}'),
|
|
|
|
));
|
|
|
|
}
|
|
|
|
onDispose();
|
|
|
|
})
|
|
|
|
..on<ParticipantEvent>((event) => sortParticipants())
|
|
|
|
..on<LocalTrackPublishedEvent>((_) => sortParticipants())
|
|
|
|
..on<LocalTrackUnpublishedEvent>((_) => sortParticipants())
|
|
|
|
..on<TrackSubscribedEvent>((_) => sortParticipants())
|
|
|
|
..on<TrackUnsubscribedEvent>((_) => sortParticipants())
|
|
|
|
..on<ParticipantNameUpdatedEvent>((event) {
|
|
|
|
sortParticipants();
|
|
|
|
})
|
|
|
|
..on<AudioPlaybackStatusChanged>((event) async {
|
|
|
|
if (!room.canPlaybackAudio) {
|
|
|
|
bool? yesno = await context.showPlayAudioManuallyDialog();
|
|
|
|
if (yesno == true) {
|
|
|
|
await room.startAudio();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
void sortParticipants() {
|
|
|
|
Map<String, ParticipantTrack> mediaTracks = {};
|
|
|
|
for (var participant in room.remoteParticipants.values) {
|
|
|
|
mediaTracks[participant.sid] = ParticipantTrack(
|
|
|
|
participant: participant,
|
|
|
|
videoTrack: null,
|
|
|
|
isScreenShare: false,
|
|
|
|
);
|
|
|
|
|
|
|
|
for (var t in participant.videoTrackPublications) {
|
|
|
|
mediaTracks[participant.sid]?.videoTrack = t.track;
|
|
|
|
mediaTracks[participant.sid]?.isScreenShare = t.isScreenShare;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
final mediaTrackList = mediaTracks.values.toList();
|
|
|
|
mediaTrackList.sort((a, b) {
|
|
|
|
// Loudest people first
|
|
|
|
if (a.participant.isSpeaking && b.participant.isSpeaking) {
|
|
|
|
if (a.participant.audioLevel > b.participant.audioLevel) {
|
|
|
|
return -1;
|
|
|
|
} else {
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Last spoke first
|
|
|
|
final aSpokeAt = a.participant.lastSpokeAt?.millisecondsSinceEpoch ?? 0;
|
|
|
|
final bSpokeAt = b.participant.lastSpokeAt?.millisecondsSinceEpoch ?? 0;
|
|
|
|
|
|
|
|
if (aSpokeAt != bSpokeAt) {
|
|
|
|
return aSpokeAt > bSpokeAt ? -1 : 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Has video first
|
|
|
|
if (a.participant.hasVideo != b.participant.hasVideo) {
|
|
|
|
return a.participant.hasVideo ? -1 : 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
// First joined people first
|
2024-05-01 09:37:34 +00:00
|
|
|
return a.participant.joinedAt.millisecondsSinceEpoch -
|
|
|
|
b.participant.joinedAt.millisecondsSinceEpoch;
|
2024-04-30 12:31:54 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
ParticipantTrack localTrack = ParticipantTrack(
|
|
|
|
participant: room.localParticipant!,
|
|
|
|
videoTrack: null,
|
|
|
|
isScreenShare: false,
|
|
|
|
);
|
|
|
|
if (room.localParticipant != null) {
|
2024-05-01 09:37:34 +00:00
|
|
|
final localParticipantTracks =
|
|
|
|
room.localParticipant?.videoTrackPublications;
|
2024-04-30 12:31:54 +00:00
|
|
|
if (localParticipantTracks != null) {
|
|
|
|
for (var t in localParticipantTracks) {
|
|
|
|
localTrack.videoTrack = t.track;
|
|
|
|
localTrack.isScreenShare = t.isScreenShare;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
participantTracks = [localTrack, ...mediaTrackList];
|
|
|
|
if (focusTrack == null) {
|
|
|
|
focusTrack = participantTracks.first;
|
|
|
|
} else {
|
2024-05-01 09:37:34 +00:00
|
|
|
final idx = participantTracks
|
|
|
|
.indexWhere((x) => focusTrack!.participant.sid == x.participant.sid);
|
2024-04-30 12:31:54 +00:00
|
|
|
focusTrack = participantTracks[idx];
|
|
|
|
}
|
|
|
|
|
|
|
|
onUpdate();
|
|
|
|
}
|
|
|
|
|
|
|
|
void revertDevices(List<MediaDevice> devices) async {
|
|
|
|
audioInputs = devices.where((d) => d.kind == 'audioinput').toList();
|
|
|
|
videoInputs = devices.where((d) => d.kind == 'videoinput').toList();
|
|
|
|
|
|
|
|
if (audioInputs.isNotEmpty) {
|
|
|
|
if (audioDevice == null && enableAudio) {
|
|
|
|
audioDevice = audioInputs.first;
|
|
|
|
Future.delayed(const Duration(milliseconds: 100), () async {
|
|
|
|
await changeLocalAudioTrack();
|
|
|
|
onUpdate();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (videoInputs.isNotEmpty) {
|
|
|
|
if (videoDevice == null && enableVideo) {
|
|
|
|
videoDevice = videoInputs.first;
|
|
|
|
Future.delayed(const Duration(milliseconds: 100), () async {
|
|
|
|
await changeLocalVideoTrack();
|
|
|
|
onUpdate();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
onUpdate();
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> setEnableVideo(value) async {
|
|
|
|
enableVideo = value;
|
|
|
|
if (!enableVideo) {
|
|
|
|
await videoTrack?.stop();
|
|
|
|
videoTrack = null;
|
|
|
|
} else {
|
|
|
|
await changeLocalVideoTrack();
|
|
|
|
}
|
|
|
|
onUpdate();
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> setEnableAudio(value) async {
|
|
|
|
enableAudio = value;
|
|
|
|
if (!enableAudio) {
|
|
|
|
await audioTrack?.stop();
|
|
|
|
audioTrack = null;
|
|
|
|
} else {
|
|
|
|
await changeLocalAudioTrack();
|
|
|
|
}
|
|
|
|
|
|
|
|
onUpdate();
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> changeLocalAudioTrack() async {
|
|
|
|
if (audioTrack != null) {
|
|
|
|
await audioTrack!.stop();
|
|
|
|
audioTrack = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (audioDevice != null) {
|
|
|
|
audioTrack = await LocalAudioTrack.create(AudioCaptureOptions(
|
|
|
|
deviceId: audioDevice!.deviceId,
|
|
|
|
));
|
|
|
|
await audioTrack!.start();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> changeLocalVideoTrack() async {
|
|
|
|
if (videoTrack != null) {
|
|
|
|
await videoTrack!.stop();
|
|
|
|
videoTrack = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (videoDevice != null) {
|
|
|
|
videoTrack = await LocalVideoTrack.createCameraTrack(CameraCaptureOptions(
|
|
|
|
deviceId: videoDevice!.deviceId,
|
|
|
|
params: videoParameters,
|
|
|
|
));
|
|
|
|
await videoTrack!.start();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void changeFocusTrack(ParticipantTrack track) {
|
|
|
|
focusTrack = track;
|
|
|
|
onUpdate();
|
|
|
|
}
|
|
|
|
|
|
|
|
void onRoomDidUpdate() => sortParticipants();
|
|
|
|
|
|
|
|
void deactivate() {
|
|
|
|
subscription?.cancel();
|
|
|
|
}
|
|
|
|
|
|
|
|
void dispose() {
|
|
|
|
room.removeListener(onRoomDidUpdate);
|
|
|
|
(() async {
|
|
|
|
await listener.dispose();
|
|
|
|
await room.disconnect();
|
|
|
|
await room.dispose();
|
|
|
|
})();
|
|
|
|
WakelockPlus.disable();
|
|
|
|
onDispose();
|
|
|
|
}
|
2024-04-18 14:33:55 +00:00
|
|
|
}
|