예제 #1
0
        internal void NewIncomingCall(string context, string contactName, string serviceName)
        {
            try
            {
                VoipCallCoordinator vCC  = VoipCallCoordinator.GetDefault();
                VoipPhoneCall       call = vCC.RequestNewIncomingCall(
                    "Hello",
                    contactName,
                    context,
                    new Uri("file://c:/data/test/bin/FakeVoipAppLight.png"),
                    serviceName,
                    new Uri("file://c:/data/test/bin/FakeVoipAppLight.png"),
                    "",
                    new Uri("file://c:/data/test/bin/FakeVoipAppRingtone.wma"),
                    VoipPhoneCallMedia.Audio,
                    new TimeSpan(0, 1, 20));
                if (call != null)
                {
                    call.AnswerRequested += Call_AnswerRequested;
                    call.EndRequested    += Call_EndRequested;
                    call.RejectRequested += Call_RejectRequested;

                    Current.VoipCall = call;
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }
예제 #2
0
        private async void StartVideoStream(String camera, String codec, String videoSize, UInt32 frameRate, UInt32 bitRate, Boolean usePreviewStream)
        {
            try
            {
                _videoSource = new MSWinRTVideo.SwapChainPanelSource();
                _videoSource.Start(VideoSwapChainPanel);
                _previewSource = new MSWinRTVideo.SwapChainPanelSource();
                _previewSource.Start(PreviewSwapChainPanel);
                var vcc        = VoipCallCoordinator.GetDefault();
                var entryPoint = typeof(PhoneCallTask).FullName;
                var status     = await vcc.ReserveCallResourcesAsync(entryPoint);

                var capabilities = VoipPhoneCallMedia.Audio | VoipPhoneCallMedia.Video;
                call = vcc.RequestNewOutgoingCall("FooContext", "FooContact", "MS2Tester", capabilities);
                call.NotifyCallActive();
                OperationResult result = await MS2TesterHelper.StartVideoStream(VideoSwapChainPanel.Name, PreviewSwapChainPanel.Name, camera, codec, videoSize, frameRate, bitRate, usePreviewStream);

                if (result == OperationResult.Succeeded)
                {
                    Debug.WriteLine("StartVideoStream: success");
                }
                else
                {
                    Debug.WriteLine("StartVideoStream: failure");
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(String.Format("StartVideoStream: Exception {0}", e.Message));
            }
        }
예제 #3
0
        private void NewOutgoingCall(string context, string contactName, string serviceName)
        {
            bool status = false;

            try
            {
                VoipCallCoordinator vCC  = VoipCallCoordinator.GetDefault();
                VoipPhoneCall       call = vCC.RequestNewOutgoingCall(context, contactName, serviceName, VoipPhoneCallMedia.Audio);
                if (call != null)
                {
                    call.EndRequested    += Call_EndRequested;
                    call.HoldRequested   += Call_HoldRequested;
                    call.RejectRequested += Call_RejectRequested;
                    call.ResumeRequested += Call_ResumeRequested;

                    call.NotifyCallActive();

                    Current.VoipCall = call;

                    Current.StartAudio();

                    status = true;
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }

            ValueSet response = new ValueSet();

            response[BackgroundOperation.Result] = status ? (int)OperationResult.Succeeded : (int)OperationResult.Failed;

            Current.SendResponse(response);
        }
예제 #4
0
        public static async void ConnectToVoiceChannel(VoiceServerUpdate data)
        {
            string name;

            if (data.GuildId == null)
            {
                data.GuildId = data.ChannelId;
                name         = $"DM - {LocalState.DMs[data.ChannelId].Name}";
            }
            else
            {
                name = $"{LocalState.Guilds[data.GuildId].Raw.Name} - {LocalState.Guilds[data.GuildId].channels[LocalState.VoiceState.ChannelId].raw.Name}";
            }
            App.UpdateLocalDeaf(false);
            App.UpdateVoiceStateHandler += App_UpdateVoiceStateHandler;
            //App.UpdateLocalMute(true); //LocalState.Muted);
            VoiceConnection = new VoiceConnection(data, LocalState.VoiceState);
            VoiceConnection.VoiceDataRecieved += VoiceConnection_VoiceDataRecieved;
            await VoiceConnection.ConnectAsync();

            ConnectoToVoiceHandler?.Invoke(typeof(App), new ConnectToVoiceArgs()
            {
                ChannelId = LocalState.VoiceState.ChannelId, GuildId = data.GuildId
            });
            AudioManager.InputRecieved += AudioManager_InputRecieved;
            if (Storage.Settings.BackgroundVoice)
            {
                VoipCallCoordinator vcc = VoipCallCoordinator.GetDefault();
                voipCall = vcc.RequestNewOutgoingCall("", name, "Quarrel", VoipPhoneCallMedia.Audio);
                voipCall.NotifyCallActive();
            }
        }
예제 #5
0
        public async Task StartVoipTask()
        {
            // Make sure there isn't already a voip task active and the contract is available.
            if (Hub.Instance.VoipTaskInstance == null &&
                ApiInformation.IsApiContractPresent("Windows.ApplicationModel.Calls.CallsVoipContract", 1))
            {
                var vcc            = VoipCallCoordinator.GetDefault();
                var voipEntryPoint = typeof(VoipTask).FullName;
                try
                {
                    var status = await vcc.ReserveCallResourcesAsync(voipEntryPoint);

                    Debug.WriteLine($"ReserveCallResourcesAsync {voipEntryPoint} result -> {status}");
                }
                catch (Exception ex)
                {
                    const int rtcTaskAlreadyRunningErrorCode = -2147024713;
                    if (ex.HResult == rtcTaskAlreadyRunningErrorCode)
                    {
                        Debug.WriteLine("VoipTask already running");
                    }
                    else
                    {
                        Debug.WriteLine($"ReserveCallResourcesAsync error -> {ex.HResult} : {ex.Message}");
                        throw;
                    }
                }
            }
        }
예제 #6
0
        private async void CallExecute()
        {
            if (_item == null || _full == null)
            {
                return;
            }

            if (_full.IsPhoneCallsAvailable && !_item.IsSelf && ApiInformation.IsApiContractPresent("Windows.ApplicationModel.Calls.CallsVoipContract", 1))
            {
                try
                {
                    var coordinator = VoipCallCoordinator.GetDefault();
                    var result      = await coordinator.ReserveCallResourcesAsync("Unigram.Tasks.VoIPCallTask");

                    if (result == VoipPhoneCallResourceReservationStatus.Success)
                    {
                        await VoIPConnection.Current.SendRequestAsync("voip.startCall", _item);
                    }
                }
                catch
                {
                    await TLMessageDialog.ShowAsync("Something went wrong. Please, try to close and relaunch the app.", "Unigram", "OK");
                }
            }
        }
        public void StartIncomingCall(RelayMessage message)
        {
            var foregroundIsVisible = false;
            var state = Hub.Instance.ForegroundClient.GetForegroundState();

            if (state != null)
            {
                foregroundIsVisible = state.IsForegroundVisible;
            }

            if (!foregroundIsVisible)
            {
                var voipCallCoordinatorCc = VoipCallCoordinator.GetDefault();

                VoipCall = voipCallCoordinatorCc.RequestNewIncomingCall(message.FromUserId, message.FromName, message.FromName,
                                                                        AvatarLink.CallCoordinatorUriFor(message.FromAvatar),
                                                                        "ChatterBox Universal",
                                                                        null,
                                                                        "",
                                                                        null,
                                                                        VoipPhoneCallMedia.Audio,
                                                                        new TimeSpan(0, 1, 20));

                SubscribeToVoipCallEvents();
            }
        }
예제 #8
0
        internal void NewOutgoingCall(string dstURI)
        {
            bool status = false;

            try
            {
                VoipCallCoordinator vCC  = VoipCallCoordinator.GetDefault();
                VoipPhoneCall       call = vCC.RequestNewOutgoingCall("Pjsua Test Call ", dstURI, "", VoipPhoneCallMedia.Audio);
                if (call != null)
                {
                    call.EndRequested    += Call_EndRequested;
                    call.RejectRequested += Call_RejectRequested;

                    call.NotifyCallActive();

                    Current.VoipCall = call;

                    MyAppRT.Instance.makeCall(dstURI);

                    status = true;
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }

            ValueSet response = new ValueSet();

            response[BackgroundOperation.Result] = status ? (int)OperationResult.Succeeded : (int)OperationResult.Failed;

            Current.SendResponse(response);
        }
예제 #9
0
        private async Task <VoipPhoneCallResourceReservationStatus> LaunchRTCTaskAsync()
        {
            // End current call before starting another call, there should be only one RTC task active at a time.
            // Duplicate calls to launch RTC task will result in HR ERROR_ALREADY_EXSIST
            // <TODO> For multiple calls against single rtc task add logic to verify that the rtc is not completed,
            // and then Skip launching new rtc task
            Current.EndCall();

            VoipCallCoordinator vCC = VoipCallCoordinator.GetDefault();
            VoipPhoneCallResourceReservationStatus status = VoipPhoneCallResourceReservationStatus.ResourcesNotAvailable;

            try
            {
                status = await vCC.ReserveCallResourcesAsync(Current.RtcCallTaskName);
            }
            catch (Exception ex)
            {
                if (ex.HResult == RTcTaskAlreadyRuningErrorCode)
                {
                    Debug.WriteLine("RTC Task Already running");
                }
            }

            return(status);
        }
예제 #10
0
        internal async void OutgoingCall(int userId, long accessHash)
        {
            await UpdateStateAsync(TLPhoneCallState.Requesting);

            var coordinator = VoipCallCoordinator.GetDefault();
            var call        = coordinator.RequestNewOutgoingCall("Unigram", _user.FullName, "Unigram", VoipPhoneCallMedia.Audio);

            _outgoing   = true;
            _systemCall = call;
            _systemCall.AnswerRequested += OnAnswerRequested;
            _systemCall.RejectRequested += OnRejectRequested;

            //var reqConfig = new TLMessagesGetDHConfig { Version = 0, RandomLength = 256 };

            //var config = await SendRequestAsync<TLMessagesDHConfig>("messages.getDhConfig", reqConfig);
            //if (config.IsSucceeded)
            //{
            //    var dh = config.Result;
            //    if (!TLUtils.CheckPrime(dh.P, dh.G))
            //    {
            //        return;
            //    }

            //    var salt = new byte[256];
            //    var secureRandom = new SecureRandom();
            //    secureRandom.NextBytes(salt);

            //    secretP = dh.P;
            //    a_or_b = salt;
            //    g_a = MTProtoService.GetGB(salt, dh.G, dh.P);

            //    var request = new TLPhoneRequestCall
            //    {
            //        UserId = new TLInputUser { UserId = userId, AccessHash = accessHash },
            //        RandomId = TLInt.Random(),
            //        GAHash = Utils.ComputeSHA256(g_a),
            //        Protocol = new TLPhoneCallProtocol
            //        {
            //            IsUdpP2p = true,
            //            IsUdpReflector = true,
            //            MinLayer = Telegram.Api.Constants.CallsMinLayer,
            //            MaxLayer = Telegram.Api.Constants.CallsMaxLayer,
            //        }
            //    };

            //    var response = await SendRequestAsync<TLPhonePhoneCall>("phone.requestCall", request);
            //    if (response.IsSucceeded)
            //    {
            //        var update = new TLUpdatePhoneCall { PhoneCall = response.Result.PhoneCall };

            //        Handle(update);
            //        await UpdateStateAsync(TLPhoneCallState.Waiting);
            //    }
            //    else
            //    {
            //        Debugger.Break();
            //    }
            //}
        }
예제 #11
0
파일: TLPushUtils.cs 프로젝트: Fart03/lau
        public static async void UpdateToastAndTiles(RawNotification rawNotification)
        {
            var payload = (rawNotification != null) ? rawNotification.Content : null;

            if (payload == null)
            {
                return;
            }

            var notification = GetRootObject(payload);

            if (notification == null)
            {
                return;
            }

            if (notification.data == null)
            {
                return;
            }

            if (notification.data.loc_key == null)
            {
                RemoveToastGroup(GetGroup(notification.data));
                return;
            }

            var caption = GetCaption(notification.data);
            var message = GetMessage(notification.data);
            var sound   = GetSound(notification.data);
            var launch  = GetLaunch(notification.data);
            var tag     = GetTag(notification.data);
            var group   = GetGroup(notification.data);

            if (notification.data.loc_key.Equals("PHONE_CALL_REQUEST"))
            {
                AddToast("PHONE_CALL_REQUEST", "PHONE_CALL_REQUEST", null, "launch", null, null, "voip");
                await VoipCallCoordinator.GetDefault().ReserveCallResourcesAsync("Unigram.Tasks.VoIPCallTask");

                return;
            }

            if (!IsMuted(notification.data))
            {
                AddToast(caption, message, sound, launch, notification.data.custom, tag, group);
            }
            if (!IsMuted(notification.data) && !IsServiceNotification(notification.data))
            {
                UpdateTile(caption, message);
            }
            if (!IsMuted(notification.data))
            {
                UpdateBadge(notification.data.badge);
            }
        }
예제 #12
0
        private async void ConnectToVoiceChannel(VoiceServerUpdate data, VoiceState state)
        {
            voipCall?.NotifyCallEnded();
            VoipCallCoordinator vcc = VoipCallCoordinator.GetDefault();
            var status = await vcc.ReserveCallResourcesAsync("WebRTCBackgroundTask.VoipBackgroundTask");

            // TODO: More info for Mobile
            voipCall = vcc.RequestNewOutgoingCall(string.Empty, string.Empty, "Quarrel", VoipPhoneCallMedia.Audio);
            voipCall.NotifyCallActive();

            voiceConnection        = new VoiceConnection(data, state, webrtcManager);
            voiceConnection.Speak += Speak;
            await voiceConnection.ConnectAsync();
        }
        public void StartOutgoingCall(OutgoingCallRequest request)
        {
            var capabilities = VoipPhoneCallMedia.Audio;

            if (request.VideoEnabled)
            {
                capabilities |= VoipPhoneCallMedia.Video;
            }
            var vCC = VoipCallCoordinator.GetDefault();

            VoipCall = vCC.RequestNewOutgoingCall(request.PeerUserId, request.PeerUserId, "ChatterBox Universal",
                                                  capabilities);
            if (VoipCall != null)
            {
                SubscribeToVoipCallEvents();

                VoipCall.NotifyCallActive();
            }
        }
예제 #14
0
        private void NewIncomingCall(string context, string contactName, string serviceName)
        {
            bool status = false;

            try
            {
                VoipCallCoordinator vCC  = VoipCallCoordinator.GetDefault();
                VoipPhoneCall       call = vCC.RequestNewIncomingCall(
                    "Hello",
                    contactName,
                    context,
                    new Uri("file://c:/data/test/bin/FakeVoipAppLight.png"),
                    serviceName,
                    new Uri("file://c:/data/test/bin/FakeVoipAppLight.png"),
                    "",
                    new Uri("file://c:/data/test/bin/FakeVoipAppRingtone.wma"),
                    VoipPhoneCallMedia.Audio,
                    new TimeSpan(0, 1, 20));
                if (call != null)
                {
                    call.AnswerRequested += Call_AnswerRequested;
                    call.EndRequested    += Call_EndRequested;
                    call.HoldRequested   += Call_HoldRequested;
                    call.RejectRequested += Call_RejectRequested;
                    call.ResumeRequested += Call_ResumeRequested;

                    Current.VoipCall = call;

                    status = true;
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }

            ValueSet response = new ValueSet();

            response[BackgroundOperation.Result] = status ? (int)OperationResult.Succeeded : (int)OperationResult.Failed;

            Current.SendResponse(response);
        }
예제 #15
0
        public async Task StartIncomingCallAsync(RelayMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            // Check if the foreground UI is visible.
            // If it is then we don't trigger an incoming call because the call
            // can be answered from the UI and VoipCallCoordinator doesn't handle
            // this case.
            // As a workaround, when SetCallActive() is called when answered from the UI
            // we create an instance of an outgoing call.
            var foregroundIsVisible = false;
            var state = await Hub.Instance.ForegroundClient.GetForegroundStateAsync();

            if (state != null)
            {
                foregroundIsVisible = state.IsForegroundVisible;
            }

            if (!foregroundIsVisible)
            {
                var voipCallCoordinator = VoipCallCoordinator.GetDefault();

                _voipCall = voipCallCoordinator.RequestNewIncomingCall(
                    message.FromUserId, message.FromName,
                    message.FromName,
                    AvatarLink.CallCoordinatorUriFor(message.FromAvatar),
                    "ChatterBox",
                    null,
                    "",
                    null,
                    VoipPhoneCallMedia.Audio,
                    new TimeSpan(0, 1, 20));

                SubscribeToVoipCallEvents();
            }
        }
예제 #16
0
        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        protected override void OnInvoke(ScheduledTask task)
        {
            var incomingCallTask = task as VoipHttpIncomingCallTask;

            if (incomingCallTask != null)
            {
                // Parse the the incoming push notification payload
                IncomingCallInfo pushNotification;
                using (var ms = new MemoryStream(incomingCallTask.MessageBody))
                {
                    var xs = new XmlSerializer(typeof(IncomingCallInfo));
                    pushNotification = (IncomingCallInfo)xs.Deserialize(ms);
                }

                String defaultContactImageUri = Package.Current.InstalledLocation.Path + @"\Assets\DefaultContactImage.jpg";
                String logoUrl = Package.Current.InstalledLocation.Path + @"\Assets\ApplicationIcon.png";

                VoipPhoneCall callObj;
                var           callCoordinator = VoipCallCoordinator.GetDefault();
                callCoordinator.RequestNewIncomingCall("/Views/SplashScreenPage.xaml?incomingCall=" + pushNotification.Number,
                                                       pushNotification.Name, pushNotification.Number, new Uri(defaultContactImageUri),
                                                       "VoipTranslator.Client.WinPhone", new Uri(defaultContactImageUri), "VoIP Translator", new Uri(logoUrl), VoipCallMedia.Audio,
                                                       TimeSpan.FromMinutes(5), out callObj);
                callObj.AnswerRequested += callObj_AnswerRequested;
                callObj.RejectRequested += callObj_RejectRequested;
            }
            else
            {
                var keepAliveTask = task as VoipKeepAliveTask;
                if (keepAliveTask != null)
                {
                    this.Complete();
                }
                else
                {
                    throw new InvalidOperationException(string.Format("Unknown scheduled task type {0}", task.GetType()));
                }
            }
        }
예제 #17
0
        public void StartOutgoingCall(string userId, bool videoEnabled)
        {
            var capabilities = VoipPhoneCallMedia.Audio;

            if (videoEnabled)
            {
                capabilities |= VoipPhoneCallMedia.Video;
            }
            var voipCallCoordinator = VoipCallCoordinator.GetDefault();

            _voipCall = voipCallCoordinator.RequestNewOutgoingCall(
                userId, userId,
                "ChatterBox",
                capabilities);

            if (_voipCall == null)
            {
                return;
            }
            SubscribeToVoipCallEvents();
            // Immediately set the call as active.
            _voipCall.NotifyCallActive();
        }
예제 #18
0
        private async void CallExecute()
        {
            var user = _item;

            if (user == null)
            {
                return;
            }

            try
            {
                var coordinator = VoipCallCoordinator.GetDefault();
                var result      = await coordinator.ReserveCallResourcesAsync("Unigram.Tasks.VoIPCallTask");

                if (result == VoipPhoneCallResourceReservationStatus.Success)
                {
                    await VoIPConnection.Current.SendRequestAsync("voip.startCall", user);
                }
            }
            catch
            {
                await TLMessageDialog.ShowAsync("Something went wrong. Please, try to close and relaunch the app.", "Unigram", "OK");
            }
        }
        public async Task StartVoipTask()
        {
            // Leaving the idle state means there's a call that's happening.
            // Trigger the VoipTask to prevent this background task from terminating.
#if true // VoipCallCoordinator support
            if (Hub.Instance.VoipTaskInstance == null &&
                ApiInformation.IsApiContractPresent("Windows.ApplicationModel.Calls.CallsVoipContract", 1))
            {
                var vcc            = VoipCallCoordinator.GetDefault();
                var voipEntryPoint = typeof(VoipTask).FullName;
                Debug.WriteLine($"ReserveCallResourcesAsync {voipEntryPoint}");
                try
                {
                    var status = await vcc.ReserveCallResourcesAsync(voipEntryPoint);

                    Debug.WriteLine($"ReserveCallResourcesAsync result -> {status}");
                }
                catch (Exception ex)
                {
                    const int RTcTaskAlreadyRunningErrorCode = -2147024713;
                    if (ex.HResult == RTcTaskAlreadyRunningErrorCode)
                    {
                        Debug.WriteLine("VoipTask already running");
                    }
                    else
                    {
                        Debug.WriteLine($"ReserveCallResourcesAsync error -> {ex.HResult} : {ex.Message}");
                    }
                }
            }
#else
            var ret = await _hub.WebRtcTaskTrigger.RequestAsync();

            Debug.WriteLine($"VoipTask Trigger -> {ret}");
#endif
        }
예제 #20
0
        private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var deferral = args.GetDeferral();
            var message  = args.Request.Message;

            if (message.ContainsKey("update"))
            {
                var buffer = message["update"] as string;
                var update = TLSerializationService.Current.Deserialize(buffer) as TLUpdatePhoneCall;
                if (update != null)
                {
                    Handle(update);
                }
            }
            else if (message.ContainsKey("caption"))
            {
                var caption = message["caption"] as string;
                if (caption.Equals("phone.discardCall"))
                {
                    if (_phoneCall != null)
                    {
                        var buffer  = message["request"] as string;
                        var payload = TLSerializationService.Current.Deserialize <byte[]>(buffer);
                        var reader  = new TLBinaryReader(payload);
                        var req     = new TLTuple <double>(reader);
                        reader.Dispose();

                        var missed   = _state == TLPhoneCallState.Ringing || (_state == TLPhoneCallState.Waiting && _outgoing);
                        var declined = _state == TLPhoneCallState.WaitingIncoming;
                        TLPhoneCallDiscardReasonBase reason = missed
                            ? new TLPhoneCallDiscardReasonMissed()
                            : declined
                            ? (TLPhoneCallDiscardReasonBase) new TLPhoneCallDiscardReasonBusy()
                            : new TLPhoneCallDiscardReasonHangup();

                        var req2 = new TLPhoneDiscardCall {
                            Peer = _phoneCall.ToInputPhoneCall(), Reason = reason, Duration = (int)req.Item1
                        };

                        const string caption2 = "phone.discardCall";
                        var          response = await SendRequestAsync <TLUpdatesBase>(caption2, req2);

                        if (response.IsSucceeded)
                        {
                            if (response.Result is TLUpdates updates)
                            {
                                var update = updates.Updates.FirstOrDefault(x => x is TLUpdatePhoneCall) as TLUpdatePhoneCall;
                                if (update != null)
                                {
                                    Handle(update);
                                }
                            }
                        }
                    }
                    else if (_systemCall != null)
                    {
                        _systemCall.AnswerRequested -= OnAnswerRequested;
                        _systemCall.RejectRequested -= OnRejectRequested;
                        _systemCall.NotifyCallEnded();
                        _systemCall = null;
                    }
                    else if (_deferral != null)
                    {
                        _deferral.Complete();
                    }
                }
                else if (caption.Equals("phone.mute") || caption.Equals("phone.unmute"))
                {
                    if (_controller != null)
                    {
                        _controller.SetMicMute(caption.Equals("phone.mute"));

                        var coordinator = VoipCallCoordinator.GetDefault();
                        if (caption.Equals("phone.mute"))
                        {
                            coordinator.NotifyMuted();
                        }
                        else
                        {
                            coordinator.NotifyUnmuted();
                        }
                    }
                }
                else if (caption.Equals("voip.startCall"))
                {
                    var buffer = message["request"] as string;
                    var req    = TLSerializationService.Current.Deserialize <TLUser>(buffer);

                    _user = req;
                    OutgoingCall(req.Id, req.AccessHash.Value);
                }
                else if (caption.Equals("voip.debugString"))
                {
                    if (_controller != null)
                    {
                        await args.Request.SendResponseAsync(new ValueSet { { "result", _controller.GetDebugString() }, { "version", VoIPControllerWrapper.GetVersion() } });
                    }
                }
            }
            else if (message.ContainsKey("voip.callInfo"))
            {
                if (_phoneCall != null)
                {
                    await args.Request.SendResponseAsync(new ValueSet { { "result", TLSerializationService.Current.Serialize(_phoneCall) } });
                }
                else
                {
                    await args.Request.SendResponseAsync(new ValueSet { { "error", false } });
                }
            }

            deferral.Complete();
        }
예제 #21
0
        private async void ProcessUpdates()
        {
            while (_queue.Count > 0)
            {
                var update = _queue.Dequeue();

                _phoneCall = update.PhoneCall;

                if (update.PhoneCall is TLPhoneCallRequested requested)
                {
                    _peer = requested.ToInputPhoneCall();

                    var req = new TLPhoneReceivedCall {
                        Peer = new TLInputPhoneCall {
                            Id = requested.Id, AccessHash = requested.AccessHash
                        }
                    };

                    const string caption  = "phone.receivedCall";
                    var          response = await SendRequestAsync <bool>(caption, req);

                    var responseUser = await SendRequestAsync <TLUser>("voip.getUser", new TLPeerUser { UserId = requested.AdminId });

                    if (responseUser.Result == null)
                    {
                        return;
                    }

                    var user  = responseUser.Result;
                    var photo = new Uri("ms-appx:///Assets/Logos/Square150x150Logo/Square150x150Logo.png");
                    if (user.Photo is TLUserProfilePhoto profile && profile.PhotoSmall is TLFileLocation location)
                    {
                        var fileName = string.Format("{0}_{1}_{2}.jpg", location.VolumeId, location.LocalId, location.Secret);
                        var temp     = FileUtils.GetTempFileUri(fileName);

                        photo = temp;
                    }

                    var coordinator = VoipCallCoordinator.GetDefault();
                    var call        = coordinator.RequestNewIncomingCall("Unigram", user.FullName, user.DisplayName, photo, "Unigram", null, "Unigram", null, VoipPhoneCallMedia.Audio, TimeSpan.FromSeconds(128));

                    _user       = user;
                    _outgoing   = false;
                    _systemCall = call;
                    _systemCall.AnswerRequested += OnAnswerRequested;
                    _systemCall.RejectRequested += OnRejectRequested;
                }
                else if (update.PhoneCall is TLPhoneCallDiscarded discarded)
                {
                    if (false)
                    {
                        discarded.IsNeedRating = true;
                    }

                    if (discarded.IsNeedRating)
                    {
                        await _connection.SendMessageAsync(new ValueSet { { "caption", "voip.setCallRating" }, { "request", TLSerializationService.Current.Serialize(_peer) } });
                    }

                    if (discarded.IsNeedDebug)
                    {
                        var req = new TLPhoneSaveCallDebug();
                        req.Debug = new TLDataJSON {
                            Data = _controller.GetDebugLog()
                        };
                        req.Peer = _peer;

                        await SendRequestAsync <bool>("phone.saveCallDebug", req);
                    }

                    await UpdateStateAsync(TLPhoneCallState.Ended);

                    if (_controller != null)
                    {
                        _controller.Dispose();
                        _controller = null;
                    }

                    if (_connection != null)
                    {
                        _connection.RequestReceived -= OnRequestReceived;
                        _connection = null;
                    }

                    if (_systemCall != null)
                    {
                        try
                        {
                            _systemCall.AnswerRequested -= OnAnswerRequested;
                            _systemCall.RejectRequested -= OnRejectRequested;
                            _systemCall.NotifyCallEnded();
                            _systemCall = null;
                        }
                        catch
                        {
                            if (_deferral != null)
                            {
                                _deferral.Complete();
                            }
                        }

                        Debug.WriteLine("VoIP call disposed");
                    }
                    else if (_deferral != null)
                    {
                        _deferral.Complete();
                    }
                }
                else if (update.PhoneCall is TLPhoneCallAccepted accepted)
                {
                    await UpdateStateAsync(TLPhoneCallState.ExchangingKeys);

                    _phoneCall = accepted;

                    auth_key = computeAuthKey(accepted);

                    byte[] authKeyHash = Utils.ComputeSHA1(auth_key);
                    byte[] authKeyId   = new byte[8];
                    Buffer.BlockCopy(authKeyHash, authKeyHash.Length - 8, authKeyId, 0, 8);
                    long fingerprint = Utils.BytesToLong(authKeyId);
                    //this.authKey = authKey;
                    //keyFingerprint = fingerprint;

                    var request = new TLPhoneConfirmCall
                    {
                        GA             = g_a,
                        KeyFingerprint = fingerprint,
                        Peer           = new TLInputPhoneCall
                        {
                            Id         = accepted.Id,
                            AccessHash = accepted.AccessHash
                        },
                        Protocol = new TLPhoneCallProtocol
                        {
                            IsUdpP2p       = true,
                            IsUdpReflector = true,
                            MinLayer       = Telegram.Api.Constants.CallsMinLayer,
                            MaxLayer       = Telegram.Api.Constants.CallsMaxLayer,
                        }
                    };

                    var response = await SendRequestAsync <TLPhonePhoneCall>("phone.confirmCall", request);

                    if (response.IsSucceeded)
                    {
                        _systemCall.NotifyCallActive();
                        Handle(new TLUpdatePhoneCall {
                            PhoneCall = response.Result.PhoneCall
                        });
                    }
                }
                else if (update.PhoneCall is TLPhoneCall call)
                {
                    _phoneCall = call;

                    if (auth_key == null)
                    {
                        auth_key = computeAuthKey(call);
                        g_a      = call.GAOrB;
                    }

                    var buffer = TLUtils.Combine(auth_key, g_a);
                    var sha256 = Utils.ComputeSHA256(buffer);

                    _emojis = EncryptionKeyEmojifier.EmojifyForCall(sha256);

                    var response = await SendRequestAsync <TLDataJSON>("phone.getCallConfig", new TLPhoneGetCallConfig());

                    if (response.IsSucceeded)
                    {
                        var responseConfig = await SendRequestAsync <TLConfig>("voip.getConfig", new TLPeerUser());

                        var config = responseConfig.Result;

                        VoIPControllerWrapper.UpdateServerConfig(response.Result.Data);

                        var logFile       = ApplicationData.Current.LocalFolder.Path + "\\tgvoip.logFile.txt";
                        var statsDumpFile = ApplicationData.Current.LocalFolder.Path + "\\tgvoip.statsDump.txt";

                        if (_controller != null)
                        {
                            _controller.Dispose();
                            _controller = null;
                        }

                        _controller = new VoIPControllerWrapper();
                        _controller.SetConfig(config.CallPacketTimeoutMs / 1000.0, config.CallConnectTimeoutMs / 1000.0, DataSavingMode.Never, true, true, true, logFile, statsDumpFile);

                        SettingsHelper.CleanUp();
                        if (SettingsHelper.IsCallsProxyEnabled)
                        {
                            var server = SettingsHelper.ProxyServer ?? string.Empty;
                            var port   = SettingsHelper.ProxyPort;
                            var user   = SettingsHelper.ProxyUsername ?? string.Empty;
                            var pass   = SettingsHelper.ProxyPassword ?? string.Empty;

                            _controller.SetProxy(ProxyProtocol.SOCKS5, server, (ushort)port, user, pass);
                        }
                        else
                        {
                            _controller.SetProxy(ProxyProtocol.None, string.Empty, 0, string.Empty, string.Empty);
                        }

                        _controller.SetStateCallback(this);
                        _controller.SetEncryptionKey(auth_key, _outgoing);

                        var connection = call.Connection;
                        var endpoints  = new Endpoint[call.AlternativeConnections.Count + 1];
                        endpoints[0] = connection.ToEndpoint();

                        for (int i = 0; i < call.AlternativeConnections.Count; i++)
                        {
                            connection       = call.AlternativeConnections[i];
                            endpoints[i + 1] = connection.ToEndpoint();
                        }

                        _controller.SetPublicEndpoints(endpoints, call.Protocol.IsUdpP2p && ApplicationSettings.Current.IsPeerToPeer);
                        _controller.Start();
                        _controller.Connect();
                    }

                    //await Task.Delay(50000);

                    //var req = new TLPhoneDiscardCall { Peer = new TLInputPhoneCall { Id = call.Id, AccessHash = call.AccessHash }, Reason = new TLPhoneCallDiscardReasonHangup() };

                    //const string caption = "phone.discardCall";
                    //await SendRequestAsync<TLUpdatesBase>(caption, req);

                    //_systemCall.NotifyCallEnded();
                }
                else if (update.PhoneCall is TLPhoneCallWaiting waiting)
                {
                    _peer = waiting.ToInputPhoneCall();

                    if (_state == TLPhoneCallState.Waiting && waiting.HasReceiveDate && waiting.ReceiveDate != 0)
                    {
                        await UpdateStateAsync(TLPhoneCallState.Ringing);
                    }
                }
            }
        }
예제 #22
0
 private async void Init()
 {
     var vcc        = VoipCallCoordinator.GetDefault();
     var entryPoint = typeof(PhoneCallTask).FullName;
     var status     = await vcc.ReserveCallResourcesAsync(entryPoint);
 }
예제 #23
0
 private void MuteRequested(VoipCallCoordinator sender, MuteChangeEventArgs args)
 {
     Debug.WriteLine("[LinphoneManager] Mute requested");
     MuteMic(false);
 }
예제 #24
0
        private async Task ConnectAsync(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args, AppServiceDeferral deferral)
        {
            try
            {
                var token     = args.Request.Message["token"] as string;
                var server    = ulong.Parse(args.Request.Message["server"] as string);
                var channelId = ulong.Parse(args.Request.Message["channel"] as string);

                async Task OnReady(ReadyEventArgs e)
                {
                    try
                    {
                        var channel = await _discord.GetChannelAsync(channelId);

                        var coordinator = VoipCallCoordinator.GetDefault();
                        await coordinator.ReserveCallResourcesAsync("Unicord.Universal.Voice.VoiceBackgroundTask");

                        var call = coordinator.RequestNewOutgoingCall(channelId.ToString(), channel.Name, "Unicord", VoipPhoneCallMedia.Audio);

                        var set = new ValueSet {
                            ["connected"] = true
                        };
                        await args.Request.SendResponseAsync(set);

                        deferral.Complete();

                        await Task.Delay(10000);

                        call.NotifyCallEnded();
                    }
                    catch (Exception ex)
                    {
                        var set = new ValueSet {
                            ["connected"] = false, ["error"] = ex.Message
                        };
                        await args.Request.SendResponseAsync(set);

                        deferral.Complete();
                    }
                }

                _discord = new DiscordClient(new DiscordConfiguration()
                {
                    Token                  = token,
                    TokenType              = TokenType.User,
                    ReconnectIndefinitely  = false,
                    AutomaticGuildSync     = false,
                    MessageCacheSize       = 0,
                    LightMode              = true,
                    WebSocketClientFactory = WebSocket4NetCoreClient.CreateNew
                });

                _discord.Ready += OnReady;
                _voiceNext      = _discord.UseVoiceNext();

                await _discord.ConnectAsync(status : UserStatus.Offline);
            }
            catch (Exception ex)
            {
                await args.Request.SendResponseAsync(new ValueSet()
                {
                    ["connected"] = false, ["error"] = ex.Message
                });

                deferral.Complete();
            }
        }
 public VoipCallCoordinatorEvents(VoipCallCoordinator This)
 {
     this.This = This;
 }
예제 #26
0
 private void MuteRequested(VoipCallCoordinator sender, MuteChangeEventArgs args)
 {
     Debug.WriteLine("[LinphoneManager] Mute requested");
     MuteMic(false);
 }