예제 #1
0
 public GroupCallManager(ushort groupId, RopuProtocol ropuProtocol, ServingNodes servingNodes, KeysClient keysClient)
 {
     _groupId      = groupId;
     _ropuProtocol = ropuProtocol;
     _servingNodes = servingNodes;
     _keysClient   = keysClient;
 }
예제 #2
0
        public async void can_get_developer_key()
        {
            KeysClient   keysClient   = new KeysClient(ACCESS_KEY, SECRET_KEY, TenantName.ONEBLINK_TEST);
            DeveloperKey developerKey = await keysClient.GetDeveloperKey(ACCESS_KEY);

            Assert.NotNull(developerKey);
        }
예제 #3
0
파일: Program.cs 프로젝트: trampster/Ropu
        static async Task Main(string[] args)
        {
            Console.WriteLine("Ropu Load Balancer");
            Console.WriteLine("Copyright (c) Daniel Hughes");
            Console.WriteLine();

            var settingsReader = new CommandLineSettingsReader();
            var settings       = settingsReader.ParseArgs(args);

            if (settings == null)
            {
                return;
            }

            var credentialsProvider = new CredentialsProvider()
            {
                Email    = settings.Email,
                Password = settings.Password
            };
            var webClient    = new RopuWebClient("https://192.168.1.9:5001/", credentialsProvider);
            var groupsClient = new GroupsClient(webClient, new ImageClient(webClient));


            var keysClient           = new KeysClient(webClient, true, encryptionKey => new CachedEncryptionKey(encryptionKey, key => new AesGcmWrapper(key)));
            var packetEncryption     = new PacketEncryption(keysClient);
            var loadBalancerProtocol = new LoadBalancerProtocol(new PortFinder(), 5069, packetEncryption, keysClient);

            var servicesClient = new ServicesClient(webClient, ServiceType.LoadBalancer);

            var controller = new LoadBalancerRunner(keysClient, loadBalancerProtocol, groupsClient, webClient, settings, servicesClient);
            await controller.Run();
        }
예제 #4
0
        public DigitalOceanClient(string token)
        {
            var client = new RestClient(DigitalOceanApiUrl)
            {
                UserAgent = "digitalocean-api-dotnet"
            };

            client.AddDefaultHeader("Authorization", $"Bearer {token}");

            _connection = new Connection(client);

            Actions           = new ActionsClient(_connection);
            DomainRecords     = new DomainRecordsClient(_connection);
            Domains           = new DomainsClient(_connection);
            DropletActions    = new DropletActionsClient(_connection);
            Droplets          = new DropletsClient(_connection);
            FloatingIps       = new FloatingIpsClient(_connection);
            FloatingIpActions = new FloatingIpActionsClient(_connection);
            ImageActions      = new ImageActionsClient(_connection);
            Images            = new ImagesClient(_connection);
            Keys      = new KeysClient(_connection);
            Regions   = new RegionsClient(_connection);
            Sizes     = new SizesClient(_connection);
            Snapshots = new SnapshotsClient(_connection);
            Tags      = new TagsClient(_connection);
            Volumes   = new VolumesClient(_connection);
        }
예제 #5
0
        public void CorrectRequestForGetAll()
        {
            var factory = Substitute.For <IConnection>();
            var client  = new KeysClient(factory);

            client.GetAll();

            factory.Received().GetPaginated <Key>("account/keys", null, "ssh_keys");
        }
예제 #6
0
        public async void get_developer_key_should_throw_oneblink_exception()
        {
            OneBlinkAPIException oneBlinkAPIException = await Assert.ThrowsAsync <OneBlinkAPIException>(() =>
            {
                KeysClient keysClient = new KeysClient("123", "aaaaaaaaaaaaaaabbbbbbbbbbbbbbbcccccccccccccccc", TenantName.ONEBLINK_TEST);
                return(keysClient.GetDeveloperKey(ACCESS_KEY));
            });

            Assert.Equal(HttpStatusCode.Unauthorized, oneBlinkAPIException.StatusCode);
        }
예제 #7
0
        public void Run(string[] args)
        {
            var settingsReader = new CommandLineClientSettingsReader();

            if (!settingsReader.ParseArgs(args))
            {
                return;
            }

            var settings = settingsReader.ClientSettings;

            if (settings.Email == null)
            {
                Console.Error.WriteLine("No Email configured");
                return;
            }

            if (settings.Password == null)
            {
                Console.Error.WriteLine("No Password configured");
                return;
            }

            var credentials = new CredentialsProvider()
            {
                Email    = settings.Email,
                Password = settings.Password
            };

            var webClient = new RopuWebClient("asdf", credentials);


            var keysClient       = new KeysClient(webClient, false, encryptionKey => new CachedEncryptionKey(encryptionKey, key => new AesGcmWrapper(key)));
            var packetEncryption = new PacketEncryption(keysClient);

            var protocolSwitch    = new ProtocolSwitch(_controlPortStarting, new PortFinder(), packetEncryption, keysClient, settings);
            var servingNodeClient = new ServingNodeClient(protocolSwitch);

            var callManagementProtocol = new LoadBalancerProtocol(new PortFinder(), 5079, packetEncryption, keysClient);

            _mediaClient = BuildMediaClient(protocolSwitch, settings);

            //IPEndPoint loadBalancerEndpoint = new IPEndPoint(settings.LoadBalancerIPAddress, LoadBalancerPort);
            var beepPlayer = BuildBeepPlayer(settings);



            _ropuClient = new RopuClient(protocolSwitch, servingNodeClient, _mediaClient, callManagementProtocol, settings, beepPlayer, webClient, keysClient);
            var ropuClientTask = _ropuClient.Run();

            //var consoleTask = TaskCordinator.RunLong(HandleCommands);

            //TaskCordinator.WaitAll(ropuClientTask, consoleTask).Wait();
            ropuClientTask.Wait();
        }
예제 #8
0
        public void CorrectRequestForGetFingerprint()
        {
            var factory = Substitute.For <IConnection>();
            var client  = new KeysClient(factory);

            client.Get("fingerprint");

            var parameters = Arg.Is <List <Parameter> >(list => (string)list[0].Value == "fingerprint");

            factory.Received().ExecuteRequest <Key>("account/keys/{id}", parameters, null, "ssh_key");
        }
예제 #9
0
        public void CorrectRequestForDeleteFingerprint()
        {
            var factory = Substitute.For <IConnection>();
            var client  = new KeysClient(factory);

            client.Delete("fingerprint");

            var parameters = Arg.Is <List <Parameter> >(list => (string)list[0].Value == "fingerprint");

            factory.Received().ExecuteRaw("account/keys/{id}", parameters, null, Method.DELETE);
        }
예제 #10
0
        public void CorrectRequestForGetId()
        {
            var factory = Substitute.For <IConnection>();
            var client  = new KeysClient(factory);

            client.Get(9001);

            var parameters = Arg.Is <List <Parameter> >(list => (int)list[0].Value == 9001);

            factory.Received().ExecuteRequest <Models.Responses.Key>("account/keys/{id}", parameters, null, "ssh_key");
        }
예제 #11
0
 public void throws_error_if_keys_empty()
 {
     try
     {
         KeysClient keysClient = new KeysClient("", "");
         Assert.NotNull(null);
     }
     catch (Exception ex)
     {
         Assert.NotNull(ex);
     }
 }
예제 #12
0
        public RopuProtocol(PortFinder portFinder, int startingPort, PacketEncryption packetEncryption, KeysClient keysClient)
        {
            _socket   = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            MediaPort = (ushort)portFinder.BindToAvailablePort(_socket, IPAddress.Any, startingPort);
            Console.WriteLine($"Serving Node Protocol bound to port {MediaPort}");

            _socketEventArgsPool  = new MemoryPool <SocketAsyncEventArgs>(() => CreateSocketAsyncEventArgs());
            _bulkRequestTokenPool = new MemoryPool <BulkRequestToken>(() => new BulkRequestToken(ReleaseBulkRequestToken));

            _packetEncryption = packetEncryption;
            _keysClient       = keysClient;
        }
예제 #13
0
        public void CorrectRequestForCreate()
        {
            var factory = Substitute.For <IConnection>();
            var client  = new KeysClient(factory);

            var body = new Models.Requests.Key {
                Name = "example"
            };

            client.Create(body);

            factory.Received().ExecuteRequest <Key>("account/keys", null, body, "ssh_key", Method.POST);
        }
예제 #14
0
        public async static Task <EncryptionCredentials> Get()
        {
            var keysService        = new KeysClient(AppToken);
            var privateKeysService = new KeyringClient(AppToken);

            privateKeysService.Connection.SetCredentials(new Credentials(EmailId, ContainerPassword));

            var key = await keysService.PublicKeys.Search(EmailId);

            var privatek = await privateKeysService.PrivateKeys.Get(key.PublicKeyId);

            return(new EncryptionCredentials(key.Key, privatek.Key, Encoding.UTF8.GetBytes(key.PublicKeyId.ToString())));
        }
예제 #15
0
 public LoadBalancerProtocol(
     IPortFinder portFinder,
     ushort startingPort,
     PacketEncryption packetEncryption,
     KeysClient keysClient)
 {
     _sendArgs         = CreateSocketAsyncEventArgs();
     _packetEncryption = packetEncryption;
     _keysClient       = keysClient;
     _socket           = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     _port             = (ushort)portFinder.BindToAvailablePort(_socket, IPAddress.Any, startingPort);
     Console.WriteLine($"Load BalancerProtocol bound to port {_port}");
 }
예제 #16
0
        public async static Task CreateKeyPair()
        {
            var keysService        = new KeysClient(AppToken);
            var privateKeysService = new KeyringClient(AppToken);

            //var key  = await keysService.PublicKeys.Search(EmailId);

            byte[] publicKey;
            byte[] privateKey;

            // Step 1. Generate Public/Private key pair.

            using (var keyPair = new VirgilKeyPair())
            {
                publicKey  = keyPair.PublicKey();
                privateKey = keyPair.PrivateKey();
            }

            Console.WriteLine("Generated Public/Private keys\n");
            Console.WriteLine(Encoding.UTF8.GetString(publicKey));
            Console.WriteLine(Encoding.UTF8.GetString(privateKey));

            // Step 2. Register Public Key on Keys Service.

            var userData = new UserData
            {
                Class = UserDataClass.UserId,
                Type  = UserDataType.EmailId,
                Value = EmailId
            };

            var vPublicKey = await keysService.PublicKeys.Create(publicKey, privateKey, userData);

            // Step 3. Confirm UDID (User data identity) with code recived on email box.

            Console.WriteLine("Enter Confirmation Code:");
            var confirmCode = Console.ReadLine();

            await keysService.UserData.Confirm(vPublicKey.UserData.First().UserDataId, confirmCode, vPublicKey.PublicKeyId, privateKey);

            Console.WriteLine("Public Key has been successfully published." + vPublicKey.PublicKeyId);

            // Step 4. Store Private Key on Private Keys Service.

            await privateKeysService.Container.Initialize(ContainerType.Easy, vPublicKey.PublicKeyId, privateKey, ContainerPassword);

            privateKeysService.Connection.SetCredentials(new Credentials(EmailId, ContainerPassword));
            await privateKeysService.PrivateKeys.Add(vPublicKey.PublicKeyId, privateKey);
        }
예제 #17
0
        public ProtocolSwitch(
            ushort startingPort,
            IPortFinder portFinder,
            PacketEncryption packetEncryption,
            KeysClient keysClient,
            IClientSettings clientSettings)
        {
            _socket           = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _packetEncryption = packetEncryption;
            _keysClient       = keysClient;
            _clientSettings   = clientSettings;
            LocalPort         = (ushort)portFinder.BindToAvailablePort(_socket, IPAddress.Any, startingPort);

            Console.WriteLine($"ProtocolSwitch bound to port {LocalPort}");
        }
예제 #18
0
        public void CorrectRequestForUpdateId()
        {
            var factory = Substitute.For <IConnection>();
            var client  = new KeysClient(factory);

            var body = new Models.Requests.UpdateKey {
                Name = "example"
            };

            client.Update(9001, body);

            var parameters = Arg.Is <List <Parameter> >(list => (int)list[0].Value == 9001);

            factory.Received().ExecuteRequest <Key>("account/keys/{id}", parameters, body, "ssh_key", Method.PUT);
        }
예제 #19
0
        public void CorrectRequestForUpdateFingerprint()
        {
            var factory = Substitute.For <IConnection>();
            var client  = new KeysClient(factory);

            var body = new Key {
                Name = "example"
            };

            client.Update("fingerprint", body);

            var parameters = Arg.Is <List <Parameter> >(list => (string)list[0].Value == "fingerprint");

            factory.Received()
            .ExecuteRequest <Models.Responses.Key>("account/keys/{id}", parameters, body, "ssh_key", Method.PUT);
        }
예제 #20
0
파일: Program.cs 프로젝트: trampster/Ropu
        static async Task Main(string[] args)
        {
            Console.WriteLine("Ropu Serving Node");
            Console.WriteLine("Copyright (c) Daniel Hughes");
            Console.WriteLine();

            var settingsReader = new CommandLineSettingsReader();
            var settings       = settingsReader.ParseArgs(args);

            if (settings == null)
            {
                return;
            }

            var portFinder          = new PortFinder();
            var credentialsProvider = new CredentialsProvider()
            {
                Email    = settings.Email,
                Password = settings.Password
            };
            var webClient        = new RopuWebClient("https://192.168.1.9:5001", credentialsProvider);
            var keysClient       = new KeysClient(webClient, true, encryptionKey => new CachedEncryptionKey(encryptionKey, key => new AesGcmWrapper(key)));
            var packetEncryption = new PacketEncryption(keysClient);

            var mediaProtocol        = new RopuProtocol(portFinder, StartingServingNodePort, packetEncryption, keysClient);
            var loadBalancerProtocol = new LoadBalancerProtocol(portFinder, StartingLoadBalancerPort, packetEncryption, keysClient);
            var serviceDiscovery     = new ServiceDiscovery();

            var groupsClient = new GroupsClient(webClient, new ImageClient(webClient));
            var registra     = new Registra(groupsClient);
            var servingNodes = new ServingNodes(100);
            var groupCallControllerLookup = new GroupCallControllerLookup();

            var servicesClient = new ServicesClient(webClient, ServiceType.ServingNode);

            var servingNodeRunner = new ServingNodeRunner(
                mediaProtocol,
                loadBalancerProtocol,
                serviceDiscovery,
                registra,
                servingNodes,
                groupCallControllerLookup,
                servicesClient,
                keysClient);

            await servingNodeRunner.Run();
        }
예제 #21
0
 public CallControl(
     LoadBalancerProtocol loadBalancerProtocol,
     ServiceDiscovery serviceDiscovery,
     RopuProtocol ropuProtocol,
     ServingNodes servingNodes,
     ServicesClient servicesClient,
     KeysClient keysClient)
 {
     _loadBalancerProtocol = loadBalancerProtocol;
     _loadBalancerProtocol.SetClientMessageHandler(this);
     _serviceDiscovery = serviceDiscovery;
     _ropuProtocol     = ropuProtocol;
     _ropuProtocol.SetMessageHandler(this);
     _servingNodes   = servingNodes;
     _servicesClient = servicesClient;
     _keysClient     = keysClient;
 }
예제 #22
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Starting Ropu Call Controller");
            Console.WriteLine("Copyright (c) Daniel Hughes 2018");
            Console.WriteLine();

            var settingsReader = new CommandLineSettingsReader();
            var settings       = settingsReader.ParseArgs(args);

            if (settings == null)
            {
                return;
            }

            var credentialsProvider = new CredentialsProvider()
            {
                Email    = settings.Email,
                Password = settings.Password
            };
            var webClient = new RopuWebClient("https://192.168.1.9:5001", credentialsProvider);

            var portFinder           = new PortFinder();
            var keysClient           = new KeysClient(webClient, true, encryptionKey => new CachedEncryptionKey(encryptionKey, key => new AesGcmWrapper(key)));
            var packetEncryption     = new PacketEncryption(keysClient);
            var ropuProtocol         = new RopuProtocol(portFinder, 9000, packetEncryption);
            var loadBalancerProtocol = new LoadBalancerProtocol(portFinder, StartingControlPort, packetEncryption, keysClient);
            var serviceDiscovery     = new ServiceDiscovery();
            var servingNodes         = new ServingNodes(100);


            var servicesClient = new ServicesClient(webClient, ServiceType.CallController);

            var callControl = new CallControl(
                loadBalancerProtocol,
                serviceDiscovery,
                ropuProtocol,
                servingNodes,
                servicesClient,
                keysClient);

            await callControl.Run();
        }
예제 #23
0
 public ServingNodeRunner(
     RopuProtocol mediaProtocol,
     LoadBalancerProtocol loadBalancerProtocol,
     ServiceDiscovery serviceDiscovery,
     Registra registra,
     ServingNodes servingNodes,
     GroupCallControllerLookup groupCallControllerLookup,
     ServicesClient servicesClient,
     KeysClient keysClient)
 {
     _ropuProtocol = mediaProtocol;
     _ropuProtocol.SetMessageHandler(this);
     _loadBalancerProtocol      = loadBalancerProtocol;
     _serviceDiscovery          = serviceDiscovery;
     _registra                  = registra;
     _servingNodes              = servingNodes;
     _groupCallControllerLookup = groupCallControllerLookup;
     _servicesClient            = servicesClient;
     _keysClient                = keysClient;
     loadBalancerProtocol.SetClientMessageHandler(this);
 }
예제 #24
0
        public LoadBalancerRunner(
            KeysClient keysClient,
            LoadBalancerProtocol loadBalancerProtocol,
            IGroupsClient groupsClient,
            RopuWebClient webClient,
            CommandLineSettings settings,
            ServicesClient servicesClient)
        {
            _keysClient           = keysClient;
            _settings             = settings;
            _loadBalancerProtocol = loadBalancerProtocol;
            _loadBalancerProtocol.SetServerMessageHandler(this);
            _groupsClient   = groupsClient;
            _webClient      = webClient;
            _servicesClient = servicesClient;

            _servingNodes = new ControllerRegistry <RegisteredServingNode>();

            _callControllers = new CallControllerRegistry(groupsClient);
            _callControllers.SetGroupCallControllerListener(this);
        }
예제 #25
0
        public DigitalOceanClient(string token)
        {
            var client = new RestClient(DigitalOceanApiUrl)
            {
                UserAgent = "digitalocean-api-dotnet"
            };

            client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", token));

            _connection = new Connection(client);

            Account           = new AccountClient(_connection);
            Actions           = new ActionsClient(_connection);
            CdnEndpoints      = new CdnEndpointsClient(_connection);
            Certificates      = new CertificatesClient(_connection);
            ContainerRegistry = new ContainerRegistryClient(_connection);
            Databases         = new DatabasesClient(_connection);
            DomainRecords     = new DomainRecordsClient(_connection);
            Domains           = new DomainsClient(_connection);
            DropletActions    = new DropletActionsClient(_connection);
            Droplets          = new DropletsClient(_connection);
            Firewalls         = new FirewallsClient(_connection);
            FloatingIpActions = new FloatingIpActionsClient(_connection);
            FloatingIps       = new FloatingIpsClient(_connection);
            ImageActions      = new ImageActionsClient(_connection);
            Images            = new ImagesClient(_connection);
            LoadBalancers     = new LoadBalancerClient(_connection);
            Projects          = new ProjectsClient(_connection);
            ProjectResources  = new ProjectResourcesClient(_connection);
            Keys          = new KeysClient(_connection);
            Kubernetes    = new KubernetesClient(_connection);
            Regions       = new RegionsClient(_connection);
            Sizes         = new SizesClient(_connection);
            Snapshots     = new SnapshotsClient(_connection);
            Tags          = new TagsClient(_connection);
            Volumes       = new VolumesClient(_connection);
            VolumeActions = new VolumeActionsClient(_connection);
            BalanceClient = new BalanceClient(_connection);
            Vpc           = new VpcClient(_connection);
        }
예제 #26
0
        public DigitalOceanClient(string token)
        {
            var client = new RestClient(DigitalOceanApiUrl)
            {
                UserAgent = "digitalocean-api-dotnet"
            };

            client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", token));

            _connection = new Connection(client);

            Actions        = new ActionsClient(_connection);
            DomainRecords  = new DomainRecordsClient(_connection);
            Domains        = new DomainsClient(_connection);
            DropletActions = new DropletActionsClient(_connection);
            Droplets       = new DropletsClient(_connection);
            ImageActions   = new ImageActionsClient(_connection);
            Images         = new ImagesClient(_connection);
            Keys           = new KeysClient(_connection);
            Regions        = new RegionsClient(_connection);
            Sizes          = new SizesClient(_connection);
        }
예제 #27
0
        public void can_be_constructed()
        {
            KeysClient keysClient = new KeysClient(ACCESS_KEY, SECRET_KEY);

            Assert.NotNull(keysClient);
        }
예제 #28
0
        public RopuClient(
            ProtocolSwitch protocolSwitch,
            ServingNodeClient servingNodeClient,
            IMediaClient mediaClient,
            LoadBalancerProtocol loadBalancerProtocol,
            IClientSettings clientSettings,
            IBeepPlayer beepPlayer,
            RopuWebClient webClient,
            KeysClient keysClient)
        {
            _webClient            = webClient;
            _beepPlayer           = beepPlayer;
            _clientSettings       = clientSettings;
            _loadBalancerProtocol = loadBalancerProtocol;
            _protocolSwitch       = protocolSwitch;
            _servingNodeClient    = servingNodeClient;
            _mediaClient          = mediaClient;
            _servingNodeClient.SetControllingFunctionHandler(this);
            _retryTimer = new Ropu.Shared.Timer();
            _keysClient = keysClient;

            var allEvents = (EventId[])Enum.GetValues(typeof(EventId));

            //start
            _start        = new RopuState(StateId.Start);
            _stateManager = new StateManager <StateId, EventId>(_start);
            _stateManager.AddState(_start);
            _start.AddTransitions(allEvents, () => _start);

            //registered
            _registered = new RopuState(StateId.Registered)
            {
                Entry = async token =>
                {
                    if (_clientSettings.UserId == null)
                    {
                        throw new InvalidOperationException("UserId is not set");
                    }
                    _callGroup        = IdleGroup;
                    _registeredUserId = _clientSettings.UserId.Value;
                    if (_heartbeatTask == null)
                    {
                        _heartbeatTask = Heartbeat(_heartbeatCancellationTokenSource.Token);
                    }
                    _heartbeatOnEvent.Set(); //allows the heartbeat to continue
                    await Task.Run(() => {});
                },
            };
            _stateManager.AddState(_registered);
            _registered.AddTransition(EventId.CallRequest, () => _startingCall !);
            _registered.AddTransition(EventId.PttDown, () => _startingCall !);
            _registered.AddTransition(EventId.RegistrationResponseReceived, () => _registered);
            _registered.AddTransition(EventId.CallStartFailed, () => _registered);
            _registered.AddTransition(EventId.PttUp, () => _registered);
            _registered.AddTransition(EventId.GroupSelected, () => _registered);

            //unregistered
            _noGroup      = new RopuState(StateId.NoGroup);
            _unregistered = new RopuState(StateId.Unregistered)
            {
                Entry = async token =>
                {
                    _heartbeatOnEvent.Reset(); //stops the heartbeat
                    await Register(token);
                }
            };
            _unregistered.AddTransition(EventId.RegistrationResponseReceived, () => IdleGroup == null ? _noGroup : _registered);
            _unregistered.AddTransition(EventId.FloorIdle, () => _unregistered);
            _unregistered.AddTransition(EventId.FloorTaken, () => _unregistered);
            _unregistered.AddTransition(EventId.CallEnded, () => _unregistered);
            _unregistered.AddTransition(EventId.CallRequest, () => _unregistered);
            _unregistered.AddTransition(EventId.CallStartFailed, () => _unregistered);
            _unregistered.AddTransition(EventId.HeartbeatFailed, () => _unregistered);
            _unregistered.AddTransition(EventId.PttUp, () => _unregistered);
            _unregistered.AddTransition(EventId.PttDown, () => _unregistered);
            _unregistered.AddTransition(EventId.GroupSelected, () => _unregistered);

            _stateManager.AddState(_unregistered);

            //no group
            _noGroup.AddTransition(EventId.PttUp, () => _noGroup);
            _noGroup.AddTransition(EventId.PttDown, () => _noGroup);
            _noGroup.AddTransition(EventId.GroupSelected, () => _registered);
            _noGroup.AddTransition(EventId.RegistrationResponseReceived, () => _noGroup);
            _noGroup.AddTransition(EventId.CallRequest, () => _noGroup);
            _noGroup.AddTransition(EventId.CallStartFailed, () => _noGroup);


            _stateManager.AddState(_noGroup);

            //deregistering
            _deregistering = new RopuState(StateId.Deregistering)
            {
                Entry = async token => await Deregister(token),
            };
            _deregistering.AddTransition(EventId.DeregistrationResponseReceived, () => _unregistered);
            _deregistering.AddTransitions(allEvents.Where(e => e != EventId.DeregistrationResponseReceived), () => _deregistering);
            _deregistering.AddTransition(EventId.GroupSelected, () => _deregistering);
            _stateManager.AddState(_deregistering);

            //starting call
            _startingCall = new RopuState(StateId.StartingCall)
            {
                Entry = async token => await StartCall(token),
                Exit  = newState =>
                {
                    if (newState != _inCallTransmitting && newState != _inCallRequestingFloor)
                    {
                        _mediaClient.StopSendingAudio();
                    }
                }
            };
            _startingCall.AddTransition(EventId.CallStartFailed, () => _registered);
            _startingCall.AddTransition(EventId.PttUp, () => _startingCall);
            _startingCall.AddTransition(EventId.PttDown, () => _startingCall);
            _startingCall.AddTransition(EventId.RegistrationResponseReceived, () => _startingCall);
            _startingCall.AddTransition(EventId.CallRequest, () => _startingCall);
            _startingCall.AddTransition(EventId.GroupSelected, () => _startingCall);

            _stateManager.AddState(_startingCall);

            //in call idle
            _inCallIdle = new RopuState(StateId.InCallIdle);
            _inCallIdle.AddTransition(EventId.PttDown, () => _inCallRequestingFloor !);
            _inCallIdle.AddTransition(EventId.PttUp, () => _inCallIdle);
            _inCallIdle.AddTransition(EventId.RegistrationResponseReceived, () => _inCallIdle);
            _inCallIdle.AddTransition(EventId.CallRequest, () => _inCallIdle);
            _inCallIdle.AddTransition(EventId.CallStartFailed, () => _registered);
            _inCallIdle.AddTransition(EventId.GroupSelected, () => _inCallIdle);
            _stateManager.AddState(_inCallIdle);

            //in call receiving
            _inCallReceiveing = new RopuState(StateId.InCallReceiving);
            _inCallReceiveing.AddTransition(EventId.PttDown, () => _inCallReceiveing);
            _inCallReceiveing.AddTransition(EventId.PttUp, () => _inCallReceiveing);
            _inCallReceiveing.AddTransition(EventId.RegistrationResponseReceived, () => _inCallReceiveing);
            _inCallReceiveing.AddTransition(EventId.CallRequest, () => _inCallReceiveing);
            _inCallReceiveing.AddTransition(EventId.CallStartFailed, () => _registered);
            _inCallReceiveing.AddTransition(EventId.GroupSelected, () => _inCallReceiveing);
            _stateManager.AddState(_inCallReceiveing);

            //in call transmitting
            _inCallTransmitting = new RopuState(StateId.InCallTransmitting)
            {
                Entry = async token =>
                {
                    _beepPlayer.PlayGoAhead();
                    await Task.Run(() => {});
                },
                Exit = newState =>
                {
                    if (newState != _inCallTransmitting && newState != _inCallRequestingFloor)
                    {
                        _mediaClient.StopSendingAudio();
                    }
                }
            };
            _inCallTransmitting.AddTransition(EventId.PttUp, () => _inCallReleasingFloor !);
            _inCallTransmitting.AddTransition(EventId.RegistrationResponseReceived, () => _inCallTransmitting);
            _inCallTransmitting.AddTransition(EventId.CallRequest, () => _inCallTransmitting);
            _inCallTransmitting.AddTransition(EventId.CallStartFailed, () => _inCallTransmitting);
            _inCallTransmitting.AddTransition(EventId.PttDown, () => _inCallTransmitting);
            _inCallTransmitting.AddTransition(EventId.GroupSelected, () => _inCallTransmitting);

            _stateManager.AddState(_inCallTransmitting);

            //in call requesting floor
            _inCallRequestingFloor = new RopuState(StateId.InCallRequestingFloor)
            {
                Entry = token =>
                {
                    if (_callGroup == null)
                    {
                        return(Task.CompletedTask);
                    }
                    if (_clientSettings.UserId == null)
                    {
                        throw new InvalidOperationException("UserId is not set");
                    }
                    _servingNodeClient.SendFloorRequest(_callGroup.Value, _clientSettings.UserId.Value);
                    StartSendingAudio();
                    return(Task.CompletedTask);
                },
                Exit = newState =>
                {
                    if (newState != _inCallTransmitting && newState != _inCallRequestingFloor)
                    {
                        _mediaClient.StopSendingAudio();
                        _beepPlayer.PlayDenied();
                    }
                }
            };
            _inCallRequestingFloor.AddTransition(EventId.RegistrationResponseReceived, () => _inCallReleasingFloor !);
            _inCallRequestingFloor.AddTransition(EventId.CallRequest, () => _inCallReleasingFloor !);
            _inCallRequestingFloor.AddTransition(EventId.CallStartFailed, () => _registered);
            _inCallRequestingFloor.AddTransition(EventId.PttDown, () => _inCallRequestingFloor);
            _inCallRequestingFloor.AddTransition(EventId.PttUp, () => _inCallIdle);
            _inCallRequestingFloor.AddTransition(EventId.GroupSelected, () => _inCallRequestingFloor);
            _stateManager.AddState(_inCallRequestingFloor);

            //in call releasing floor
            _inCallReleasingFloor = new RopuState(StateId.InCallReleasingFloor)
            {
                Entry = async token =>
                {
                    if (_callGroup == null)
                    {
                        throw new InvalidOperationException("No call group");
                    }
                    if (_clientSettings.UserId == null)
                    {
                        throw new InvalidOperationException("UserId is not set");
                    }
                    while (!token.IsCancellationRequested)
                    {
                        _servingNodeClient.SendFloorReleased(_callGroup.Value, _clientSettings.UserId.Value);
                        await Task.Run(() => token.WaitHandle.WaitOne(1000));
                    }
                }
            };
            _inCallReleasingFloor.AddTransition(EventId.FloorGranted, () => _inCallReleasingFloor);
            _inCallReleasingFloor.AddTransition(EventId.RegistrationResponseReceived, () => _inCallReleasingFloor);
            _inCallReleasingFloor.AddTransition(EventId.CallRequest, () => _inCallReleasingFloor);
            _inCallReleasingFloor.AddTransition(EventId.CallStartFailed, () => _registered);
            _inCallReleasingFloor.AddTransition(EventId.PttDown, () => _inCallRequestingFloor);
            _inCallReleasingFloor.AddTransition(EventId.PttUp, () => _inCallReleasingFloor);
            _inCallReleasingFloor.AddTransition(EventId.GroupSelected, () => _inCallReleasingFloor);

            _stateManager.AddState(_inCallReleasingFloor);


            _inCallReleasingFloor.AddTransition(EventId.FloorGranted, () => _inCallReleasingFloor);


            _stateManager.StateChanged += (sender, args) =>
            {
                Console.WriteLine($"State Changed {this._stateManager.CurrentState}");
                StateChanged?.Invoke(this, args);
            };

            _stateManager.AddTransitionToAll(EventId.HeartbeatFailed, () => _unregistered, stateId => true);
            _stateManager.AddTransitionToAll(EventId.NotRegistered, () => _unregistered, stateId => true);
            _stateManager.AddTransitionToAll(EventId.CallEnded, () => _registered, stateId => stateId != StateId.Unregistered && stateId != StateId.Start && stateId != StateId.Deregistering);
            _stateManager.AddTransitionToAll(EventId.FloorIdle, () => _inCallIdle, IsRegistered);
            _stateManager.AddTransitionToAll(EventId.FloorTaken, () => _inCallReceiveing, IsRegistered);
            _stateManager.AddTransitionToAll(EventId.FloorGranted, () => _inCallTransmitting, stateId => stateId != StateId.InCallReleasingFloor);
            _stateManager.AddTransitionToAll(EventId.DeregistrationResponseReceived, () => _unregistered, stateId => true);
            _stateManager.AddTransitionToAll(EventId.GroupDeselected, () => _noGroup, stateId => true);

            _stateManager.CheckEventsAreHandledByAll((EventId[])Enum.GetValues(typeof(EventId)));
        }
예제 #29
0
파일: Program.cs 프로젝트: trampster/Ropu
        static void Main(string[] args)
        {
            const ushort controlPortStarting = 5061;

            var settingsManager = new CommandLineClientSettingsReader();

            if (!settingsManager.ParseArgs(args))
            {
                return;
            }

            var settings = settingsManager.ClientSettings;

            var webClient = new RopuWebClient("https://192.168.1.9:5001/", settingsManager);

            var keysClient       = new KeysClient(webClient, false, encryptionKey => new CachedEncryptionKey(encryptionKey, key => new AesGcmWrapper(key)));
            var packetEncryption = new PacketEncryption(keysClient);

            var protocolSwitch    = new ProtocolSwitch(controlPortStarting, new PortFinder(), packetEncryption, keysClient, settings);
            var servingNodeClient = new ServingNodeClient(protocolSwitch);

            IAudioSource audioSource =
                settings.FileMediaSource != null ?
                (IAudioSource) new FileAudioSource(settings.FileMediaSource) :
                (IAudioSource) new PulseAudioSimple(StreamDirection.Record, "RopuInput");

            var audioPlayer            = new PulseAudioSimple(StreamDirection.Playback, "RopuOutput");
            var audioCodec             = new OpusCodec();
            var jitterBuffer           = new AdaptiveJitterBuffer(2, 50);
            var mediaClient            = new MediaClient(protocolSwitch, audioSource, audioPlayer, audioCodec, jitterBuffer, settings);
            var callManagementProtocol = new LoadBalancerProtocol(new PortFinder(), 5079, packetEncryption, keysClient);

            var beepPlayer = new BeepPlayer(new PulseAudioSimple(StreamDirection.Playback, "RopuBeeps"));


            var ropuClient = new RopuClient(protocolSwitch, servingNodeClient, mediaClient, callManagementProtocol, settings, beepPlayer, webClient, keysClient);

            var application = new RopuApplication(ropuClient);

            var imageService = new ImageService();

            //TODO: get web address from config
            var imageClient  = new ImageClient(webClient);
            var groupsClient = new GroupsClient(webClient, imageClient);
            var usersClient  = new UsersClient(webClient);
            //settings.UserId = usersClient.GetCurrentUser().Result.Id;
            var pttPage = new PttPage(imageService);

            var navigator = new Navigator();

            var colorService = new ColorService();

            navigator.Register <LoginViewModel, LoginView>(() => new LoginView(new LoginViewModel(navigator, webClient, settingsManager), imageService));

            navigator.Register <SignupViewModel, SignupPage>(() => new SignupPage(new SignupViewModel(navigator, usersClient), imageService));

            Action <Func <Task> > invoke = toDo => Application.Instance.Invoke(toDo);

            var permissionServices = new PermissionServices();

            var pttView = new PttView(new PttViewModel <Color>(ropuClient, settingsManager, groupsClient, usersClient, imageClient, colorService, invoke, permissionServices, webClient, navigator), pttPage);

            navigator.Register <PttViewModel <Color>, PttView>(() => pttView);
            navigator.RegisterView("HomeRightPanel", "PttView", () => pttView);


            var homeView = new HomeView(new HomeViewModel(navigator), navigator, colorService);

            navigator.Register <HomeViewModel, HomeView>(() => homeView);

            var browseGroupsView = new BrowseGroupsView(new BrowseGroupsViewModel(groupsClient, navigator));

            navigator.Register <BrowseGroupsViewModel, BrowseGroupsView>(() => browseGroupsView);

            Func <Group, BrowseGroupView> browseGroupViewBuilder = group => new BrowseGroupView(new BrowseGroupViewModel(group, groupsClient, settings, navigator), imageService, navigator, colorService);

            navigator.Register <BrowseGroupViewModel, BrowseGroupView, Group>(group => browseGroupViewBuilder(group));

            var selectIdleGroupView = new SelectIdleGroupView(new SelectGroupViewModel(groupsClient, navigator, ropuClient));

            navigator.RegisterView("HomeRightPanel", "SelectIdleGroupView", () => selectIdleGroupView);

            var mainForm = new MainView(navigator, new MainViewModel(settings, navigator));

            mainForm.Icon = imageService.Ropu;

            var ignore = navigator.ShowModal <HomeViewModel>();

            ignore = navigator.ShowPttView();
            application.Run(mainForm);
        }